 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Prime Triplet in C++
In this problem, we are given a number N. Our task is to print all prime triplets less than N.
Prime triplet is a set of three prime numbers. That are of the form (p, p+2, p+6) or (p, p+4, p+6). All prime numbers are grouped according to the above triplets as every third prime in the direct pattern is a multiple of 6.
Let’s see an example to understand the problem
Input: N = 13 Output: 5 7 11
To solve this problem, we have to find all prime numbers less than equal to N. And the check for triplets.
The code to show the implementation of our solution,
Example
#include <bits/stdc++.h> using namespace std; void findPrimes(int n, bool prime[]) {    for (int p = 2; p * p <= n; p++) {       if (prime[p] == true) {          for (int i = p * 2; i <= n; i += p)          prime[i] = false;       }    } } void printPrimeTriplets(int n) {    bool prime[n + 1];    memset(prime, true, sizeof(prime));    findPrimes(n, prime);    for (int i = 2; i <= n-6; ++i) {       if (prime[i] && prime[i + 2] && prime[i + 6])          cout<<i<<"\t"<<(i+2)<<"\t"<<(i+6)<<endl;       else if (prime[i] && prime[i + 4] && prime[i + 6])          cout<<i <<"\t"<<(i + 4)<<"\t"<<(i + 6)<<endl;    } } int main() {    int N = 15;    cout<<"Prime Triplets Less than "<<N<<" are :\n";    printPrimeTriplets(N);    return 0; }  Output
Prime Triplets Less than 15 are : 5 7 11 7 11 13
Advertisements
 