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   0m2.038s
user   0m7.140s
sys    0m0.124s

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.001s
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.047s
user   0m0.044s
sys    0m0.000s

Rust

fn main() {
    let mut decimal = [0; 200];
    decimal[0] = 1;
    for n in 1..101 {
        let mut carry = 0;
        for i in 0..decimal.len() {
            let mut digit = decimal[i];
            digit = n * digit + carry;
            carry = digit / 10;
            decimal[i] = digit % 10;
        }
    }
    println!("{}", decimal.iter().sum::<u64>());
}
$ rustc -C target-cpu=native -C opt-level=3 -o factorial_digits factorial_digits.rs
$ time ./factorial_digits
real   0m0.002s
user   0m0.000s
sys    0m0.000s