![]() |
VOOZH | about |
Given a number n, find the sum of the first n natural numbers using recursion.
Examples:
Input: n = 3
Output: 6
Explanation: 1 + 2 + 3 = 6
Input: n = 5
Output: 15
Explanation: 1 + 2 + 3 + 4 + 5 = 15
To find the sum of the first n natural numbers using recursion, we define a function recurSum(n-1).
At each step, the function adds the current number n to the sum of all smaller numbers by calling recurSum(n-1).
The recursion continues until the base case is reached, where n = 0, at which point the function returns 0 to stop further calls.
As the recursive calls return back, the intermediate sums are combined step by step, eventually producing the total sum of the first n natural numbers.
6
Time Complexity: O(n)
Space Complexity: O(n) Recursive Space