# Print all safe primes below N in C++

In this problem, we are given an integer N and we have to print all safe prime number whose values are less than N.

A safe prime number is a prime number which can be represented as [(2*p)- 1] where p is also a prime number.

Examples − 5[(2*2) +1] , 7[(2*3)+1].

Let’s take a few examples to understand the problem better −

Input: N = 12
Output: 5 7 11.

To solve this problem, we will find all the prime numbers less than N(for this we will use Sieve of Eratosthenes). And check if the prime number is a safe prime number or not and print if it is a safe prime number.

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
void printPrime(int n){
cout<<n<<"\t";
}
void generateSafePrimes(int n){
int prime[n + 1];
for (int i = 2; i <= n; i++)
prime[i] = 1;
prime[0] = prime[1] = 0;
for (int p = 2; p * p <= n; p++) {
if (prime[p] == 1) {
for (int i = p * 2; i <= n; i += p)
prime[i] = 0;
}
}
for (int i = 2; i <= n; i++) {
if (prime[i] != 0) {
int temp = (2 * i) + 1;
if (temp <= n && prime[temp] != 0)
prime[temp] = 2;
}
}
for (int i = 5; i <= n; i++)
if (prime[i] == 2)
printPrime(i);
}
// Driver code
int main(){
int n = 34;
cout<<"safe Prime numbers less than "<<n<<" are :\n";
generateSafePrimes(n);
return 0;
}

## Output

Safe Prime numbers less than 34 are −

5 7 11 23