A strong number is a nonnegative integer equal to the sum of the factorials of its digits. For example, 145 = 1! + 4! + 5! = 1 + 24 + 120.
Run the Python examples, compare expected outputs, modify the code, and complete guided exercises.
View on GitHubfrom math import factorial
n = 145
total = sum(factorial(int(ch)) for ch in str(n))
print("Sum of digit factorials:", total)
print("Strong number:", total == n)
Output:
Sum of digit factorials: 145
Strong number: True
The digit factorial is different from the factorial of the whole number.
The original tutorial implements factorial using a loop. This helper is useful for understanding how the digit test works.
def my_factorial(n):
result = 1
for i in range(1, n + 1):
result *= i
return result
print(my_factorial(5))
Output:
120
Convert each character to a digit and compare with the original positive integer.
from math import factorial
raw = input("Enter a nonnegative whole number: ").strip()
if not raw.isdecimal():
print("Enter digits only")
else:
n = int(raw)
total = sum(factorial(int(digit)) for digit in str(n))
print("Sum:", total)
print("Strong number:", total == n)
Output:
Sum: 145
Strong number: True
The result is a Boolean, which can be reused in filters and loops.
from math import factorial
def is_strong(n):
return n >= 0 and sum(factorial(int(ch)) for ch in str(n)) == n
for number in (1, 2, 145, 146, 40585):
print(number, is_strong(number))
Output:
1 True
2 True
145 True
146 False
40585 True
The original lesson found 145 and 40585 between 10 and 100000. The improved function also handles the single-digit numbers 1 and 2.
from math import factorial
facts = [factorial(i) for i in range(10)]
def strong(n):
return n >= 0 and sum(facts[int(ch)] for ch in str(n)) == n
print([n for n in range(1, 100000) if strong(n)])
Output:
[1, 2, 145, 40585]
Because 0! = 1, zero does not equal the factorial sum of its digits.
from math import factorial
print("0!:", factorial(0))
print("0 is strong:", factorial(0) == 0)
Output:
0!: 1
0 is strong: False
Display each factorial term so the equality becomes easy to inspect.
from math import factorial
n = 145
terms = [factorial(int(d)) for d in str(n)]
print(" + ".join(map(str, terms)), "=", sum(terms))
Output:
1 + 24 + 120 = 145
input() returns a string. Convert and validate the value before doing arithmetic.Try 2, 145, 146 and 40585, then list strong numbers below 100000. Use the companion practice notebook for runnable examples and self-checks.
Yes: 1! + 4! + 5! = 145.
No, 0! is 1.
No. Strong numbers use digit factorials; Armstrong numbers use powers.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.