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.
Ruby: Running time = 0.78s
+-#factorial
def factorial(n)
return 1 if n<2
(2..n).inject{|u,v|u*v}
end
+-#Enumerable
module Enumerable
def sum
self.inject{|u,v|u+v}
end
def product
self.inject{|u,v|u*v}
end
def count(ob)
self.select{|i|i==ob}.length
end
def take_while
return [] unless yield(self.first)
if(self.class==Range)
evalPoint=self.first
evalPoint=evalPoint.succ while yield(evalPoint.succ) and not evalPoint==self.last
return self.first..evalPoint
else
s=self.to_a
upTo=1
upTo+=1 while yield(s[upTo]) and upTo<self.length
return self[0...upTo]
end
end
end
+-#dig_split
def dig_split(n)
s=n.to_s
s.split("").map{|i|i.to_i}
end
+-#repeat_combos
def repeat_combos(selectFrom,totalDigits)
return [] if selectFrom==[]
return [[selectFrom.first]*totalDigits] if(selectFrom.length==1)
return selectFrom.map{|i|[i]} if totalDigits==1
ret=[]
selectFrom.each do |a|
1.upto(totalDigits-1) do |b|
c=repeat_combos(selectFrom[(selectFrom.index(a)+1)..-1],totalDigits-b)
c.each{|d|ret.push(([a]*b)+d)}
end
ret.push([a]*totalDigits)
end
ret
end
def p34
fax=(0..9).map{|i|factorial(i)}
puts (2..7).map{|i|repeat_combos((0..9).to_a,i)}.inject{|u,v|u+v}.
select{|a|a==dig_split(a.map{|i|fax[i]}.sum).sort}.map{|a|a.map{|i|fax[i]}.sum}.sum
end