Created
August 25, 2012 19:52
-
-
Save kiyotune/3470196 to your computer and use it in GitHub Desktop.
Project Euler 問題34
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/env perl | |
use strict; | |
use warnings; | |
#n桁の数値のそれぞれの数字の階乗の和の最大値を考える | |
#【6桁】[max] 999999 < 2177280 | |
#【7桁】[max] 9999999 > 2540160 | |
#よって最大は7桁2540160未満 | |
#1桁の数値は明らかに除外 | |
#2桁の数値は14=1+24=25からが2桁になるので最小値は14から | |
#眠いので力技 | |
my $ans = 0; | |
foreach my $num (14..2540160) | |
{ | |
my $sum = sum_factorial($num); | |
if($sum == $num) | |
{ | |
$ans += $sum; | |
} | |
} | |
print "Ans: $ans\n"; | |
exit(1); | |
# | |
# 入力値の各数値の階乗の和を計算 | |
# | |
sub sum_factorial | |
{ | |
my @a = split(//, shift); | |
my $sum = 0; | |
foreach (@a) | |
{ | |
$sum += get_factorial($_); | |
} | |
return ($sum); | |
} | |
# | |
# 階乗 | |
# | |
sub get_factorial | |
{ | |
my $n = shift; | |
my $ret = 1; | |
map { $ret*=$_ } (1..$n); | |
return $ret; | |
} | |
# Ans: 40730 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment