It's your lucky day! I coded an unoptimized solution. This runs pretty quickly (<10sec) but you could really improve the factor subroutine.

my @numbers = (1 .. 10000); my %factor_hash = (); my $number = 1; my @perfect_numbers = (); for $number (@numbers) { #do the factoring in a subroutine #store a string such as 1-2-4 for the factors of 4 $factor_hash{$number} = factor($number); } #time to check for perfection for $number (@numbers) { my $sum_of_factors = 0; my @factors = split /-/, $factor_hash{$number}; for my $factor (@factors) { $sum_of_factors+=$factor; } #a number is perfect if it equals half the sum of all factors # (because the number itself is a factor) if ($number == $sum_of_factors/2) { print "$number is perfect\n"; push @perfect_numbers, $number; } } sub factor { my $factor_string = ""; my $number = shift; for my $i ( 1 .. $number) { if (($number % $i) == 0) { $factor_string .= "-$i"; } } return $factor_string; } #OUTPUT #6 is perfect #28 is perfect #496 is perfect #8128 is perfect

According to wikipedia the output is correct.


In reply to Re: finding perfect numbers by zek152
in thread finding perfect numbers by derpp

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.