Last active
August 29, 2015 14:07
-
-
Save zigo928/3bc713ba016fc8aed610 to your computer and use it in GitHub Desktop.
找出素数
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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