The classical Sieve of Eratosthenes algorithm takes O(N log (log N)) time to find all prime numbers less than N. In this article, a modified Sieve is discussed that works in O(N) time.
Given a number N, print all prime numbers smaller than N Input : int N = 15 Output : 2 3 5 7 11 13 Input : int N = 20 Output : 2 3 5 7 11 13 17 19
Manipulated Sieve of Eratosthenes algorithm works as following:
For every number i where i varies from 2 to N-1: Check if the number is prime. If the number is prime, store it in prime array. For every prime numbers j less than or equal to the smallest prime factor p of i: Mark all numbers j*p as non_prime. Mark smallest prime factor of j*p as j
Below is implementation of above idea.
2 3 5 7 11
isPrime = isPrime = 0 After i = 2 iteration : isPrime [F, F, T, T, F, T, T, T] SPF [0, 0, 2, 0, 2, 0, 0, 0] index 0 1 2 3 4 5 6 7 After i = 3 iteration : isPrime [F, F, T, T, F, T, F, T, T, F ] SPF [0, 0, 2, 3, 2, 0, 2, 0, 0, 3 ] index 0 1 2 3 4 5 6 7 8 9 After i = 4 iteration : isPrime [F, F, T, T, F, T, F, T, F, F] SPF [0, 0, 2, 3, 2, 0, 2, 0, 2, 3] index 0 1 2 3 4 5 6 7 8 9
This article is contributed by Divyanshu Srivastava and Nishant Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- How is the time complexity of Sieve of Eratosthenes is n*log(log(n))?
- Sieve of Eratosthenes
- Sum of all Primes in a given range using Sieve of Eratosthenes
- Check for balanced parentheses in an expression | O(1) space | O(N^2) time complexity
- Segmented Sieve (Print Primes in a Range)
- Sieve of Sundaram to print all primes smaller than n
- Sieve of Atkin
- Prime Factorization using Sieve O(log n) for multiple queries
- Bitwise Sieve
- Number of unmarked integers in a special sieve
- Longest sub-array of Prime Numbers using Segmented Sieve
- Segmented Sieve
- Sum of first n odd numbers in O(1) Complexity
- Complexity Analysis of Binary Search
- Minimum time to reach a point with +t and -t moves at time t
- Space and time efficient Binomial Coefficient
- To Generate a One Time Password or Unique Identification URL
- MakeMyTrip Interview Experience | Set 13 (On-Campus for Full Time)
- Find the largest multiple of 3 from array of digits | Set 2 (In O(n) time and O(1) space)
- Find Index of given fibonacci number in constant time