How to find all the numbers that are equal to the sum of the factorials of their digits in Python

1 Answer

0 votes
# Example: 145 = 1! + 4! + 5! = 1 + 24 + 120 = 145

# Function to compute the factorial of a number
def factorial(n):
    fact = 1
    for i in range(2, n + 1):
        fact *= i
    return fact

# Function to find all numbers equal to the sum of the factorials of their digits
def find_digit_factorial_numbers():
    # Precompute factorials of digits 0-9
    factorials = [factorial(i) for i in range(10)]

    # Define an upper limit (7 * 9! is a safe limit for this problem)
    upper_limit = 7 * factorials[9]

    # Iterate through all numbers and check the condition
    for num in range(10, upper_limit + 1):
        temp = num
        digit_sum = 0

        # Calculate the sum of factorials of digits
        while temp > 0:
            digit = temp % 10
            digit_sum += factorials[digit]
            temp //= 10

        # Check if the number equals the sum of the factorials of its digits
        if digit_sum == num:
            print(f"{num} is a digit factorial number.")

find_digit_factorial_numbers()


'''
run:

145 is a digit factorial number.
40585 is a digit factorial number.

'''

 



answered Nov 9 by avibootz
...