Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

160
Vistas
Determine a prime number function

Could anyone explain to me the 2nd and 3rd statement in the for loop

What is the 1st and 2nd i in the middle part and the last one (i = i + 6)

function prime(n) {
  if (n <= 1) return false;
  if (n <= 3) return true;

  if (n % 2 == 0 || n % 3 == 0) return false
  for (let i = 5; i * i <= n; i = i + 6) {
    if (n % i == 0 || n % (i + 2) == 0)

      return false;
  }
  return true
}

console.log(prime(11))
console.log(prime(25))
console.log(prime(29))

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

There are a couple of hacks in this function to determine primality of a number n.

  1. Every non-prime number has at-least 1 factor less than or equal to its square root.
  2. Every 6th number from 3 onwards is a multiple of 3. So, if we have already checked that 3 does not divide n, we can safely say numbers like 9,15,21... will not divide n.

The if inside the loop checks for divisibility of n by i or i + 2. Since we know, 3 | i+4 (-- from 2 above), we don't check divisibility there as it is not required. And since this loop runs from i = 5 upto i = sqrt(n), if we find no factors, we can exit the loop and return true for number's primality (-- from 1 above)

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda