Skip to content

Instantly share code, notes, and snippets.

@vayn
Created May 22, 2010 05:55
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 vayn/409824 to your computer and use it in GitHub Desktop.
Save vayn/409824 to your computer and use it in GitHub Desktop.
Prime Number
<?php
$sum = 2;
for ($i = 3; $i <= 10000; $i++) {
$k = 1;
for ($j = 2; $j < $i; $j++) {
if ($i % $j == 0) {
$k = 0;
break;
}
}
if ($k == 1) {
echo $i . "\n";
$sum = $sum + $i;
}
}
echo $sum . "\n";
?>
@HelixSpiral
Copy link

If you check for the number being even above the second for then you can optimize the for check by only checking for odd numbers. Since every even number is prime.

You could also optimize this by only checking odd numbers to begin with, eliminating the need to check if the number is even all together.

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