Code Lab

Modo entrevista. Cronômetro de 15 min, sem dicas e sem autocompletar

Closest prime number

DifícilBasics15 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.

Exemplos

closestPrime(10)

Retorna 11

closestPrime(12)

Retorna 11

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

Retorna 2

Cobrada em Amazon · Fonte

Carregando o editor...
  1. EntradaclosestPrime(10)
    Esperado11
  2. EntradaclosestPrime(12)
    Esperado11
  3. EntradaclosestPrime(13)
    Esperado13

Os testes ocultos rodam no envio