![]() |
VOOZH | about |
Given a positive integer n. The task is to find the sum of the sum of first n natural number.
Examples:
Input: n = 3
Output: 10
Explanation:
Sum of first natural number: 1
Sum of first and second natural number: 1 + 2 = 3
Sum of first, second and third natural number = 1 + 2 + 3 = 6
Sum of sum of first three natural number = 1 + 3 + 6 = 10Input: n = 2
Output: 4
Sum of Natural Numbers is represented by Triangular Numbers. A simple solution is to one by one add triangular numbers.
20
Time Complexity: O(N), for traversing from 1 till N to calculate the required sum.
Auxiliary Space: O(1), as constant extra space is required.
An efficient solution is to use direct formula n(n+1)(n+2)/6
Mathematically, we need to find, Sum(((i * (i + 1))/2)), where 1 <= i <= n
So, lets solve this summation,
Sum = ? ((i * (i + 1))/2), where 1 <= i <= n
= (1/2) * ? (i * (i + 1))
= (1/2) * ? (i2 + i)
= (1/2) * (? i2 + ? i)
We know ? i2 = n * (n + 1) * (2*n + 1) / 6 and
? i = n * ( n + 1) / 2.
Substituting the value, we get,
Sum = (1/2) * ((n * (n + 1) * (2*n + 1) / 6) + (n * ( n + 1) / 2))
= n * (n + 1)/2 [(2n + 1)/6 + 1/2]
= n * (n + 1) * (n + 2) / 6
Below is the implementation of the above approach:
20
Time Complexity: O(1), as constant operations are being performed.
Auxiliary Space: O(1), as constant extra space is required.