Skip to content
BytePatterns

Primes in a Wide Range

HardMath & Number Theory#segmented-sieve#sieve~40m

Problem

Count the primes p with lo ≤ p ≤ hi. The bounds can be as large as 10^12, far too large to sieve from 1, but the window itself is narrow: hi minus lo is at most 10^6. Values below 2 inside the window are not prime and simply do not count.

Examples

Input:  lo = 10, hi = 30
Output: 6
Why:    11, 13, 17, 19, 23 and 29
Input:  lo = 1000000000000, hi = 1000000001000
Output: 37
Why:    only the 1,001 values of the window are sieved, not the trillion below them
Input:  lo = 14, hi = 16
Output: 0
Why:    edge case, a window with no primes in it

Hints

0 / 3

Stuck on the idea rather than the code? Sieve of Eratosthenes covers it.