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

169
Vistas
Why is unshift() returning a different value than push() if I am targeting the first element in the former and the last element in the latter?

I have a function for Project Euler #7. Towards the end, I changed the code from primeArray.push(i); to primeArray.unshift(i) and return primeArray[primeArray.length - 1]; to return primeArray[0];. This altered the return. In the former. It returned the correct answer, 104021, while the latter returned 20001, which is not even prime. I do not understand why that is.

function primeFinder(primeTarget) {
  //since 2 is the only even prime, putting it here saves us some effort in checking primality by just iterating over the odd numbers
  //it also helps the for loop since we are only interested in checking for divisors among previous primes.
  let primeArray = [2];
  let i = 3;

  while (primeArray.length < primeTarget) {
    let primeLogger = false;
    //We don't need to check for divisibility by 2, so j can equal 1
    for (j = 1; j < primeArray.length && primeArray[j] < Math.sqrt(i); j++) {
      if (i % primeArray[j] === 0) {
        primeLogger = true;
        //Since we have found a divisor and changed primeLogger, we can exit the loop
        break;
      }
    }
    //Where the break goes to, and also where the for loop goes to once finishes
    if (primeLogger === false) {
      primeArray.push(i);
    }
    i += 2;
  }
  return primeArray[primeArray.length - 1];
}
console.log(primeFinder(10001));
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Because primeArray is now in descending order but your loop still searches from start to end; now from biggest towards smaller values. Until it finds something that is >= Math.sqrt(i) which most likely will be the very first check, j=1.
Then it ends the loop with primeLogger === false

so for example, for:

i=9, j=1
primeArray === [7,5,3,2]
primeArray[j] === 5

And since the check 5 < Math.sqrt(9) is false the loop is finished.

Therefore 9 is a prime number and is now added to the start of primeArray.

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