
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C++ Program to Implement Sieve of eratosthenes to Generate Prime Numbers Between Given Range
The Sieve of Eratosthenes algorithm is one of the most efficient ways to find prime numbers smaller than n when n is smaller than around 10 million. It follows a simple process of marking the multiples of already prime numbers as false i.e. non-prime numbers.
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 the 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 Sieve of Eratosthenes algorithm 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++ Implementation of Sieve of Eratosthenes
Here is the C++ code implementing the above steps to implement Sieve of Eratosthenes algorithm.
#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 = 40; 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 31 37
Complexity of Sieve of Eratosthenes Algorithm
- Time Complexity: The time complexity of the Sieve of Eratosthenes algorithm is O(n log(logn)).
- Space Complexity: The space complexity of the Sieve of Eratosthenes algorithm is O(n).