Skip to content

Instantly share code, notes, and snippets.

@bklein01
Last active August 29, 2015 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bklein01/b3ee07017f98b4f09a61 to your computer and use it in GitHub Desktop.
Save bklein01/b3ee07017f98b4f09a61 to your computer and use it in GitHub Desktop.
Find the highest prime number given an argument
<?php
class primeTest
{
private $primeArray;
public function __construct() {
$this->primeArray = array();
}
private function isPrime($n) {
if (in_array($n, $this->primeArray)) {
return true;
} else {
if (sizeof($this->primeArray) > 0) {
$top = max($this->primeArray);
} else {
$top = 0;
}
if ($n < $top) {
return true;
} else {
$i = 2;
if ($n == 2) {
$this->primeArray[] = $n;
return true;
}
while ($i < $n) {
if ($n % $i == 0) {
return false;
}
$i++;
}
$this->primeArray[] = $n;
return true;
}
}
}
public function findTopPrime($input) {
if ($input == '') {
return "You Must Enter A Number For This Excercise";
} else {
$primes = '';
$highestPrime = 1;
for ($i=1; $i<=$input; $i++) {
if ($input % $i == 0) {
if ($this->isPrime($i)) {
if ($primes == '') {
$primes = $i;
} else {
$primes .= ','. $i;
}
if ($i > $highestPrime) {
$highestPrime = $i;
}
}
}
}
$output = "Highest Prime: " . $highestPrime . "\n\n";
$output .= "Collection of Primes: " . $primes . "\n";
return $output;
}
}
}
$input = $argv[1];
$objPrime = new primeTest();
$results = $objPrime->findTopPrime($input);
echo $results;
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment