Problem
$n!$ means $n \times (n - 1) \times … \times 3 \times 2 \times 1$.
Find the sum of the digits in the number $100!$.
Answer
1 | 648 |
Python1
2
3
4
5
6
7
8
9
10
11
12import math
# We do a straightforward computation thanks to Python's built-in arbitrary precision integer type.
def compute():
n = math.factorial(100)
ans = sum(int(c) for c in str(n))
return str(ans)
if __name__ == "__main__":
print(compute())
Ruby1
2#!/usr/bin/env ruby
puts 100.downto(1).inject(:*).to_s.each_char.inject(0) {|s,v|s+v.to_i}
Haskell1
2
3
4
5
6
7
8
9sumDigits :: 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
Clojure1
2#!/usr/bin/env clojure
(println (reduce + (map #(- (int %) 48) (str (reduce * (range BigInteger/ONE 100))))))
Java1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19public final class p020 implements EulerSolution {
public static void main(String[] args) {
System.out.println(new p020().run());
}
/*
* We do a straightforward product with help from Java's BigInteger type.
*/
public String run() {
String temp = Library.factorial(100).toString();
int sum = 0;
for (int i = 0; i < temp.length(); i++)
sum += temp.charAt(i) - '0';
return Integer.toString(sum);
}
}
Mathematica1
2
3
4(*
* We do a straightforward computation thanks to Mathematica's built-in arbitrary precision integer type.
*)
Total[IntegerDigits[100!]]