Skip to content

Instantly share code, notes, and snippets.

@revsbech
Created September 12, 2016 11:11
Show Gist options
  • Save revsbech/eadf4d875005005b685dcdd24128839f to your computer and use it in GitHub Desktop.
Save revsbech/eadf4d875005005b685dcdd24128839f to your computer and use it in GitHub Desktop.
<?php
if ($argc != 2) {
print "Usage:: primes.php <max>" . PHP_EOL;
exit (1);
}
$i = 1;
$max = intval($argv[1]);
echo "Finding primnumber below " . $max . PHP_EOL;
for ($i =1; $i < $max; $i++) {
if (isPrime($i)) {
printf("%d is a prime!\n", $i);
}
}
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