public
Created

PHP prime number generator

  • Download Gist
prime.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
<!DOCTYPE html>
<html>
<head>
<title>Prime Number Generator</title>
</head>
<body onload="location.href='#bottom'">
<?php
 
$start = microtime(TRUE);
 
$primes = json_decode(file_get_contents("prime_array.json"));
 
$i = $primes[count($primes) -1] + 1;
$ip = $i + 999;
 
if($i % 2 === 0)
{
++$i;
++$ip;
}
 
for($i;$i < $ip;$i+=2)
{
$prime = TRUE;
 
foreach($primes as $p)
{
//Divisible by another primeā€¦it's a composite
if($i % $p === 0)
{
$prime = FALSE;
break;
}
}
if($prime === TRUE)
{
$primes[] = $i;
}
}
 
echo implode(", ", $primes);
 
file_put_contents("prime_array.json", json_encode($primes));
 
$end = microtime(TRUE);
 
?><p> Generated <?= count($primes) ?> primes in <?= $end - $start ?> seconds</p>
<span id="bottom"></span>
</body>
</html>
prime_array.json
JSON
1
[2]

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.