Python Program to Find Factorial Using Recursion
def factorial(n): return 1 if n == 0 else n * factorial(n-1) which calls itself until it reaches zero.Examples
How to Think About It
Algorithm
Code
def factorial(n): if n == 0: return 1 else: return n * factorial(n - 1) print(factorial(5))
Dry Run
Let's trace factorial(5) through the code
Call factorial(5)
Since 5 != 0, return 5 * factorial(4)
Call factorial(4)
Since 4 != 0, return 4 * factorial(3)
Call factorial(3)
Since 3 != 0, return 3 * factorial(2)
Call factorial(2)
Since 2 != 0, return 2 * factorial(1)
Call factorial(1)
Since 1 != 0, return 1 * factorial(0)
Call factorial(0)
Since 0 == 0, return 1
Return values back up
factorial(1) = 1 * 1 = 1 factorial(2) = 2 * 1 = 2 factorial(3) = 3 * 2 = 6 factorial(4) = 4 * 6 = 24 factorial(5) = 5 * 24 = 120
| Call | Return Value |
|---|---|
| factorial(0) | 1 |
| factorial(1) | 1 |
| factorial(2) | 2 |
| factorial(3) | 6 |
| factorial(4) | 24 |
| factorial(5) | 120 |
Why This Works
Step 1: Base Case
The function stops calling itself when it reaches n == 0, returning 1 because factorial of zero is defined as 1.
Step 2: Recursive Call
For any other number, the function calls itself with n-1, breaking the problem into smaller parts.
Step 3: Multiplying Results
Each call multiplies the current number n by the factorial of n-1, building up the final factorial value.
Alternative Approaches
def factorial_iterative(n): result = 1 for i in range(1, n + 1): result *= i return result print(factorial_iterative(5))
import math print(math.factorial(5))
Complexity: O(n) time, O(n) space
Time Complexity
The function calls itself n times, so the time grows linearly with the input number.
Space Complexity
Each recursive call adds a new layer to the call stack, so space used is proportional to n.
Which Approach is Fastest?
The iterative and math module methods use constant space and are faster in practice, but recursion is clearer for learning.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Recursion | O(n) | O(n) | Learning recursion and simple code |
| Iterative | O(n) | O(1) | Performance and memory efficiency |
| math.factorial | O(n) | O(1) | Quick and optimized built-in solution |