Sieve of Eratosthenes
What is Sieve of Eratosthenes?
Sieve of Eratosthenes is an ancient algorithm of finding prime numbers for any given range. It's actually about maintaining a Boolean table to check for corresponding prime no.
Algorithm
The algorithm is pretty simple.
- Say, we need information up to integer N.
- Create a table of size N+1, sieve[N+1]
- Assign all the table entries TRUE initially.
- Base case:
0 and 1 is not prime
Thus sieve[0]=FALSE=sieve[1]
-
For(i=2; i*i<=N; i=i+1)
IF(sieve[i] is TRUE) //i is prime
Make all multiple ofi FALSE since they are not prime
sieve[j]=FALSE where j is multiple of i within range N
END IF
END FOR
- Table is built. Now to check any integer K whether prime or not
Return sieve[k]
Let's say our range is up to 20 Thus initially declare sieve[21] and all are true. sieve[0]=FALSE sieve[1]=FALSE ------------------------------------------------------------ sieve[2]=true Thus all multiple of 2, needed to be false (Of course they are not prime since divisible by 2) Thus, sieve[4]=FALSE sieve[6]=FALSE sieve[8]=FALSE sieve[10]=FALSE sieve[12]=FALSE sieve[14]=FALSE sieve[16]=FALSE sieve[18]=FALSE sieve[20]=FALSE ------------------------------------------------------------ sieve[3]=true Thus all multiple of 3, needed to be false (Of course they are not prime since divisible by 3) Thus, sieve[6]=FALSE (it was already false though) sieve[9]=FALSE sieve[12]=FALSE(it was already false though) sieve[15]=FALSE sieve[18]=FALSE(it was already false though) ------------------------------------------------------------ Sieve[4]=FALSE (Nothing to do more with it) ------------------------------------------------------------ sieve[5]=TRUE Thus all multiple of 5, needed to be false (Of course they are not prime since divisible by 5) Thus, sieve[10]=FALSE (it was already false though) sieve[15]=FALSE (it was already false though) sieve[20]=FALSE (it was already false though) In this way, after completing all possible entries we can find Only true entries are sieve[2] sieve[3] sieve[5] sieve[7] sieve[11] sieve[13] sieve[17] sieve[19] Others are false.So now for any given number with in the N
We can tell whether the number is prime or not in O(1) time (based on corresponding TRUE/FALSE value).
When to use this algorithm in programming?
Sieve of Eratosthenes can be very efficient for any program we require to check prime numbers for multiple times (Multiple test cases too).
In such cases, we construct the Sieve of Eratosthenes only single time and for all query each only takes O(1) time reducing the time complexity overall.
C++ implementation:
Output
need an explanation for this answer? contact us directly to get an explanation for this answer