Skip to content

Instantly share code, notes, and snippets.

@dionyziz
Created November 29, 2011 14:04
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 dionyziz/1404894 to your computer and use it in GitHub Desktop.
Save dionyziz/1404894 to your computer and use it in GitHub Desktop.
A sieve of Eratosthenes in PHP
<?php
define( 'N', 10000 );
// upper bound for our prime number
$estimate = floor( N * log( N ) + N * log( log( N ) ) );
$primes = array( 2, 3, 5, 7, 11, 13 );
$primeCount = 6;
$lastPrime = 13;
for ( $i = 17; $primeCount <= N; $i += 2 ) {
$prime = true;
for ( $j = 0; $j < $primeCount; ++$j ) {
if ( $primes[ $j ] * $primes[ $j ] > $i ) {
break;
}
if ( $i % $primes[ $j ] == 0 ) {
$prime = false;
break;
}
}
if ( $prime ) {
if ( $i * $i <= $estimate ) {
$primes[] = $i;
}
$lastPrime = $i;
++$primeCount;
}
}
echo $lastPrime . "\n";
echo "Used " . memory_get_peak_usage() . " bytes of memory.\n";
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment