Click here to Skip to main content
15,794,633 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
progran to find nearestprime nomber
Updated 26-Oct-11 12:02pm
Sergey Alexandrovich Kryukov 26-Oct-11 12:28pm    
Any questions?
Chuck O'Toole 26-Oct-11 12:48pm    
What has Code Project become? There's been a rash of folks who just sign up one day and then start writing posts about giving them complete code solutions to the most basic Computer Science 1 homework. Like this dude. Doesn't anybody read the guidelines anymore? Are these the kind of people who are going to define the software industry for the future? Or is this just a fad and these folks will have no prayer of working in the computer industry?
Richard MacCutchan 26-Oct-11 17:02pm    
I think (or rather hope) that they will not last long even if they do manage to find employment in the industry.

1 solution

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[^]


Share this answer
Espen Harlinn 2-Nov-11 17:04pm    
5'ed Manfred, quite educational :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900