20 August 2010

Project Euler : Find the sum of the digits in the number 100!

Problem 20
n! means n x (n -1) x ... x 3 x 2 x 1
Find the sum of the digits in the number 100!

Solution (In Ruby)

All we have to do for the above problem is to write a factorial method. Get the value of 100! and split it into characters and simply add them. Source code is given below.
def fact(n)
  return 1 if n == 0
  n * fact(n-1)
end
puts "Result is #{fact(100).to_s.split(//).inject(0){|b,i| b+i.to_i}}"

Hover here to see the result

Cheers!!
Bragaadeesh

No comments: