Last active
August 29, 2015 14:27
-
-
Save adhocore/8d3514c7aa9fcd04f1df to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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