Aug
10
In my attempt to learn Ruby out in the open, here’s my solution for Project Euler Problem 34.
Having just solved Project Euler 30 in Ruby a few days ago, the solution to this problem was still on the tips of my fingers. The solution is almost identical. I could have nerded out and come up with an intelligent upper bound, but doesn’t 99999 just feel right?
As always, any feedback is welcome.
# Euler 34
# http://projecteuler.net/index.php?section=problems&id=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.
timer_start = Time.now
# There's no factorial method in Ruby, I guess.
class Integer
# http://rosettacode.org/wiki/Factorial#Ruby
def factorial
(1..self).reduce(1, :*)
end
end
# Note the completely random upper bound
max, answer = 99999, 0
(3..max).each do |i|
sum_factorials = i.to_s.chars \
.inject(0){|sum, char| sum + (char.to_i.factorial)}
answer += i if (i == sum_factorials)
end
puts answer
puts "Elapsed Time: #{(Time.now - timer_start)*1000} milliseconds"