Find The Nearest Prime
August 25, 2017
I’ve seen this problem several times on Stack Overflow and other message boards:
Write a program to find the nearest prime number to a given real number. You may limit the search to the hundred smallest primes.
Your task is to write the program to find the nearest prime number. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
In Python. This function returns the last prime, if x > last prime. bisect_left is from the bisect module.
I’m glad to see you providing a pragmatic solution. To be even more pragmatic, though, I’d just Google up a list of primes and copy and paste the first hundred of them.
Implementation in Julia. If it doesn’t look right for some reason, let me know and I’ll post a screenshot instead.
global P = primes(1000)[1:100] # first 100 primes
function NearestPrime(x::Int64)
if x > P[end]
return P[end]
else
d = abs(P – x)
return P[indmin(d)]
end
end
Quite a nifty little problem. It would be more of a challenge if the scope of it were larger though. Thanks
@Zack: I’m not familiar with Julia. Is `primes` a built-in function? Or part of the standard library? Does Julia provide integer factorization?
An alternative solution using a lazy prime generator. Generate primes until the distance between the pime and target increases.