$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!$.
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
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
So, the Sage version runs about 1.5 times as fast. I don’t want to write this in Cython for now since the number $100!$ is going to be a bit long and I’d initially have to resort to using the arbitrary length Longs in Python, pretty much negating any speedup I would achieve by using C.