PythonMastery

Strong number program in Python

Check whether a number is a strong number, like 145 = 1! + 4! + 5!, and find every strong number below 100,000.

A strong number is equal to the sum of the factorials of its digits. 145 is a strong number, because 1! + 4! + 5! = 1 + 24 + 120 = 145.

The program

python
import math

n = int(input("Enter a number: "))

digits = [int(d) for d in str(n)]
parts = [math.factorial(d) for d in digits]
total = sum(parts)

print(" + ".join(f"{d}!" for d in digits), "=", " + ".join(str(p) for p in parts), "=", total)

if total == n:
    print(f"{n} is a strong number")
else:
    print(f"{n} is not a strong number")

Typed in this example: 145. Press Run to type your own.

output
Enter a number: 145
1! + 4! + 5! = 1 + 24 + 120 = 145
145 is a strong number

How it works

This is similar to an Armstrong number, which uses powers of the digits instead of factorials.

Finding all of them

A digit can only be 0 to 9, so the program can calculate those ten factorials once, store them in a list, and look them up:

python
import math

DIGIT_FACTORIALS = [math.factorial(d) for d in range(10)]


def is_strong(n):
    return n == sum(DIGIT_FACTORIALS[int(d)] for d in str(n))


print(*[n for n in range(1, 100_000) if is_strong(n)])
output
1 2 145 40585

There are only four strong numbers. 1 and 2 count because 1! = 1 and 2! = 2. The search can stop below 10 million: 9! is 362,880, so an 8-digit number gives a digit sum of at most 8 × 362,880 = 2,903,040. That has only 7 digits, so no number with 8 or more digits can be a strong number.

Learn the idea: Loops: for, while, and the Pythonic Patterns, Functions & Scoping