Project Euler Problem 34
問題
145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145. Find the sum of all numbers which are equal to the sum of the factorial of their digits. Note: as 1! = 1 and 2! = 2 are not sums they are not included.
ソース
class Integer @@fact_cache = [1] def fact f = @@fact_cache[self] return f unless f.nil? @@fact_cache[self] = (1..self).inject(:*) end end puts (3..100000).inject(0){|s, i| s + (i == i.to_s.scan(/./).inject(0){|s, c| s + c.to_i.fact} ? i : 0) }
解答
40730
感想
コレもそのまま組むだけで、特に難しいところはない。(ループ回数はいつものごとく決め打ちだが。。。
factは0-9のみなのでキャッシュしておくと速い