Skip to content

Instantly share code, notes, and snippets.

@adhocore
Last active Aug 29, 2015
Embed
What would you like to do?
<?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