Skip to content

Instantly share code, notes, and snippets.

@lesterchan
Created April 3, 2014 15:11
Show Gist options
  • Save lesterchan/9956235 to your computer and use it in GitHub Desktop.
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.
<?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