Created
November 29, 2011 14:04
-
-
Save dionyziz/1404894 to your computer and use it in GitHub Desktop.
A sieve of Eratosthenes in PHP
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 | |
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