Project Euler 20: Factorial Digit Sum

Factorial Digit Sum

Warning: Please only read this post, when you are absolutely sure, that you don’t want to take part in the challenge that is Project Euler. My posts will spoil the solution for you. I’m posting my solutions to show one possible way on how to solve the problems in case you want to compare your solutions with mine or are stuck and gave up on solving the problem.

Problem 20 has you calculate the digit sum of “100!”. “100!” is the factorial of 100 and equates to 1 * 2 * 3 * … * 99 * 100. And from this product we want to know the digit sum. We have already calculated the digit sum of another long integer in a previous Project Euler problem (Problem 16),  therefore I’m going to keep this post rather short.

Since we don’t have to worry, that 100! overflows our range for integers in Python, we can simply calculate 100! and store it regularly in a variable. We are going to use the same trick as in Problem 16 to calculate the digit sum. We use the built-in function sum, that returns the sum of a given list. And the list we are going to give as parameter is the single digits of 100!. This is produced by using another built-in function called map(), which applies a given function, in our case int(), to a list. This parameter is going to be the str() of 100!, which can be seen as a list of single characters. This chain of function calls ultimately gives us the digit sum.

So here’s the code:

"""Digit sum of 100!"""

def euler20():
    """Calculates solution of Problem 20"""
    counter = 1
    for i in range(2, 101):
        counter *= i
    counter = sum(map(int,str(counter)))
    print("Result: " + str(counter))

euler20()

Problem 20 was really easy to solve, especially since we already knew how to quickly calculate the digit sum of a given number and didn’t have to worry for an overflow caused by storing 100!. The processing speed was sufficient and not really interesting, considering the simplicity of the problem solution.

Have a nice evening!

The post Project Euler 20: Factorial Digit Sum appeared first on Rather Read.