Problem 241
Count Primes in a Range
Hard · 30 pts · Math, Number Theory
Problem
You are given two integers L and R. Count the prime numbers P with L <= P <= R. R can be as large as 10^12, but the range is short: R - L is at most one million. A normal sieve up to 10^12 is impossible. Use a segmented sieve: first find all primes up to the square root of R (at most 10^6) with an ordinary sieve. Then, in a boolean array covering only L to R, cross out the multiples of each of these primes. Remember that 1 is not prime. The numbers in this problem can be larger than a 32-bit int can hold (about 2.1 × 10^9), so use a 64-bit integer type: long long in C++, long in Java (Python needs nothing special).
Input
Two integers L and R.
Output
Print the number of primes in [L, R].
Constraints
1 <= L <= R <= 10^12; R - L <= 1000000
Example input
10 30
Example output
6
Explanation
Between 10 and 30, the primes are 11, 13, 17, 19, 23 and 29. All other numbers in the range have a smaller divisor, so the answer is 6.