# Which is the fastest algorithm to find prime numbers using C++?

C++ProgrammingServer Side Programming

The Sieve of Eratosthenes is one of the most efficient ways to find the prime numbers smaller than n when n is smaller than around 10 million.

A program that demonstrates the Sieve of Eratosthenes is given as follows.

## Example

#include <bits/stdc++.h>
using namespace std;
void SieveOfEratosthenes(int num) {
bool pno[num+1];
memset(pno, true, sizeof(pno));
for (int i = 2; i*i< = num; i++) {
if (pno[i] == true) {
for (int j = i*2; j< = num; j + = i)
pno[j] = false;
}
}
for (int i = 2; i< = num; i++)
if (pno[i])
cout << i << " ";
}
int main() {
int num = 15;
cout << "The prime numbers smaller or equal to "<< num <<" are: ";
SieveOfEratosthenes(num);
return 0;
}

## Output

The output of the above program is as follows.

The prime numbers smaller or equal to 15 are: 2 3 5 7 11 13

Now, let us understand the above program.

The function SieveOfEratosthenes() finds all the prime numbers that occur before num that is provided as argument. The code snippet for this is given as follows.

void SieveOfEratosthenes(int num) {
bool pno[num+1];
memset(pno, true, sizeof(pno));
for (int i = 2; i*i< = num; i++) {
if (pno[i] == true) {
for (int j = i*2; j< = num; j + = i)
pno[j] = false;
}
}
for (int i = 2; i< = num; i++)
if (pno[i])
cout << i << " ";
}

The function main() sets the value of num and then prints all the prime numbers that are smaller or equal to num. This is done by calling the function SieveOfEratosthenes(). The code snippet for this is given as follows.

int main() {
int num = 15;
cout << "The prime numbers smaller or equal to "<< num <<" are: ";
SieveOfEratosthenes(num);
return 0;
}
Published on 21-Nov-2018 16:57:01