Project Euler Problem 034
Statement
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.
Solution
This is pretty similar to problem 30, but instead of the digits being powered to 5.
It's their factorial instead. For performance issues I store the results of the
digits of the factorials in a dictionary.
factorials = { 0: 1, 1:1, 2:2, 3:6, 4:24, 5:120, 6:720, 7:5040, 8:40320, 9:362880 } def find_limit(): limit = '9' while factorials[9] * len(limit) > int(limit): limit += '9' return int(limit) def is_sum_of_factorial_digits(n): sum_d = 0 for digit in str(n): sum_d += factorials[int(digit)] if sum_d > n: return False if sum_d == n: return True return False if __name__ == '__main__': limit = find_limit() result = sum(i for i in range(10, limit + 1) if is_sum_of_factorial_digits(i)) print("The result is:", result)
The Python file is available for download here.