![]() |
VOOZH | about |
Given a number n, print all primes smaller than n.
Input: N = 10
Output: 2, 3, 5, 7
Explanation : The output β2, 3, 5, 7β for input N = 10 represents the list of the prime numbers less than or equal to 10.
Input: N = 5
Output: 2, 3, 5
Explanation : The output β2, 3, 5β for input N = 5 represents the list of the prime numbers less than or equal to 5.
A Naive approach is to run a loop from 0 to n-1 and check each number for primeness. A Better Approach is to 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 the following issues.
Segmented Sieve
The idea of a 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.
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 the implementation of the 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
Time Complexity : O(n * ln(sqrt(n)))
Auxiliary Space: O(sqrt(n))
Note that time complexity (or a number of operations) by Segmented Sieve is the same as Simple Sieve. It has advantages for large 'n' as it has better locality of reference thus allowing better caching by the CPU and also requires less memory space.