Created
April 3, 2014 15:11
-
-
Save lesterchan/9956235 to your computer and use it in GitHub Desktop.
Write a function which, taking in a positive integer n as input, returns an array of all primes lower than n.
This file contains hidden or 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 | |
/* | |
Sample expected output: | |
getPrimes(5); ⇒ array(2, 3) | |
getPrimes(10); ⇒ array(2, 3, 5, 7) | |
*/ | |
function getPrimes($n) | |
{ | |
if ($n <= 0) throw new InvalidArgumentException("positive integer required"); | |
if ($n < 2) return array(); | |
// 2 is the only "special" prime we care about | |
$primes = array(2); | |
// for efficiency, we iterate over odd numbers only | |
for ($candidate=3; $candidate<$n; $candidate+=2) | |
{ | |
// we use the collection of previously found primes to limit number of iterations | |
// there's no need to go beyond the square root when looking for factors | |
$upper_bound = ceil(sqrt($candidate)); | |
// local variable to avoid lookup at each loop iteration | |
$len = count($primes); | |
// for loop starts at index 1 because we have already excluded even numbers, so we don’t need to test modulo 2 | |
for ($i=1; $i<$len; $i++) | |
{ | |
$cur_prime = $primes[$i]; | |
if ($candidate % $cur_prime === 0) continue 2; | |
if ($cur_prime >= $upper_bound) break; | |
} | |
// if we reach here, we've found a new prime! yeah!! | |
$primes[] = $candidate; | |
} | |
return $primes; | |
} | |
echo implode(',', getPrimes(200)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment