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
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.
Enter a number: 145 1! + 4! + 5! = 1 + 24 + 120 = 145 145 is a strong number
How it works
str(n)gives the digits as text, andint(d)turns each one back into a number:[1, 4, 5].math.factorial(d)calculates d!, so the parts are[1, 24, 120].- The program prints the whole sum, so you can check it by hand. For 123 it prints
1! + 2! + 3! = 1 + 2 + 6 = 9, and 9 is not 123. - The program is for positive numbers. A minus sign is not a digit, so
int("-")would raise aValueError.
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:
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)])
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.