Fun with Factorions

Also known as Project Euler problem 34:

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.

According to Wikipedia, A factorion is a natural number that equals the sum of the factorials of its decimal digits. So now we know what we are looking at. Wikipedia also tells us how many decimal factorians exists, but I wrote some code anyway.

The first part of this is to determine whether a given number is a factorian:

import math

def is_factorion(integer):
    """ Returns True if integer is a factorion, else False
        See problem 34 for a more detailed explanation """
    digit_sum = 0
    for n in str(integer):
        digit_sum += math.factorial(int(n))
    if digit_sum == integer:
        return True
        return False

And then for the reason I found myself googling this: What is the range of numbers I need to check?

It turns out that:

If n is a natural number of d digits that is a factorion, then 10d − 1 ≤ n ≤ 9!d. This fails to hold for d ≥ 8 thus n has at most 7 digits, and the first upper bound is 9,999,999. But the maximum sum of factorials of digits for a 7 digit number is 9!7 = 2,540,160 establishing the second upper bound.

Problem 34 tells us to ignore 1 and 2 so the solution can be derived by simply summing each number between 3 and 2540160 for which is_factorion is True.