How do I find the nearest prime number?

Marty picture Marty · Oct 15, 2009 · Viewed 26.6k times · Source

Is there any nice algorithm to find the nearest prime number to a given real number? I only need to search within the first 100 primes or so.

At present, I've a bunch of prime numbers stored in an array and I'm checking the difference one number at a time (O(n)?).

Answer

mjv picture mjv · Oct 15, 2009

Rather than a sorted list of primes, given the relatively small range targetted, have an array indexed by all the odd numbers in the range (you know there are no even primes except the special case of 2) and containing the closest prime. Finding the solution becomes O(1) time-wise.

I think the 100th prime is circa 541. an array of 270 [small] ints is all that is needed.

This approach is particularly valid, given the relative high density of primes (in particular relative to odd numbers), in the range below 1,000. (As this affects the size of a binary tree)