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++ code to implement the above approach #include <bits/stdc++.h> using namespace std;
// Function to calculate // the sum of first N terms int nthSum( int N)
{ // Formula for sum of N terms
int ans = (N * (N + 2) * (N + 4)) / 3;
return ans;
} // Driver code int main()
{ int N = 5;
cout << nthSum(N);
return 0;
} |
// Java program for the above approach import java.util.*;
public class GFG
{ // Function to calculate
// the sum of first N terms
static int nthSum( int N)
{
// Formula for sum of N terms
int ans = (N * (N + 2 ) * (N + 4 )) / 3 ;
return ans;
}
// Driver code
public static void main(String args[])
{
int N = 5 ;
System.out.println(nthSum(N));
}
} // This code is contributed by Samim Hossain Mondal. |
# Python code to implement the above approach # Function to calculate # the sum of first N terms def nthSum(N):
# Formula for sum of N terms
ans = ( int )((N * (N + 2 ) * (N + 4 )) / 3 )
return ans
# Driver code N = 5
print (nthSum(N))
# This code is contributed by Taranpreet |
// C# program for the above approach using System;
class GFG
{ // Function to calculate // the sum of first N terms static int nthSum( int N)
{ // Formula for sum of N terms
int ans = (N * (N + 2) * (N + 4)) / 3;
return ans;
} // Driver code public static void Main()
{ int N = 5;
Console.Write(nthSum(N));
} } // This code is contributed by Samim Hossain Mondal. |
<script> // JavaScript code for the above approach
// Function to calculate
// the sum of first N terms
function nthSum(N)
{
// Formula for sum of N terms
let ans = (N * (N + 2) * (N + 4)) / 3;
return ans;
}
// Driver code
let N = 5;
document.write(nthSum(N));
// This code is contributed by Potta Lokesh
</script> |
105
Time Complexity: O(1)
Auxiliary Space: O(1), since no extra space has been taken.