Euler Problem 34

Back to overview.

145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.

Find the sum of all numbers which are equal to the sum of the factorial of their digits.

Note: as 1! = 1 and 2! = 2 are not sums they are not included.

The algorithm for checking if a number is curious should be efficient. The more difficult thing is to select the upper bound for the brute force. It can be seen that $9 999 999 < 9! * 7$. Hence we can select $10^7$ as our bound.

In [1]:
from math import factorial

def is_curious(n):
    s = sum([factorial(int(d)) for d in str(n)])
    return n == s

assert(is_curious(145) == True)
In [2]:
s = sum([n for n in range(3, 10**7) if is_curious(n)])
In [3]:
assert(s == 40730)
s
Out[3]:
40730