Closest prime number
HardBasics15 min
Write a function closestPrime(n) that returns the prime number closest to the integer n.
- A prime number is a whole number greater than 1 that can be divided evenly only by 1 and by itself: 2, 3, 5, 7, 11, 13 and so on. 1 is not a prime number. "Divided evenly" means the remainder
x % iis 0. nis an integer from -1000 to 1000000. It can be 0, 1 or negative.- If
nis prime, returnnitself. - The distance between two numbers is the absolute value of their difference. Return the prime with the smallest distance to
n. - If two primes are equally close, return the smaller one:
12gives11, not13. - For every
nthat is 2 or less the answer is 2. - Return a number, do not print it.
A simple loop over the numbers around n is enough.
Examples
closestPrime(10)Returns 11
closestPrime(12)Returns 11
closestPrime(-5)Returns 2
Asked at Amazon · Source
Loading the editor...
- Input
closestPrime(10)Expected11 - Input
closestPrime(12)Expected11 - Input
closestPrime(13)Expected13
Hidden tests run on Submit