Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

167
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda