Python Program to Find Strong Number
sum(math.factorial(int(digit)) for digit in str(number)) == number.Examples
How to Think About It
Algorithm
Code
import math def is_strong_number(num): total = sum(math.factorial(int(digit)) for digit in str(num)) if total == num: print(f"{num} is a strong number") else: print(f"{num} is not a strong number") # Example usage is_strong_number(145)
Dry Run
Let's trace the number 145 through the code
Convert number to string
str(145) -> '145'
Calculate factorial of each digit
factorial(1) = 1, factorial(4) = 24, factorial(5) = 120
Sum factorials
1 + 24 + 120 = 145
Compare sum with original number
145 == 145 -> True
Print result
"145 is a strong number"
| Digit | Factorial |
|---|---|
| 1 | 1 |
| 4 | 24 |
| 5 | 120 |
Why This Works
Step 1: Breaking number into digits
Converting the number to a string lets us look at each digit separately using str(num).
Step 2: Calculating factorial
We use math.factorial() to find the factorial of each digit, which is the product of all positive integers up to that digit.
Step 3: Comparing sum to original
If the sum of all digit factorials equals the original number, it means the number is strong.
Alternative Approaches
def factorial(n): result = 1 for i in range(2, n+1): result *= i return result def is_strong_number(num): total = sum(factorial(int(d)) for d in str(num)) if total == num: print(f"{num} is a strong number") else: print(f"{num} is not a strong number") is_strong_number(145)
def factorial(n): if n == 0 or n == 1: return 1 return n * factorial(n-1) def is_strong_number(num): total = sum(factorial(int(d)) for d in str(num)) if total == num: print(f"{num} is a strong number") else: print(f"{num} is not a strong number") is_strong_number(145)
Complexity: O(d) time, O(1) space
Time Complexity
The program loops through each digit once, calculating factorial which is O(1) for digits 0-9, so overall O(d) where d is number of digits.
Space Complexity
Uses constant extra space for sum and factorial calculations, so O(1).
Which Approach is Fastest?
Using math.factorial() is fastest and simplest; manual or recursive factorial methods add overhead.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Using math.factorial | O(d) | O(1) | Simplicity and speed |
| Manual factorial loop | O(d) | O(1) | No imports allowed |
| Recursive factorial | O(d) | O(1) | Learning recursion |
math.factorial() for clean and fast factorial calculation in Python.