Strong Number Check with Recursive Factorials
Recognize strong numbers with a recursive factorial helper. Students trace digit factorials, recursion's base case, and the positive-input check for zero.
1# Helper function for factorial2def factorial(n):3 if n == 0 or n == 1:4 return 15 return n * factorial(n - 1)67# Take number8num = int(input("Enter a number: "))910# Calculate sum of factorial of digits11temp = abs(num)12strong_sum = 013while temp > 0:14 digit = temp % 1015 strong_sum += factorial(digit)16 temp //= 101718# Check19if abs(num) > 0 and abs(num) == strong_sum:20 print("Strong number")21else:22 print("Not a strong number")
Output
Enter a number: 145 Strong number
In this one
- Use a recursive helper
- Define zero factorial
- Reject a skipped-loop false positive
How it works
- 1
Define factorial with zero and one base cases.
- 2
Sum factorials of the input magnitude's digits.
- 3
Require a positive magnitude equal to that sum.
Edge cases
Is zero strong?
Is zero strong?
No. 0! is one; a skipped digit loop must not make zero pass.
Why must factorial stop at zero or one?
Why must factorial stop at zero or one?
Without a base case, calls do not finish and eventually exceed Python's recursion limit.
What's going on
A strong number equals the sum of its digits' factorials. The helper returns one for zero and one; larger digit factorials multiply while recursive calls count downward.
The digit loop adds factorial(digit), not digit raised to a power. For 145, the total is 1 + 24 + 120. Recursion keeps unfinished calls on the call stack, Python's record of pending work, until a base case returns.
Is zero strong? No. 0! is one; a skipped digit loop must not make zero pass.
Why must factorial stop at zero or one? Without a base case, calls do not finish and eventually exceed Python's recursion limit.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Which number is strong?
Pick an answer to check it.
Question 2
Is zero strong?
Pick an answer to check it.
Questions people ask
Is zero strong?
No. 0! is one; a skipped digit loop must not make zero pass.
Why must factorial stop at zero or one?
Without a base case, calls do not finish and eventually exceed Python's recursion limit.
Which number is strong?
145.
๐Related Content
- ๐
Phase 2 - Learn Concepts
Review Phase 2 concepts and explanations
- ๐
Phase 2 - Quiz
Test your Phase 2 understanding with quiz questions
- ๐ป
Phase 2 - All Practice Problems
Explore all practice problems for Phase 2
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum