Want more features on Pastebin? Sign Up, it's FREE!
Guest

Divisors February 14, 2012

By: a guest on Feb 14th, 2012  |  syntax: Perl  |  size: 0.84 KB  |  views: 60  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. use warnings;
  2. use strict;
  3.  
  4. my $max = int($ARGV[0]) or die "Usage: $0 <max positive integer>\n";
  5. my @divisors;
  6. my %amicable;
  7. for my $n (1 .. $max) {
  8.     # 1 is always a divider of any integer
  9.     push @{$divisors[$n]}, 1;
  10.  
  11.     # find the rest of the dividers
  12.     for (2 .. $max) {
  13.         push @{$divisors[$n]}, $_ unless ($n % $_);
  14.     }
  15.  
  16.     # check to see if this is a perfect number
  17.     my $total = unpack "%123d*" , pack( "d*", @{$divisors[$n]});
  18.     print "$n is a perfect number\n" if (2*$n == $total);
  19.  
  20.     # check to see if this is an amicable pair with an earlier number
  21.     $amicable{$n} = $total-$n;
  22.     if (
  23.             exists($amicable{$total-$n}) &&
  24.             ($amicable{$total-$n} == $n) &&
  25.             ($n != $total-$n)
  26.         )
  27.     {
  28.         print "$n and " . ($total-$n) . " are an amicable pair\n";
  29.     }
  30. }
clone this paste RAW Paste Data