-
-
Save amarnus/1860327 to your computer and use it in GitHub Desktop.
List of all the circular primes under a million
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 | |
ini_set('memory_limit', '256M'); | |
$maximum = 1000000; // a million if you were wondering.. | |
global $values; | |
function check_if_circular($prime) { | |
global $values; | |
$back2back = $prime . $prime; // 7373 | |
$count = strlen($prime); | |
for($i = 0; $i <= $count - 1; ++$i) { | |
$number = intval(substr($back2back, $i, $count)); | |
if ($values[$number] > 0) { | |
return FALSE; | |
} | |
} | |
return TRUE; | |
} | |
function microtime_float() { | |
list($usec, $sec) = explode(" ", microtime()); | |
return ((float)$usec + (float)$sec); | |
} | |
function sieve($uptil) { | |
global $values; | |
$values = array_fill(0, $uptil+1, -1); | |
$values[0] = 1; // 0 is neither prime nor composite | |
$values[1] = 1; // 1 is not prime | |
$threshold = intval(sqrt($uptil)); | |
$i = 2; | |
while($i <= $threshold) { | |
if ($values[$i] > 0) { | |
++$i; | |
continue; | |
} | |
$k = 2; | |
$j = $i*$k; | |
while($j <= $uptil) { | |
$values[$j] = 1; | |
$j = $i*(++$k); | |
} | |
++$i; | |
} | |
$list = array_filter($values, create_function('$elem', 'return ($elem < 0);')); | |
$list = array_filter(array_keys($list), "check_if_circular"); | |
// print_r($list); | |
return count($list); | |
} | |
$start = microtime_float(); | |
print sieve($maximum) . " in " . (microtime_float() - $start) . " seconds\n"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment