Select Page

Project Euler 20 Problem Statement

n! means n × (n − 1) × … × 3 × 2 × 1

Find the digit sum in the number 100!


Python natively supports arbitrary-precision integers and arithmetic with as many digits as necessary to perform a calculation.  100! requires 158 digits to represent this factorial and Python handles it easily.

We import the factorial function from the math library to handle the calculations.

from math import factorial

To solve this problem we calculate 100! and convert the result to a string so we can iterate over each character-digit (integers are not iterable, but strings are).

sum(map(int, str(factorial(100))))

Then, using the map function we iterate over the string and convert every character-digit back to an integer using the int function.

Finally, we add the digits together for a digit sum using the sum function.

 sum(map(int, str(factorial(100))))

HackerRank version

HackerRank increases the factorial from 100 to 1,000 and runs 100 trials.  This solution was fast enough to handle these parameters.

Python 2.7 Source

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 – SOLVED