Project Euler Problem 20 Solution

Question

n!n! means n×(n1)×...×3×2×1n \times (n - 1) \times ... \times 3 \times 2 \times 1.

Find the sum of the digits in the number 100!100!.

Clojure

#!/usr/bin/env clojure
(println (reduce + (map #(- (int %) 48) (str (reduce * (range BigInteger/ONE 100))))))
$ time clojure factorial.clj
real   0m0.692s
user   0m1.176s
sys    0m0.028s

Haskell

sumDigits ::  Integer -> Integer
sumDigits n = sumDigits' n 0
    where sumDigits' 0 acc = acc
          sumDigits' n acc = sumDigits' (div n 10) (acc + (mod n 10))

factorial ::  Integer -> Integer
factorial n = foldr (*) 1 [1..n]

main = print $ sumDigits $ factorial 100
$ ghc -O2 -o factorial factorial.hs
$ time ./factorial
real   0m0.002s
user   0m0.000s
sys    0m0.000s

Ruby

#!/usr/bin/env ruby
puts 100.downto(1).inject(:*).to_s.each_char.inject(0) {|s,v|s+v.to_i}
$ time ruby factorial.rb
real   0m0.044s
user   0m0.040s
sys    0m0.000s

Questions? Comments? Send me an email: z@chdenton.com