Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

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.

IntermediatePhase 2 - Level 2: Number-based Looping LogicExample 12 of 14
strong-number-check-with-recursive-factorials.py
1# Helper function for factorial
2def factorial(n):
3 if n == 0 or n == 1:
4 return 1
5 return n * factorial(n - 1)
6
7# Take number
8num = int(input("Enter a number: "))
9
10# Calculate sum of factorial of digits
11temp = abs(num)
12strong_sum = 0
13while temp > 0:
14 digit = temp % 10
15 strong_sum += factorial(digit)
16 temp //= 10
17
18# Check
19if 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. 1

    Define factorial with zero and one base cases.

  2. 2

    Sum factorials of the input magnitude's digits.

  3. 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.