![]() |
VOOZH | about |
Given a positive integer n, find the sum of the first n natural numbers.
Examples :
Input: n = 3
Output: 6
Explanation: 1 + 2 + 3 = 6Input: n = 5
Output: 15
Explanation: 1 + 2 + 3 + 4 + 5 = 15
Table of Content
For example n = 4
Initially : sum = 0
i = 1, sum = sum + 1 = 1
i = 2, sum = sum + 2 = 3
i = 3, sum = sum + 3 = 7
i = 4, sum = sum + 4 = 11
15
In this approach, we use recursion to find the sum of the first n natural numbers. The function calls itself with (n-1) until it reaches the base case of n = 1. Each call adds the current value of n to the sum of smaller values, effectively building the result in a top-down manner.
Sum of first n natural numbers = (n * (n+1)) / 2
For example: n = 5
Sum = (5 * (5 + 1)) / 2 = (5 * 6) / 2 = 30 / 2 = 15
How does this work?
We can prove this formula using induction.
It is true for n = 1 and n = 2
For n = 1, sum = 1 * (1 + 1)/2 = 1
For n = 4, sum = 4* (4 + 1)/2 = 10
Let it be true for k = n-1.
Sum of k numbers = (k * (k+1))/2
Putting k = n-1, we get
Sum of k numbers = ((n-1) * (n-1+1))/2
= (n - 1) * n / 2
If we add n, we get,
Sum of n numbers = n + (n - 1) * n / 2
= (2n + n2 - n)/2
= n * (n + 1)/2
15