Project-Euler-020

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

Python

1
2
3
4
5
6
7
8
9
10
11
12
import 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())


Ruby

1
2
#!/usr/bin/env ruby
puts 100.downto(1).inject(:*).to_s.each_char.inject(0) {|s,v|s+v.to_i}


Haskell

1
2
3
4
5
6
7
8
9
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


Clojure

1
2
#!/usr/bin/env clojure
(println (reduce + (map #(- (int %) 48) (str (reduce * (range BigInteger/ONE 100))))))


Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public 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);
}

}


Mathematica

1
2
3
4
(* 
* We do a straightforward computation thanks to Mathematica's built-in arbitrary precision integer type.
*)
Total[IntegerDigits[100!]]

文章作者: Monad Kai
文章链接: onlookerliu.github.io/2018/03/29/Project-Euler-020/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Code@浮生记
支付宝打赏
微信打赏