I remember solving the problem like this:
- Use the sieve of eratosthenes to generate all primes below
sqrt(1000000000) = ~32 000
in an array primes
.
- For each number
x
between m
and n
only test if it's prime by testing for divisibility against numbers <= sqrt(x)
from the array primes
. So for x = 29
you will only test if it's divisibile by 2, 3 and 5
.
There's no point in checking for divisibility against non-primes, since if x divisible by non-prime y
, then there exists a prime p < y
such that x divisible by p
, since we can write y
as a product of primes. For example, 12
is divisible by 6
, but 6 = 2 * 3
, which means that 12
is also divisible by 2
or 3
. By generating all the needed primes in advance (there are very few in this case), you significantly reduce the time needed for the actual primality testing.
This will get accepted and doesn't require any optimization or modification to the sieve, and it's a pretty clean implementation.
You can do it faster by generalising the sieve to generate primes in an interval [left, right]
, not [2, right]
like it's usually presented in tutorials and textbooks. This can get pretty ugly however, and it's not needed. But if anyone is interested, see:
http://pastie.org/9199654 and this linked answer.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…