\(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.
Let \(f(n)\) be the sum of the factorial of the digits of \(n\). If \(10^k \leq n \lt 10^{k+1}\), then \(f(n) \leq 9! \cdot (k+1) = 362880(k+1)\). If \(k \geq 7\), then \(362880(k+1) \lt 10^k\), so \(9999999\) is a (loose) upper bound. From there, brute force.
from math import factorial
def p34():
res = 0
fact = list(map(factorial, range(10)))
for n in range(3, 10 ** 7):
n_cpy, f = n, 0
while n_cpy > 0:
f += fact[n_cpy % 10]
n_cpy //= 10
if n == f:
res += n
return res