Skip to content

Instantly share code, notes, and snippets.

@twaddington
Created February 2, 2011 04:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save twaddington/807227 to your computer and use it in GitHub Desktop.
Save twaddington/807227 to your computer and use it in GitHub Desktop.
<?php
function isPrime($number) {
// A prime number is only divisible by 1 and itself.
// All numbers are divisible by 1, so start with 2.
for ($div = 2; $div < $number; $div++) {
// If $number is wholly divisible by $div (no remainder).
if (($number % $div) === 0) {
// If we can evenly divide $number by anything that
// is not 1 or itself, it is not prime and we can return
// immediately.
return false;
}
}
// Return true
return true;
}
$i=2;
while ($i<=1000) {
if (isPrime($i)) {
echo "Prime: " . $i . "\n";
}
$i++;
}
?>
@appcove
Copy link

appcove commented Feb 2, 2011

It is obvious that no prime number is divisible by 2, so you would speed this up by

for($div = 3; $div < $number; $div+=2)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment