
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
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
Print All Prime Quadruplets of a Number Less Than It in C++
In this problem, we are given a positive integer N, and we have to print all prime quadruplet less than or equal to n.
Prime quadruplets are the set of four prime numbers calculated as {p, p+2, p+6, p+8}. Example − 5 7 11 13.
Let’s take an example to understand the problem −
Input: N = 15 Output: 5 7 11 13.
To solve this problem, a simple approach is to generate all quadruplets of prime number p and check if all p, p+2, p+6, p+8 are prime numbers. This solution is easy but is more complex for the compiler.
Another efficient approach is to fond all prime numbers (using the sieve of Eratosthenes) and store them in an array up to a certain range. And traverse the array and check p, p+2, p+6, p+8 are prime or not and print if they all are prime.
Example
#include <bits/stdc++.h> using namespace std; #define MAX 100000 bool prime[MAX]; void primeNumberGenerator() { memset(prime, true, sizeof(prime)); for (int p = 2; p * p < MAX; p++) { if (prime[p] == true) { for (int i = p * 2; i < MAX; i += p) prime[i] = false; } } } void printPrimeQuadruplet(int n) { for (int i = 0; i < n - 7; i++) { if (prime[i] && prime[i + 2] && prime[i + 6] && prime[i + 8]) { cout<<i<<" "<<i+2<<" "<<i+6<<" "<<i+8<<endl; } } } int main() { primeNumberGenerator(); int n = 42; cout<<"All prime Quadruplets are :\n"; printPrimeQuadruplet(20); return 0; }
Output
All prime Quadruplets are −
5 7 11 13 11 13 17 19
Advertisements