Project Euler Problem 20 Statement
$n!$ means $n\times (n-1)\times \dots \times 3\times 2\times 1$
Find the digit sum in the number $100!$
Solution
Python natively supports arbitrary-precision integers and arithmetic with as many digits as necessary to perform a calculation. For example, it takes 158 digits to represent 100! and Python handles it easily.
sum(map(int,str(math.factorial(100))))Text with a dashed underscore will highlight the code section being talked about when moused over or tapped.
To solve this problem, we calculate 100! using the factorial function from the math library and convert the result to a string so we can iterate over each digit individually. Since integers are not directly iterable, we convert the result to a string, allowing us to access each digit individually.
Then, using the map() function, we convert every character-digit back to an integer and add them up for a digit sum using the sum() function.
HackerRank version
HackerRank Project Euler 20 increases the factorial to any number $0\le N\le1000$ and runs 100 test cases.
Python Source Code
import math
for _ in range(int(input())):
N = int(input())
print(sum(map(int, str(math.factorial(N)))))
Last Word
Embrace the power of arbitrary-precision integers and ignore the call to solve it in some primitive way.
See also, Project Euler 16: Digit sum for a large power of 2