klenwell information services : Euler20Ruby

Project Euler #20

return to ProjectEuler

http://projecteuler.net/problem=20

=begin

    http://projecteuler.net/problem=20
   
    n! means n * (n − 1) * ... * 3 * 2 * 1
   
    For example, 10! = 10 * 9 * ... * 3 * 2 * 1 = 3628800, and the sum of the
    digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.

    Find the sum of the digits in the number 100!

=end


#
# Constants / Globals
#
def assert_match(value, expected)
    raise "value %s != expected %s" % [value, expected] unless value == expected
    true
end


#
# Test Case / Solution
#
def test_case
    number = 10
    expected = 27
   
    sum = sum_digits(factorial(number))
    assert_match(sum, expected)
    puts "test case passed!"
end


def solution
    number = 100
    sum = sum_digits(factorial(number))
    return sum
end



#
# Support Code
#
def factorial(n)
    fact = 1
    while n >= 1
        fact *= n
        n -= 1
    end
   
    return fact
end

def sum_digits(number)
    sum = 0
    number.to_s.split('').each do |n|
        sum += n.to_i
    end
    return sum
end



#
# Test Code
#



#
# Main
#
test_case
puts solution