I am self-learning js and came across this problem(#3) from the Euler Project
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
Logic:
Have an array
primesto store all the prime numbers less thannumberLoop through the odd numbers only below
numberto check for primes usingiCheck if
iis divisible by any of the elements already inprimes.- If yes,
isPrime = falseand break the for loop forjbyj=primesLength - If not,
isPrime = true
- If yes,
If
isPrime == truethen addito the arrayprimesand check ifnumber%i == 0- If
number%i == 0%update the value offactorasfactor = i
- If
Return
factorafter looping through all the numbers belownumber
My code:
function problem3(number){
let factor = 1;
let primes = [2]; //array to store prime numbers
for(let i=3; i<number; i=i+2){ //Increment i by 2 to loop through only odd numbers
let isPrime = true;
let primesLength= primes.length;
for(let j=0; j< primesLength; j++){
if(i%primes[j]==0){
isPrime = false;
j=primesLength; //to break the for loop
}
}
if(isPrime == true){
primes.push(i);
if(number%i == 0){
factor = i;
}
}
}
return factor;
}
console.log(problem3(600851475143));
It is working perfectly for small numbers, but is quite very slow for 600851475143. What should I change in this code to make the computation faster?
//to break the for loop" Doesn't Javascript have abreak? \$\endgroup\$0.00001s. \$\endgroup\$