Find sum of first N terms of the series 5, 11, 19, 29, 41, . . .
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.
C++
#include <bits/stdc++.h>
using namespace std;
int nthSum( int N)
{
int ans = (N * (N + 2) * (N + 4)) / 3;
return ans;
}
int main()
{
int N = 5;
cout << nthSum(N);
return 0;
}
|
Java
import java.util.*;
public class GFG
{
static int nthSum( int N)
{
int ans = (N * (N + 2 ) * (N + 4 )) / 3 ;
return ans;
}
public static void main(String args[])
{
int N = 5 ;
System.out.println(nthSum(N));
}
}
|
Python3
def nthSum(N):
ans = ( int )((N * (N + 2 ) * (N + 4 )) / 3 )
return ans
N = 5
print (nthSum(N))
|
C#
using System;
class GFG
{
static int nthSum( int N)
{
int ans = (N * (N + 2) * (N + 4)) / 3;
return ans;
}
public static void Main()
{
int N = 5;
Console.Write(nthSum(N));
}
}
|
Javascript
<script>
function nthSum(N)
{
let ans = (N * (N + 2) * (N + 4)) / 3;
return ans;
}
let N = 5;
document.write(nthSum(N));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1), since no extra space has been taken.