Given a number n, print all primes smaller than n. For example, if the given number is 10, output 2, 3, 5, 7.
A Naive approach is to run a loop from 0 to n-1 and check each number for primeness. A Better Approach is use Simple Sieve of Eratosthenes.
Problems with Simple Sieve:
The Sieve of Eratosthenes looks good, but consider the situation when n is large, the Simple Sieve faces following issues.
- An array of size Θ(n) may not fit in memory
- The simple Sieve is not cache friendly even for slightly bigger n. The algorithm traverses the array without locality of reference
The idea of segmented sieve is to divide the range [0..n-1] in different segments and compute primes in all segments one by one. This algorithm first uses Simple Sieve to find primes smaller than or equal to √(n). Below are steps used in Segmented Sieve.
- Use Simple Sieve to find all primes upto square root of ‘n’ and store these primes in an array “prime”. Store the found primes in an array ‘prime’.
- We need all primes in range [0..n-1]. We divide this range in different segments such that size of every segment is at-most √n
- Do following for every segment [low..high]
- Create an array mark[high-low+1]. Here we need only O(x) space where x is number of elements in given range.
- Iterate through all primes found in step 1. For every prime, mark its multiples in given range [low..high].
In Simple Sieve, we needed O(n) space which may not be feasible for large n. Here we need O(√n) space and we process smaller ranges at a time (locality of reference)
Below is implementation of above idea.
Primes smaller than 100: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
Note that time complexity (or number of operations) by Segmented Sieve is same as Simple Sieve. It has advantages for large ‘n’ as it has better locality of reference and requires
This article is contributed by Utkarsh Trivedi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- Segmented Sieve (Print Primes in a Range)
- Sieve of Eratosthenes
- Sieve of Atkin
- Bitwise Sieve
- Sum of all Primes in a given range using Sieve of Eratosthenes
- Sieve of Eratosthenes in 0(n) time complexity
- Sieve of Sundaram to print all primes smaller than n
- Number of unmarked integers in a special sieve
- Prime Factorization using Sieve O(log n) for multiple queries
- Count the number of special permutations
- Find numbers a and b that satisfy the given conditions
- Check if number can be displayed using seven segment led
- Check if the sum of primes is divisible by any prime from the array
- Count numbers upto N which are both perfect square and perfect cube