Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

176
Views
¿Por qué unshift() devuelve un valor diferente que push() si estoy apuntando al primer elemento en el primero y al último elemento en el último?

Tengo una función para Project Euler #7. Hacia el final, cambié el código de primeArray.push(i); a primeArray.unshift(i) y return primeArray[primeArray.length - 1]; para return primeArray[0]; . Esto alteró el regreso. En la antigua. Devolvió la respuesta correcta, 104021, mientras que el último devolvió 20001, que ni siquiera es primo. No entiendo por qué es eso.

 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 answers
Answer question

0

Porque primeArray ahora está en orden descendente, pero su ciclo aún busca de principio a fin; ahora desde los valores más grandes hacia los más pequeños. Hasta que encuentre algo que sea >= Math.sqrt(i) que muy probablemente será la primera verificación, j=1 .
Luego termina el ciclo con primeLogger === false

así por ejemplo, para:

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

Y dado que el control 5 < Math.sqrt(9) es false , el bucle finaliza.

Por lo tanto, 9 es un número primo y ahora se agrega al comienzo de primeArray .

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!