I am trying to determine the largest prime factor of a number by working backwards from the largest possible factor. Once a factor is found, I test to see if it is prime by using the PrimeTest3 function within the original function.
However, it is not giving me the answer I am expecting for the number 13195. When I test the code as shown above using the 'this passed the test' statement, I can see that it is skipping from the first factor found (2639) to the last factor found (5), and strangely, when logging the the result of passing i through PrimeTest3, it shows up as false, even though it had to have been true to pass the if statement in the first place.
var largestPrimeFactor3 = function (num) {
function PrimeTest3(a){
if (a<=1 || a%1!=0)
return false;
limit = Math.ceil(Math.pow(a,.5));
if (a%2==0 || a%3==0)
return false;
if (a==2 || a==3)
return true;
for (i=6;i<limit;i+=6){
if (a%(i-1)==0)
return false;
if (a%(i+1)==0)
return false;
}
return true;
}
for(var i = Math.floor(num/2); i>0; i--){
console.log(i);
if(num % i === 0 && PrimeTest3(i)){
console.log('this passed the test:' + PrimeTest3(i));
return true;
}
}
}
console.log(largestPrimeFactor3(13195));
Would really appreciate any help or clarification. Thanks!!
Aucun commentaire:
Enregistrer un commentaire