Alternate Primes till N in C++?

Here we will see how to print all alternate prime numbers till N. The alternate prime numbers are like below. Suppose N = 15. So the prime numbers till N are {2, 3, 5, 7, 11, 13}. The alternate prime numbers are {2, 5, 11}. Let us see how we can solve this problem.

Algorithm

printAlternatePrime(N)

Begin
define one Boolean array prime of size N + 1, and fill with 1.
for p := 2, p^2 is less than N, increase p by 1, do
if prime[p] is true, then
for all multiples of p, make the position 0 in prime array
end if
done
set the flag
for p := 2 to n, do
if prime[p] is true, then
if flag is set, then
print p, and reset the flag
else
set the flag
end if
end if
done
End

Example

Live Demo

#include<iostream>
using namespace std;
void printAlternatePrime(int n) {
bool prime[n + 1];
for(int i = 0; i<=n; i++) {
prime[i] = true;
}
for (int p = 2; p * p <= n; p++) {
if (prime[p]) {
for (int i = p * 2; i <= n; i += p) //all multiples will be false
prime[i] = false;
}
}
bool prime_flag = true;
for (int p = 2; p <= n; p++) {
if (prime[p]) {
if (prime_flag) {
cout << p << " ";
prime_flag = false;
} else {
prime_flag = true; //set to print next prime
}
}
}
}
main() {
int n;
cout << "Enter upper limit: ";
cin >> n;
cout << "Alternate prime numbers are: ";
printAlternatePrime(n);
}

Output

Enter upper limit: 20
Alternate prime numbers are: 2 5 11 17

Updated on: 30-Jul-2019

883 Views