For problem 20, the goal is to sum all the digits in a large number:

n! = n\times (n-1) \times \ldots \times 3 \times 2 \times 1

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))
  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.


Comments are closed.