Skip to content

Instantly share code, notes, and snippets.

@adhocore
Last active August 29, 2015 14:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adhocore/8d3514c7aa9fcd04f1df to your computer and use it in GitHub Desktop.
Save adhocore/8d3514c7aa9fcd04f1df to your computer and use it in GitHub Desktop.
<?php
/**
* Alternative prime number generator
*
* Generates first <n> prime numbers using
* the prime numbers themselves
*
* @author Jitendra Adhikari <jiten.adhikary@gmail.com>
*
* @param int The number of prime numbers to generate
* @return array The generated prime numbers
*/
function primes($n)
{
static $p = [2];
if (count($p) >= $n) {
return array_slice($p, 0, $n);
}
$i = end($p);
while ($i++) {
foreach ($p as $_p) {
if ($i % $_p == 0) {
continue 2;
}
}
$p[] = $i;
if (count($p) == $n) {
return $p;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment