Skip to content

Instantly share code, notes, and snippets.

@ringmaster
Created October 23, 2012 20:30
Show Gist options
  • Save ringmaster/3941342 to your computer and use it in GitHub Desktop.
Save ringmaster/3941342 to your computer and use it in GitHub Desktop.
Primes
<?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