Editor

Python Program to Check a Strong Number

Beginner · Numbers

A strong number is a number equal to the sum of the factorials of its digits, where the factorial of n, written n!, is 1 x 2 x 3 up to n. 145 is a strong number because 1! + 4! + 5! = 1 + 24 + 120 = 145.

Program

strong_number.py
num = 145 # or: num = int(input("Enter a number: "))
total = 0
temp = num # work on a copy so num stays unchanged
while temp > 0:
digit = temp % 10
# Work out the factorial of this digit
fact = 1
for i in range(1, digit + 1):
fact *= i
total += fact
temp //= 10
print(f"Sum of the factorials of the digits of {num}: {total}")
if total == num:
print(num, "is a strong number")
else:
print(num, "is not a strong number")
Output
Sum of the factorials of the digits of 145: 145
145 is a strong number

How it works

  1. temp % 10 takes the last digit and temp //= 10 drops it, so the while loop visits every digit.
  2. The inner for loop works out the factorial of the digit by multiplying 1 x 2 x ... up to the digit.
  3. For the digit 0 the inner loop does not run and fact stays 1, which is right, because 0! is 1.
  4. If the factorials add up to the number itself, it is a strong number.

Another way to write it

Using math.factorial()

Using math.factorial()
import math
def is_strong(n):
return n == sum(math.factorial(int(d)) for d in str(n))
print("Strong numbers up to 50000:")
print([n for n in range(1, 50001) if is_strong(n)])
Output
Strong numbers up to 50000:
[1, 2, 145, 40585]

math.factorial() replaces the inner loop. Only four strong numbers exist in all: 1, 2, 145 and 40585.

Try it yourself

Speed up the check by working out the factorials of 0 to 9 once, into a list, and looking each digit up.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises