Code Lab

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 % i is 0.
  • n is an integer from -1000 to 1000000. It can be 0, 1 or negative.
  • If n is prime, return n itself.
  • 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: 12 gives 11, not 13.
  • For every n that 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

11 and 13 are both at distance 1, so the smaller one wins.
closestPrime(-5)

Returns 2

Asked at Amazon · Source

Loading the editor...
  1. InputclosestPrime(10)
    Expected11
  2. InputclosestPrime(12)
    Expected11
  3. InputclosestPrime(13)
    Expected13

Hidden tests run on Submit.