HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpMinor

is_Prime() function on PHP

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
phpfunctionis_prime

Problem

I tried to make an is_Prime() function in PHP. What do you think about this code?

";
    return false;
  }
  $data = array();
  for ($i=1;$i2)
  {
    echo $x." is not a prime number";
  }
  else
  {
    echo $x. " is a prime number";
  }
}
?>


How to use?

for($i=0;$i<=100;$i++)
{
  is_Prime($i);
}

Solution

All primes end in either 1, 3, 7, or 9. You could do a check up front to make sure the number satisfies that requirement.

Second, a number is prime if it has no prime factors besides itself and 1. Therefore you should start you checking loop at 3, not at 1. Since you only need to check against primes, you could start the loop at 3, increment it by 10, and check $x/$i, $x/($i+4), $x/($i+6), and $x/($i+8). That would be 4 divide operations instead of the 10 you are presently doing.

Third, you only have to check possible factors up to the square root of the number you are checking, so figure out the sqrt($x) and make that the end of the loop. You are also putting all the factors you find into an array, which is not necessary if you are simply trying to see if the number is prime.

Context

StackExchange Code Review Q#110611, answer score: 3

Revisions (0)

No revisions yet.