Solved Problem - Segmented Sieve
In this lesson, we'll discuss how to implement the segmented Sieve: a very popular variation of sieve.
We'll cover the following
Problem statement
Given two integers, and , print all primes between and (both inclusive).
Input format
The only line of input contains two integers and .
Sample
Input
100000000 100000100
Output
100000007 100000037 100000039 100000049 100000073 100000081
Sieve
Obviously, Sieve of Eratosthenes comes to mind. Now, two things don’t work right here:
- , we don’t have enough memory to declare an array of a billion integers (4 GB memory).
- Even if we could declare an array that big, the time complexity would be , which is obviously very slow.
Observation:
Segmented sieve
Since the range in which we want the generate the primes is at max , we can run a modified version of sieve on a Boolean array of size such that.
- - denotes whether is prime or not.
- - denotes whether is prime or not.
- …
- - denotes whether is prime or not.
Marking multiples not-prime
Comparing to sieve where we iterate up to and if the current number is prime, we mark its multiples not-prime.
Here, we will iterate up to , but if the number doesn’t belong in the range , we don’t know if it’s a prime or not. So, in this case, we will mark multiples not-prime for all the numbers in .
We only need to mark the multiples if the multiple is between and . To do this, we start with the first multiple of this number that is greater than or equal to .
First multiplex of just greater than or equal to can be calculated as follow:
Get hands-on with 1400+ tech skills courses.