Reputation: 334
I was trying out the 3rd challenge in the Euler project and I wrote this code to try and solve it.The idea is to find the highest prime factor of 600851475143. After a few popups from Winscript I get the right answer, but then my cpu jumps to 25% and I get nothing else from Winscript leading me to believe something is causing it to go into an infinite loop. Can anyone spot what the problem is?
var isprime = function(n)
{
var s= Math.sqrt(n);
for(i=2;i<=s;i++)
{
if(n%i===0)
{
return false;
}
}
return true;
};
var largest = 0;
var q=0;
while(q<(600851475143/4))
{
if(600851475143%q===0)
{
if(q>largest)
{
if(isprime(q))
{
largest=q;
WScript.Echo(largest);
}
}
var d = 600851475143/q;
if(d>largest)
{
if(isprime(d))
{
largest = d;
WScript.Echo(largest);
}
}
}
q+=1;
}
WScript.Echo(largest);
Upvotes: 0
Views: 89
Reputation: 413818
Once you've found the largest factor, the loop will continue to run, and run, and run, until it has reached the end condition — when q
is 150212868785. One hundred and fifty trillion iterations takes a while.
Upvotes: 1