So I’m trying to solve the third problem of Project Euler in which you have to get the largest prime factor of a number. I’m trying this problem via freeCodeCamp. I pass all tests of 2, 3, 5, 7, 8 and 13195, but from 13195 and upwards I get a Potential infinite loop detected on line 12. Tests may fail if this is not changed.
warning. The final test of 600851475143 gives the following warnings:
Potential infinite loop detected on line 6. Tests may fail if this is not changed.
Potential infinite loop detected on line 15. Tests may fail if this is not changed.
Potential infinite loop detected on line 12. Tests may fail if this is not changed.
and the horribly wrong answer of 104441.
What could I have done wrong, since my loops don’t look like they would run infinitely syntax-wise? Am I missing something here?
Code I’m using:
const eratoSieve = (n) => {
let primes = [2, 3, 5, 7];
if (n > 7)
{
primes = [];
for (let i = 2; i < n; i++)
{
primes.push(i);
}
}
for (let j = 0; j < primes.length; j++)
{
let currentMultiple = primes[j];
for (let k = j + 1; k < primes.length - 1; k++)
{
if (primes[k] % currentMultiple === 0)
{
primes.splice(k, 1);
}
}
}
return primes;
};
function largestPrimeFactor(number) {
let primeNums = eratoSieve(number);
console.log(primeNums);
let biggestPrime = 0;
primeNums.forEach(elem => {
(number % elem === 0) ? biggestPrime = elem : 0;
});
return biggestPrime;
}
console.log(largestPrimeFactor(100));
Thanks in advance for the help!