Digit Factorials¶

Numbers like 145 are called factorions.

We can use similar logic as problem 30 to produce an upper bound for how many numbers to brute force. Let $f(n)$ be the sum of the factorials of the digits of $n$, and consider the largest seven digit number, 9999999. $f(9999999) = 7 \times 9! = 2540160$. If we replaced any digits in 9999999, they would have to be smaller than 9, so the sum of the factorials of the digits would be smaller than 2540160. Therefore, for any $n \leq 9999999$, $f(n) \leq 2540160$, so for $n$ to equal $f(n)$, $n$ must be less than or equal to 2540160, as well.

We can write a simple recursive function for calculating the sum of the factorials of the digits:

In [1]:
from functools import cache
from math import factorial

@cache
def sfd(n):
    q = n // 10
    if q == 0:
        return factorial(n)
    
    return factorial(n % 10) + sfd(q)

Now we just iterate over all the numbers less than our upper bound.

In [2]:
factorions = {n for n in range(3, 2540161) if sfd(n) == n}
factorions
Out[2]:
{145, 40585}

Interestingly, there's only two factorions!

In [3]:
sum(factorions)
Out[3]:
40730

Relevant sequences¶

  • Factorions: A014080

Copyright (C) 2025 filifa¶

This work is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license and the BSD Zero Clause license.