Euler #20: Factorial Digit Sum

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

For example, 10! = 10 \times 9 \times 8 \times 7 \times 6 \times 5 \times 4 \times 3 \times 2 \times 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!.

https://projecteuler.net/problem=20

Trying 100! in my unsuspecting calculator overflows it. It’s an unimaginably big number. It is approximately 10^{158}. For comparison, the number of atoms in the observable universe is estimated to be somewhere on the order of 10^{80}!! (Factorial definitely not intended).

Calculating this directly is just doing 100 multiplications. Storing this number is a different story, however. With languages like C, some preliminary work needs to be done. With Python and its bignum support, the answer is just a few lines.

import math

total = 0
for digit in str(math.factorial(100)):
    total += int(digit)
print(total)

The answer is 648. Easy-peasy. Of course, there’s some stuff going on under the hood such as Python’s implementation of factorial or bignum. I might not need to pop open the hood every time I go driving, but it’s good to know what’s under there.