Created
August 14, 2012 02:23
-
-
Save ichirin2501/3345808 to your computer and use it in GitHub Desktop.
Project Euler 23
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/perl | |
use strict; | |
use warnings; | |
use Data::Dumper; | |
use List::Util qw/sum/; | |
sub factor{ | |
my $n = shift; | |
my %hash = (); | |
for(my $i=2; $i*$i<=$n; $i++){ | |
while( $n % $i == 0 ){ | |
$hash{$i}++; | |
$n /= $i; | |
} | |
} | |
$hash{$n}++ if $n > 1; | |
return %hash; | |
} | |
sub sum_of_divisor{ | |
my %hash = ($#_ == 0 ? %{$_[0]} : @_); | |
my $res = 1; | |
my $tmp = 1; | |
return 0 if scalar(keys %hash) == 0; | |
while( my ($a, $b) = each %hash ){ | |
$res *= ($a ** ($b + 1) - 1) / ($a - 1); | |
$tmp *= $a ** $b; | |
} | |
return $res - $tmp; | |
} | |
my $m = 28123; | |
my @abundantNum = grep{sum_of_divisor(factor($_)) > $_} 1..$m; | |
my %S = (); | |
foreach my $i (0..$#abundantNum){ | |
foreach my $j ($i..$#abundantNum){ | |
last if $abundantNum[$i] + $abundantNum[$j] > $m; | |
$S{ $abundantNum[$i] + $abundantNum[$j] } = 1; | |
} | |
} | |
print sum grep{!exists($S{$_})} 1..$m; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment