Fastest Algorithm to Find Prime Numbers Using C++



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

In this article, we have a given number as 'num'. Our task is to find all the prime numbers less than or equal to num using Sieve of Eratosthenes algorithm in C++.

Example

Here is an example to find prime numbers less than 10:

Input:
num = 10

Output:
2 3 5 7

The explanation of the above example is as follows:

Numbers: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

i = 2 = Prime number
After removing all multiples of 2:
2, 3, 5, 7, 9

i = 3 = Prime number
After removing all multiples of 3:
2, 3, 5, 7

Prime numbers: 2, 3, 5, 7

Steps to Implement Sieve of Eratosthenes

Here are the steps to implement the fastest algorithm i.e. Sieve of Eratosthenes to find the the prime numbers:

  • We have defined a prime() function that accepts the given number num as argument.
  • We have initialized the first two elements as false i.e. '0' and '1' are not prime numbers.
  • Then we check if the current element 'i' is prime or not. If it is prime, then we mark their multiples as not prime.
  • Then we have returned all the prime numbers using the second for loop.

C++ Program to Sieve of Eratosthenes to Find Prime Numbers

Here is the C++ code for implementing the fastest algorithm to find the prime numbers Using the Sieve of Eratosthenes:

Open Compiler
#include <bits/stdc++.h> using namespace std; void prime(int num) { vector<bool> pno(num + 1, true); pno[0] = pno[1] = false; for (int i = 2; i * i <= num; i++) { if (pno[i]) { for (int j = i * i; j <= num; j += i) pno[j] = false; } } for (int i = 2; i <= num; i++) { if (pno[i]) cout << i << " "; } } int main() { int num = 30; cout << "The prime numbers upto " << num << " are: "; prime(num); return 0; }

The output of the above code is:

The prime numbers upto 30 are: 2 3 5 7 11 13 17 19 23 29

Time and Space Complexity

The time complexity of the Sieve of Eratosthenes algorithm is O(n log(logn)). The space complexity is O(n).

Updated on: 2025-05-02T13:17:12+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements