16,000,909 members
See more:
progran to find nearestprime nomber
Posted
Updated 26-Oct-11 11:02am
v3
Sergey Alexandrovich Kryukov 26-Oct-11 12:28pm
Any questions?
--SA
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.

## Solution 1

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

v4