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
primes
to store all the prime numbers less thannumber
Loop through the odd numbers only below
number
to check for primes usingi
Check if
i
is divisible by any of the elements already inprimes
.- If yes,
isPrime = false
and break the for loop forj
byj=primesLength
- If not,
isPrime = true
- If yes,
If
isPrime == true
then addi
to the arrayprimes
and check ifnumber%i == 0
- If
number%i == 0%
update the value offactor
asfactor = i
- If
Return
factor
after 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\$