|
| 1 | +// C++ program to print super primes less than or equal to n. |
| 2 | +#include <bits/stdc++.h> |
| 3 | +using namespace std; |
| 4 | + |
| 5 | +// Generate all prime numbers less than n. |
| 6 | +bool SieveOfEratosthenes(int n, bool isPrime[]) |
| 7 | +{ |
| 8 | + // Initialize all entries of boolean array as true. A |
| 9 | + // value in isPrime[i] will finally be false if i is Not |
| 10 | + // a prime, else true bool isPrime[n+1]; |
| 11 | + isPrime[0] = isPrime[1] = false; |
| 12 | + for (int i = 2; i <= n; i++) |
| 13 | + isPrime[i] = true; |
| 14 | + |
| 15 | + for (int p = 2; p * p <= n; p++) { |
| 16 | + // If isPrime[p] is not changed, then it is a prime |
| 17 | + if (isPrime[p] == true) { |
| 18 | + // Update all multiples of p |
| 19 | + for (int i = p * 2; i <= n; i += p) |
| 20 | + isPrime[i] = false; |
| 21 | + } |
| 22 | + } |
| 23 | +} |
| 24 | + |
| 25 | +// Prints all super primes less than or equal to n. |
| 26 | +void superPrimes(int n) |
| 27 | +{ |
| 28 | + // Generating primes using Sieve |
| 29 | + bool isPrime[n + 1]; |
| 30 | + SieveOfEratosthenes(n, isPrime); |
| 31 | + |
| 32 | + // Storing all the primes generated in a an array |
| 33 | + // primes[] |
| 34 | + int primes[n + 1], j = 0; |
| 35 | + for (int p = 2; p <= n; p++) |
| 36 | + if (isPrime[p]) |
| 37 | + primes[j++] = p; |
| 38 | + |
| 39 | + // Printing all those prime numbers that occupy prime |
| 40 | + // numbered position in sequence of prime numbers. |
| 41 | + for (int k = 0; k < j; k++) |
| 42 | + if (isPrime[k + 1]) |
| 43 | + cout << primes[k] << " "; |
| 44 | +} |
| 45 | + |
| 46 | +// Driven program |
| 47 | +int main() |
| 48 | +{ |
| 49 | + int n = 241; |
| 50 | + cout << "Super-Primes less than or equal to " << n |
| 51 | + << " are :" << endl; |
| 52 | + superPrimes(n); |
| 53 | + return 0; |
| 54 | +} |
| 55 | + |
| 56 | + |
0 commit comments