Check Strong Number in Python
Explain 145 through 1! + 4! + 5! in a Python digit loop. New programmers practice extraction, a running sum, and why the single zero digit contributes one.
1# Program to check strong number23import math45num = int(input("Enter an integer: "))67total = math.factorial(0) if num == 0 else 08temp = num9while temp > 0:10 digit = temp % 1011 total += math.factorial(digit)12 temp //= 101314if total == num:15 print(num, "is a strong number")16else:17 print(num, "is not a strong number")
Output
145 is a strong number
The contributions 1, 24, and 120 total 145.
In this one
- Compute factorials of separate digits
- Remove decimal digits with //
- Account for 0! in a zero input
How it works
- 1
Read num and initialize total, including the zero-digit case.
- 2
While temp is positive, add the last digit factorial and remove that digit.
- 3
Compare the sum with the original num.
Edge cases
Zero
Enter 0.
Its only digit contributes 0! = 1, so it is not a strong number.
Single digit two
Enter 2.
2! equals 2, so it qualifies.
What's going on
145 is strong because 1! + 4! + 5! equals 1 + 24 + 120, which is 145. A factorial multiplies the positive integers up to a value; 0! is defined as 1.
The while loop takes the last digit with % 10, adds math.factorial(digit), and removes that digit with //= 10. temp changes while num stays available for comparison. For zero, the initialized total is 1 so its one digit contributes 0! even though the loop does not run.
Zero therefore is not strong. Negative input skips the positive-only loop and does not match the original negative number. This is a small integer-property exercise; it does not calculate the factorial of the whole input, only the factorial of each decimal digit.
After this program
If the idea is still fuzzy, read Day 8: Conditional Statements in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 20 conditional programs, or see every topic on Python exercises.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What is summed for 145?
Pick an answer to check it.
Question 2
Why is zero not strong?
Pick an answer to check it.
Questions people ask
What is summed for 145?
The factorials of its digits, 1! + 4! + 5!, not 145!.
Why is zero not strong?
Its one digit has factorial 1, and 1 does not equal 0.
Why use temp instead of changing num?
The comparison still needs the original input after digit extraction finishes.