Skip to content

Instantly share code, notes, and snippets.

@bondarewicz
Created September 17, 2013 13:34
Show Gist options
  • Save bondarewicz/6594346 to your computer and use it in GitHub Desktop.
Save bondarewicz/6594346 to your computer and use it in GitHub Desktop.
PHP: Prime Numbers
<?php
$primes = array();
for ($i = 0; $i <= 1000; $i++) {
if(isPrime($i) === true) array_push($primes, $i);
}
var_dump($primes);
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