Reputation: 25
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!!
Upvotes: 1
Views: 80
Reputation: 782130
The for
loop inside PrimeTest3
is using the same variable i
as the loop in largestPrimeFactor3
. You need to declare this variable as local to the internal function, with a var
declaration.
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 (var 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));
Upvotes: 2
Reputation: 106800
You're having unexpected results because you're changing the value of i
in PrimeTest3
.
if(num % i === 0 && PrimeTest3(i)){ // i changed in PrimeTest3
// now i is not what it was when originally passed in PrimeTest3
console.log('this passed the test:' + PrimeTest3(i));
A fix would be to change:
for (i=6;i<limit;i+=6){
To:
for (var i=6;i<limit;i+=6){
This will localize the i
variable to not change the other i
variable outside PrimeTest3
's function scope.
While you're at it, localize limit
to the scope of PrimeTest3
by doing var limit = ...
instead of just limit = ...
.
Upvotes: 0