Skip to content

Instantly share code, notes, and snippets.

@zigo928
Last active August 29, 2015 14:07
Show Gist options
  • Save zigo928/3bc713ba016fc8aed610 to your computer and use it in GitHub Desktop.
Save zigo928/3bc713ba016fc8aed610 to your computer and use it in GitHub Desktop.
找出素数
<?php
function isPrime($num)
{
//1 is not prime. See: http://en.wikipedia.org/wiki/Prime_number#Primality_of_one
if($num == 1)
return false;
//2 is prime (the only even number that is prime)
if($num == 2)
return true;
/**
* if the number is divisible by two, then it's not prime and it's no longer
* needed to check other even numbers
*/
if($num % 2 == 0) {
return false;
}
/**
* Checks the odd numbers. If any of them is a factor, then it returns false.
* The sqrt can be an aproximation, hence just for the sake of
* security, one rounds it to the next highest integer value.
*/
for($i = 3; $i <= ceil(sqrt($num)); $i = $i + 2) {
if($num % $i == 0)
return false;
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment