<?php
// list all primes between 2 and some integer
// using the Sieve of Erastothenes
function listPrimes($end) {
// generate an array of all possible integers
// between the first prime and the supplied limit
$sieve = range(2, $end);
// retrieve the size of the array
$size = sizeof($sieve);
// reset internal array pointer to beginning of array
reset($sieve);
// iterate over the array
while (list($key, $val) = each($sieve)) {
// for each element
// check if subsequent elements are divisible by it
// remove them from the array if so
for ($x=$key+1; $x<$size; $x++) {
if ($sieve[$x] % $val == 0) {
unset($sieve[$x]);
}
}
}
// at the end, elements left in array are primes
return $sieve;
}
// list all the primes between 2 and 100
// result: "2 3 5 7...83 89 97"
echo implode(" ", listPrimes(100));
?>
อ้างอิง http://www.phpeveryday.com/articles/PHP-Number-Generating-Prime-Numbers-P348.html
คีย์เวิร์ด list prime number function