Skip to content

Instantly share code, notes, and snippets.

@pwm
Last active December 23, 2017 21:09
Show Gist options
  • Save pwm/45c0d95dba4af2755965dd2331214194 to your computer and use it in GitHub Desktop.
Save pwm/45c0d95dba4af2755965dd2331214194 to your computer and use it in GitHub Desktop.
Sieve of Eratosthenes
<?php
// https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
function sieve(int $n): array {
$a = array_fill(2, $n - 1, true);
for ($i = 2, $iMax = floor(sqrt($n)); $i <= $iMax; $i++) {
if ($a[$i] === true) {
for ($j = $i ** 2; $j <= $n; $j += $i) {
$a[$j] = false;
}
}
}
return array_keys(array_filter($a, function ($e) { return $e; }));
}
// 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97
echo implode(', ', sieve(100));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment