Created
October 23, 2012 20:30
-
-
Save ringmaster/3941342 to your computer and use it in GitHub Desktop.
Primes
This file contains hidden or 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 | |
function seive($candidates, $min = 0, $max = 0) { | |
$primes = array(); | |
$last = ($max == 0) ? floor(end($candidates) / 2) : $max; | |
$i = ($min == 0) ? reset($candidates) : $min; | |
while($i <= $last) { | |
$candidates = array_filter($candidates, function($n) use ($i, &$primes) { | |
if($n < $i) { | |
$primes[] = $n; | |
return false; | |
} | |
$e = $n / $i; | |
if($e == 1) return true; | |
if($e != floor($e)) return true; | |
return false; | |
}); | |
$i++; | |
} | |
$primes = array_merge($primes, $candidates); | |
return $primes; | |
} | |
function calculatePrime() { | |
// Generate big wheel | |
$init = 300; | |
$candidates = range(2, $init); | |
$primes = seive($candidates, 2, $init); | |
$min = max($primes); | |
for($z = 1; $z <= 5; $z++) { | |
// Multiply out big wheel | |
$candidates = $primes; | |
foreach($primes as $prime) { | |
$candidates[] = $prime + $init * $z; | |
} | |
// Re-seive | |
// echo " * Seive pass $z, " . count($candidates) . " candidates, " . count($primes) . " primes\n"; | |
$primes = seive($candidates, $min); | |
} | |
return $primes; | |
} | |
$res = calculatePrime(); | |
echo implode("\n", $res); | |
//echo "\n * " . count($res) . "\n"; | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment