Code Lab

Mode entretien. Minuteur de 15 min, sans indices ni autocomplétion

Closest prime number

DifficileBasics15 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.

Exemples

closestPrime(10)

Renvoie 11

closestPrime(12)

Renvoie 11

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

Renvoie 2

Posé chez Amazon · Source

Chargement de l'éditeur...
  1. EntréeclosestPrime(10)
    Attendu11
  2. EntréeclosestPrime(12)
    Attendu11
  3. EntréeclosestPrime(13)
    Attendu13

Les tests cachés se lancent à la soumission