PHP Classes

optimization

Recommend this page to a friend!

      Is Prime  >  All threads  >  optimization  >  (Un) Subscribe thread alerts  
Subject:optimization
Summary:limit the number of check
Messages:4
Author:JACQ Fabien
Date:2012-01-09 11:03:37
Update:2013-06-23 15:45:05
 

  1. optimization   Reply   Report abuse  
Picture of JACQ Fabien JACQ Fabien - 2012-01-09 11:03:37
in the following flow control:
for($i=10; $i < ($num/2); $i++){

You can limit the number of check by doing this:
for($i=10; $i < sqrt($num); $i++){


  2. Re: optimization   Reply   Report abuse  
Picture of Ahmad Retha Ahmad Retha - 2012-01-09 19:40:41 - In reply to message 1 from JACQ Fabien
Thanks Jacq! Spot on!

If anyone has any optimisation recommendations then they are most welcome to suggest them.

  3. Re: optimization   Reply   Report abuse  
Picture of Omar Ramos 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

  4. Re: optimization   Reply   Report abuse  
Picture of Ahmad Retha Ahmad Retha - 2013-06-23 15:45:05 - In reply to message 3 from Omar Ramos
I should really do more checks and pay more attention... Didn't see this post until recently. Code fixed now. Thank you.