Hey all,
I have been doing the Euler challenge and, on problem 3 (largest prime factorial) I get the hint that a possible infinite loop is detected but I cannot see that being the case as my code has breaks/return statements and the loops are limited by the input number. Obviously, I know putting a huge number would take a lot of time to compute but that is always going to be the case, isn’t it?
Thought I’d ask here whether I am wrong and the warning is real or whether I am right in believing it is a false flag due to the possible size of the computation required by a large number.
The tests all pass, just made me wonder if I have missed something.
Thanks all.
My code is as follows:
function largestPrimeFactor(number) {
if(isPrime(number)) return number;
return primeFactors(number);
}
function isPrime(num) {
if(num <= 3) return true;
for( let i = 2; i < num; i++) {
if(num % i === 0) return false;
}
return true;
}
function primeFactors(num) {
let primeFact;
for(let i = 2; i < num; i++) {
if(isPrime(i) && num % i === 0) primeFact = i;
}
return primeFact;
}
largestPrimeFactor(13195);
Figured it out, thanks to Bob and having a peek at the official solution. Final solution without warning is as follows:
function largestPrimeFactor(number) {
// Set the starting prime
let prime = 2,
rtn = 1;
// Initiate a loop which will only run while
// prime is less than number
while (prime <= number) {
// Check that the current prime is a factor of the current number
number % prime === 0 ?
// if it is set the return value to the current prime
(rtn = prime,
// Then decrement the initial number so we can start from there
// on the next run
// If it isn't factor increment the current prime
number /= prime) : prime++;
}
// Return the final value.
return rtn;
}
largestPrimeFactor(13195);