
Omar Ramos - 2012-11-15 05:42:49 -
In reply to message 2 from Ahmad Retha
Hi Ahmad,
I was using your class for ProjectEuler.net's Problem #7 where one has to find a specific prime number (the 10,001st prime) and I discovered that the class has a slight issue starting with the number 121 which results in a false positive.
The issue happens within the loop because the sqrt(121) = 11 (and therefore the number shouldn't be prime since the square root results in a whole number).
There are two ways to resolve the issue, one is to change the ending condition in the for loop to use <= rather than < (that way 11 would be checked properly). Another thing to do is add in a check to see if the sqrt($num) is a whole number (if it isn't some decimal number then we know the number is not prime).
In my case I just went ahead and implemented both:
$squareRoot = sqrt($num);
// If the square root ends up being a whole number
// then that number cannot be prime:
if ($squareRoot == (int) $squareRoot)
{
return false;
}
for($i = 10; $i <= $squareRoot; $i = $i + 1)
And that should do the trick :-).
-Omar