Python Program to Find Sum of Natural Numbers Using Recursion
def sum_natural(n): return n if n == 1 else n + sum_natural(n-1) which calls itself until it reaches 1.Examples
How to Think About It
Algorithm
Code
def sum_natural(n): if n == 1: return 1 else: return n + sum_natural(n - 1) number = 10 print("Sum of natural numbers up to", number, "is", sum_natural(number))
Dry Run
Let's trace sum_natural(5) through the code
Call sum_natural(5)
Since 5 != 1, return 5 + sum_natural(4)
Call sum_natural(4)
Since 4 != 1, return 4 + sum_natural(3)
Call sum_natural(3)
Since 3 != 1, return 3 + sum_natural(2)
Call sum_natural(2)
Since 2 != 1, return 2 + sum_natural(1)
Call sum_natural(1)
Since 1 == 1, return 1
Calculate returns
sum_natural(2) = 2 + 1 = 3 sum_natural(3) = 3 + 3 = 6 sum_natural(4) = 4 + 6 = 10 sum_natural(5) = 5 + 10 = 15
| Call | Return Value |
|---|---|
| sum_natural(1) | 1 |
| sum_natural(2) | 3 |
| sum_natural(3) | 6 |
| sum_natural(4) | 10 |
| sum_natural(5) | 15 |
Why This Works
Step 1: Base Case
The function stops calling itself when n == 1, returning 1 to avoid infinite recursion.
Step 2: Recursive Call
For any number greater than 1, the function calls itself with n-1 to break down the problem.
Step 3: Summation
Each call adds the current number n to the sum returned by the smaller problem, building the total sum.
Alternative Approaches
def sum_natural_loop(n): total = 0 for i in range(1, n+1): total += i return total print("Sum using loop:", sum_natural_loop(10))
def sum_natural_formula(n): return n * (n + 1) // 2 print("Sum using formula:", sum_natural_formula(10))
Complexity: O(n) time, O(n) space
Time Complexity
The function calls itself n times, so the time grows linearly with n.
Space Complexity
Each recursive call adds a new layer to the call stack, so space also grows linearly with n.
Which Approach is Fastest?
The formula method is fastest with O(1) time and space, while recursion and loop are O(n).
| Approach | Time | Space | Best For |
|---|---|---|---|
| Recursion | O(n) | O(n) | Learning recursion and small inputs |
| Loop | O(n) | O(1) | Simple iterative calculation |
| Formula | O(1) | O(1) | Fastest for any input size |