Skip to content

Instantly share code, notes, and snippets.

@Petah
Created July 7, 2021 03:39
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 Petah/71e7fa50c984888c3780eb9949e7dd61 to your computer and use it in GitHub Desktop.
Save Petah/71e7fa50c984888c3780eb9949e7dd61 to your computer and use it in GitHub Desktop.
Prime drag race
<?php
$passes = 0; //Init passes
$sieveSize = 1000000; //Set sieve size
$runTime = 10; //The amount of seconds the script should be running for
$stopTime = microtime(true) + $runTime;
$q = sqrt($sieveSize);
while (microtime(true) < $stopTime) {
$factor = 3;
$rawbits = [];
while ($factor < $q) {
for ($i = $factor; $i <= $sieveSize; $i += 2) {
if (!isset($rawbits[$i])) {
$factor = $i;
break;
}
}
$ft2 = $factor * 2;
for ($i = $factor * $factor; $i <= $sieveSize; $i += $ft2) {
$rawbits[$i] = 1;
}
$factor += 2;
}
$passes++;
}
$endTime = microtime(true);
$startTime = $stopTime - $runTime;
$rawbitCount = ($sieveSize / 2) - array_sum($rawbits);
$primeCounts = [
10 => 4,
100 => 25,
1000 => 168,
10000 => 1229,
100000 => 9592,
1000000 => 78498,
10000000 => 664579,
100000000 => 5761455,
];
//Print the results
printf(
"Passes: %d, Time: %dms, Avg: %dms, Limit: %d, Count: %d, Valid: %s",
$passes,
(int)(($endTime - $startTime) * 1000),
(($endTime - $startTime) * 1000) / $passes,
$sieveSize,
$rawbitCount,
$primeCounts[$sieveSize] === $rawbitCount ? 'True' : 'False'
);
// Following 2 lines added by rbergen to conform to drag race output format
echo "\n\n";
printf("DennisdeBest;%d;%f;1;algorithm=base,faithful=no\n", $passes, $endTime - $startTime);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment