Skip to content

Instantly share code, notes, and snippets.

@eaton
Created April 10, 2012 23:39
Show Gist options
  • Save eaton/2355657 to your computer and use it in GitHub Desktop.
Save eaton/2355657 to your computer and use it in GitHub Desktop.
<?php
$ceiling = 600851475143;
$factor = -1;
for ($i = 1; $i < sqrt($ceiling); $i += 2) {
$factor = getLargestFactor($i);
if ($factor == 1) {
primeList($i);
}
}
$ram = memory_get_usage(TRUE);
$factor = getLargestFactor($ceiling);
print "Fuck yeah! The largest prime factor of $ceiling is $factor! It only took $ram bytes of RAM.";
function getLargestFactor($i) {
$primes = primeList();
rsort($primes);
foreach($primes as $p) {
if ($i % $p == 0) {
return $p;
}
}
return 1;
}
function primeList($i = NULL) {
static $primes = array(2,1);
if (isset($i)) {
array_unshift($primes, $i);
}
return $primes;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment