Python Program to Check if a Number is a Strong Number

A strong number is a number whose sum of all digits' factorial equals the original number. For example, 145 is a strong number because 1! + 4! + 5! = 1 + 24 + 120 = 145. We can check this using the modulus operator and loops to extract digits and calculate factorials.

Example

Let's check if 145 is a strong number ?

def factorial(n):
    if n == 0 or n == 1:
        return 1
    fact = 1
    for i in range(1, n + 1):
        fact = fact * i
    return fact

my_sum = 0
my_num = 145
print("The number is")
print(my_num)
temp = my_num

while(my_num):
    remainder = my_num % 10
    my_sum = my_sum + factorial(remainder)
    my_num = my_num // 10

if(my_sum == temp):
    print("The number is a strong number")
else:
    print("The number is not a strong number")
The number is
145
The number is a strong number

Using Pre-computed Factorials

For efficiency, we can pre-compute factorials of digits 0-9 ?

# Pre-computed factorials for digits 0-9
factorials = [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]

def is_strong_number(num):
    original = num
    digit_sum = 0
    
    while num > 0:
        digit = num % 10
        digit_sum += factorials[digit]
        num //= 10
    
    return digit_sum == original

# Test with multiple numbers
test_numbers = [1, 2, 145, 40585]
for number in test_numbers:
    if is_strong_number(number):
        print(f"{number} is a strong number")
    else:
        print(f"{number} is not a strong number")
1 is a strong number
2 is a strong number
145 is a strong number
40585 is a strong number

How It Works

The algorithm follows these steps:

  • Extract each digit using modulus operator (% 10)
  • Calculate factorial of each digit
  • Sum all the factorials
  • Compare the sum with the original number
  • Remove the last digit using integer division (// 10)

Common Strong Numbers

Here are the first few strong numbers ?

factorials = [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]

def find_strong_numbers(limit):
    strong_numbers = []
    for num in range(1, limit):
        temp = num
        digit_sum = 0
        
        while temp > 0:
            digit = temp % 10
            digit_sum += factorials[digit]
            temp //= 10
        
        if digit_sum == num:
            strong_numbers.append(num)
    
    return strong_numbers

strong_nums = find_strong_numbers(50000)
print("Strong numbers up to 50000:")
print(strong_nums)
Strong numbers up to 50000:
[1, 2, 145, 40585]

Conclusion

A strong number equals the sum of factorials of its digits. Use modulus and integer division to extract digits, then compare the factorial sum with the original number. Pre-computing factorials improves efficiency for multiple checks.

Updated on: 2026-03-25T19:22:33+05:30

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements