Last active
December 23, 2017 21:09
-
-
Save pwm/45c0d95dba4af2755965dd2331214194 to your computer and use it in GitHub Desktop.
Sieve of Eratosthenes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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