Digit factorials

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.


Idea

The key to this problem is to determine the upper bound of search sapce.

But it is hard for me to determine the bound, so I first estimate the bound as $ 10^7 $, since $ 9! $ is 362880. And check this result in Euler, and it passes. LOL....


In [1]:
from math import factorial
In [2]:
digit_factorials = list(map(factorial, range(10)))
In [3]:
digit_factorials
Out[3]:
[1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]
In [4]:
def digit_factorial_sum(n):
    s = 0
    while n:
        s += digit_factorials[n % 10]
        n //= 10
    return s
In [5]:
def solve(bound):
    results = []
    for i in range(3, int(bound)):
        if digit_factorial_sum(i) == i:
            results.append(i)
    return sum(results), results
In [6]:
solve(1e7)
Out[6]:
(40730, [145, 40585])