Search⌘ K

Solved Problem - Segmented Sieve

Understand how to implement the segmented sieve algorithm to efficiently find all prime numbers between given large integers. This lesson explains the problem constraints, why the standard sieve is inefficient, and guides you through the time and memory optimized approach for ranges up to 10^9 with difference up to 10^6.

Problem statement

Given two integers, NN and MM, print all primes between NN and MM (both inclusive).

Input format

The only line of input contains two integers NN and MM (1NM109)(MN106)(1 \leq N \leq M \leq 10^9)( M-N \leq 10^6).


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:

  1. M<=109M <= 10^9, we don’t have enough memory to declare an array of a billion integers (4 GB memory).
  2. Even if we could declare an array that big, the time complexity would be O(Mlog(logM))O(M*log(logM)), which is obviously very slow.

Observation: MN<=106M - N <= 10^6


Segmented sieve

Since ...