$n!$ means $n\times(n-1)\times\cdots\times 3\times 2\times 1$. For example, $10!=10\times 9\times\cdots\times 2\times 1=3628800$ and the sum of the digits in the number $10!$ is 27. Find the sum of the digits in $100!$.

Sage Solution

There is a single-line solution in Sage. I’ve added a bit more here just to determine the timing.

import time
 
start = time.time()
 
s = sum(factorial(100).digits())
 
elapsed = time.time() - start
 
print "Solution %s found after %s seconds" % (s,elapsed)

When executed, we find the following.

Solution 648 found after 0.000201940536499 seconds

Python Solution

Without the built-in functions of Sage, we can build a factorial function and use some string functionality in Python to achieve the same result.

import time
 
def factorial(n):
    if n == 0: return 1
    else: return n * factorial(n - 1)
 
def sum_digits(n):
    return sum([int(i) for i in str(n)])
 
start = time.time()
 
sumfac = sum_digits(factorial(100))
 
elapsed = time.time() - start
 
print("%s found in %s seconds") % (sumfac,elapsed)

When executed, the same result is returned.

648 found in 0.000312805175781 seconds

We could also compute the factorial using a reduced lambda function as in the following code.

#!/usr/bin/python
 
import time
 
 
def factorial(n):
    return reduce(lambda x,y: x*y, range(1,n+1,1))
 
def sum_digits(n):
    return sum([int(i) for i in str(n)])
 
start = time.time()
 
sumfac = sum_digits(factorial(100))
 
elapsed = time.time() - start
 
print("%s found in %s seconds") % (sumfac,elapsed)

Comments are closed