Last active
August 29, 2015 14:21
-
-
Save bklein01/b3ee07017f98b4f09a61 to your computer and use it in GitHub Desktop.
Find the highest prime number given an argument
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 | |
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