Sieve of Eratosthenes
- Difficulty Level : Medium
- Last Updated : 07 Jun, 2022
Given a number n, print all primes smaller than or equal to n. It is also given that n is a small number.
Input : n =10
Output : 2 3 5 7
Input : n = 20
Output: 2 3 5 7 11 13 17 19
The sieve of Eratosthenes is one of the most efficient ways to find all primes smaller than n when n is smaller than 10 million or so (Ref Wiki).
Following is the algorithm to find all the prime numbers less than or equal to a given integer n by the Eratosthene’s method:
When the algorithm terminates, all the numbers in the list that are not marked are prime.
Explanation with Example:
Let us take an example when n = 50. So we need to print all prime numbers smaller than or equal to 50.
We create a list of all numbers from 2 to 50.
According to the algorithm we will mark all the numbers which are divisible by 2 and are greater than or equal to the square of it.
Now we move to our next unmarked number 3 and mark all the numbers which are multiples of 3 and are greater than or equal to the square of it.
We move to our next unmarked number 5 and mark all multiples of 5 and are greater than or equal to the square of it.
We continue this process and our final table will look like below:
So the prime numbers are the unmarked ones: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47.
Thanks to Krishan Kumar for providing the above explanation.
Following is the implementation of the above algorithm. In the following implementation, a boolean array arr of size n is used to mark multiples of prime numbers.
Time Complexity: O(n*log(log(n)))
Auxiliary Space: O(n)
You may also like to see :
- How is the time complexity of Sieve of Eratosthenes is n*log(log(n))?
- Segmented Sieve.
- Sieve of Eratosthenes in 0(n) time complexity
Auxiliary Space: O(1)