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 Eratosthenes’ method:
- Create a list of consecutive integers from 2 to n: (2, 3, 4, …, n).
- Initially, let p equal 2, the first prime number.
- Starting from p2, count up in increments of p and mark each of these numbers greater than or equal to p2 itself in the list. These numbers will be p(p+1), p(p+2), p(p+3), etc..
- Find the first number greater than p in the list that is not marked. If there was no such number, stop. Otherwise, let p now equal this number (which is the next prime), and repeat from step 3.
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 print numbers smaller than or equal to 50.
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.
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 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.
Following are the prime numbers below 30 2 3 5 7 11 13 17 19 23 29
Time complexity : O(n*log(log(n)))
This article is compiled by Abhinav Priyadarshi and reviewed by GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- Sum of all Primes in a given range using Sieve of Eratosthenes
- Sieve of Eratosthenes in 0(n) time complexity
- Segmented Sieve
- Sieve of Atkin
- Bitwise Sieve
- Number of unmarked integers in a special sieve
- Prime Factorization using Sieve O(log n) for multiple queries
- Sieve of Sundaram to print all primes smaller than n
- Segmented Sieve (Print Primes in a Range)
- Minimum number of Fibonacci jumps to reach end
- Count of integers in a range which have even number of odd digits and odd number of even digits
- Print all the permutation of length L using the elements of an array | Iterative
- Sum of N terms in the expansion of Arcsin(x)
- Minimize the cost of buying the Objects