Perfect Numbers

Apr
17

After seeing a recent tweet from mathematician Marcus du Sautoy about perfect numbers and their relation to Mersenne primes I thought I'd write some PHP to "brute force" a list of perfect numbers.

$start = 2;
$perfect = array();

for ($i = $start;;$i++) {
  set_time_limit(36000);
  $numbers = array();
  for ($j = 1; $j < $i; $j++) {
    if ($i % $j == 0) {
      $numbers[] = $j;
    }
  }
  $sum = 0;
  foreach ($numbers as $num) {
    $sum += $num;
  }
  if ($sum == $i) {
    $fh = fopen('perfect.txt', 'a+');
    fwrite($fh, $i . "\n");
    fclose($fh);
  }
}

As you can see it's a very intensive script and will take several hours just to calculate the first four (the first three take practically no time at all to on my system though). As the only known perfect numbers are even one possible improvement would have been to replace the first for loop with $i + 2 for the part that increments the counter as there is no point testing odd numbers.

Improving this function to use Mersenne Primes would also be incredibly hard - to date only 46 have been found due to how intensive the processing required is for calculating them. The 46th number was only just found last year as the result of a distributed computing project.

your comments - Post a comment

blog comments powered by Disqus