Starting from a given integer
n
search the integers below
n
in descending fashion and the integers above
n
in ascending fashion. You will get two prime integers this way. Then you determine the distance from
n
to each of the primes:
distanceToBelow = n - primeBelowN
distanceToAbove = primeAboveN - n
result = primeAboveN
if(distanceToBelow <= distanceToAbove)
result = primeBelowN
Actually you'd always search downwards except for when n == 2 because the nearest prime below 2 is -2 with a distance of 4 compared to 3 with a distance of 1. Consider three consecutive primes X < Y < Z and figure out why with Y >=3 the nearest prime to Y is always X.
If you have trouble figuring out whether an integer is prime check my solution here:
Prime number program[
^]
Cheers!
—MRB