aboutsummaryrefslogtreecommitdiff
path: root/challenge-020/feng-chang/perl5/ch-2.pl
blob: 5d68276e7c92feecfad70fe161c72ac39df23c80 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#!/bin/env perl

use Modern::Perl;
use integer;

my $i = 0;
my %sods;
my $cnt = 0;

while (1) {
    $sods{ $i } = sod($i) unless defined $sods{ $i };
    my $v = $sods{ $i };
    
    if ($v > $i) {
        $sods{ $v } = sod($v) unless defined $sods{ $v };
        if ($i == $sods{ $v }) {
            say "$i $v";
            last if ++$cnt == 5;
        }
    }

    ++$i;
}

# sum of proper divisors
sub sod {
    my $n = shift;

    my $sum = 0;
    my @a = (1) x ($n/2 + 1);

    for (my $i = 1; $i < $n/2 + 1; ++$i) {
        next unless $a[$i];

        if ($n % $i) {
            my $j = $i;
            while ($j <= $n/2 + 1) {
                $a[$j] = 0;
                $j += $i;
            }
        } else {
            $sum += $i;
        }
    }

    return $sum;
}