Skip to content

Instantly share code, notes, and snippets.

@mmenavas
Last active January 6, 2019 23:46
Show Gist options
  • Save mmenavas/53e98ff5e3e905e0aa8609e10cb03290 to your computer and use it in GitHub Desktop.
Save mmenavas/53e98ff5e3e905e0aa8609e10cb03290 to your computer and use it in GitHub Desktop.
Prime Numbers
<?php
/**
* Usage:
* Run the command below to see a list of all prime numbers up to 1000.
* php main.php 1000
*/
include_once("./PrimeNumbers.php");
if (isset($argv[1])) {
PrimeNumbers::printPrimeNumbers($argv[1]);
}
<?php
// This utility class provides a function that calculates all prime numbers up to a given number.
// Disclaimer: Depending on your system, you may not want to find prime numbers greater than 10000 as
// this operation can take several minutes if not hours.
class PrimeNumbers {
public static function getPrimeNumbers($ceiling) {
// Validate input
if (!is_numeric($ceiling) || $ceiling < 2) {
return [];
}
elseif ($ceiling < 3) {
return [2];
}
$all_integers = self::getIntegers($ceiling);
// Closest integer greater than or equal to the square root of $ceiling
$square_root = ceil(sqrt($ceiling));
$prime_numbers = self::getPrimeNumbers($square_root);
$multiples = self::getMultiples($prime_numbers, $ceiling);
return array_diff($all_integers, $multiples);
}
public static function getIntegers($ceiling) {
// Get every integer from 0 to N.
$all_integers = [];
for ($i = 2 ; $i <= $ceiling; $i++) {
$all_integers[] = $i;
}
return $all_integers;
}
public static function getMultiples($prime_numbers, $ceiling) {
// All multiples less than N, of each element in B:
$multiples = [];
foreach ($prime_numbers as $number) {
$j = 2;
while (($j * $number) <= $ceiling) {
if (!in_array($j * $number, $multiples)) {
$multiples[] = $j * $number;
}
$j++;
}
}
return $multiples;
}
public static function printPrimeNumbers($ceiling) {
if ($ceiling > 10000) {
print "Input ($ceiling) is too large. Try entering a number with 4 or less digits.\n";
return false;
}
$prime_numbers = self::getPrimeNumbers($ceiling);
print "Prime numbers up to $ceiling:\n";
if (empty($prime_numbers)) {
print "None\n";
return false;
}
foreach ($prime_numbers as $number) {
print "$number\n";
}
print "\n";
return 1;
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment