![]() |
VOOZH | about |
Given an integer N. The task is to find the sum of the first N terms of the series 5, 11, 19, 29, 41, . . . till Nth term.
Examples:
Input: N = 5
Output: 105
Explanation: 5 + 11 + 19 + 29 + 41 = 105.Input: N = 2
Output: 16
Explanation: The terms are 5 and 11
Approach: From the given series first determine the Nth term:
1st term = 5 = 1 + 4 = 1 + 22
2nd term = 11 = 2 + 9 = 2 + 32
3rd term = 19 = 3 + 16 = 3 + 42
4th term = 29 = 4 + 25 = 4 + 52
.
.
Nth term = N + (N+1)2
So the Nth term can be written as: TN = N + (N+1)2
Therefore the sum up to N terms becomes
1 + 22 + 2 + 32 + 3 + 42 + . . . + N + (N+1)2
= [1 + 2 + 3 + . . . + N] + [22 + 32 + 42 + . . . + (N+1)2]
= (N*(N+1))/2 + [(N+1)*(N+2)*(2*N + 3)]/6 - 1
= [N*(N+2)*(N+4)]/3
Therefore the sum of the first N terms can be given as: SN = [N*(N+2)*(N+4)]/3
Illustration:
For example, take N = 5
The output will be 105.
Use N = 5, then N*(N+2)*(N+4)/3
= 5 * 7 * 9/3 = 5 * 7 * 3 = 105.
This is same as 5 + 11 + 19 + 29 + 41
Below is the implementation of the above approach.
105
Time Complexity: O(1)
Auxiliary Space: O(1), since no extra space has been taken.