Nov
24
Project Euler: Summing digits in a factorial
Filed Under hisabati, project euler by Mucheru
For problem 20, the goal is to sum all the digits in a large number:
Find the sum of the digits in the number 100!
The algorithm proceeds as follows:
1: def factorial(n): 2: if(n == 0): 3: return 1 4: else: 5: return (n * factorial(n-1)) 6: 7: def sum_factorial(n): 8: fact = factorial(n) 9: digits = [int(x) for x in str(fact)] 10: return sum(digits)
The factorial() function is defined in a pretty straightforward recursive algorithm. The interesting line stuff happens in the sum_factorial() function (specifically on line 9). We use a list comprehension to unpack the digits in the factorial number into a list object. When the comprehension is evaluated, the call to str() converts the factorial number to a string (which is iterable). We take each character in the string and call int() on it to convert it to an integer. The collection of integers is then collected into a list. the call to sum() on line 10 takes a list of integers and returns a single number which is the sum.