Sum of the first N terms of the series 5,12, 23, 38….
Last Updated :
31 May, 2022
Given a number N, the task is to find the sum of first N terms of the below series:
Sn = 5 + 12 + 23 + 38 + … upto n terms
Examples:
Input: N = 2
Output: 17
5 + 12
= 17
Input: N = 4
Output: 80
5 + 12 + 23 + 38
= 78
Approach: Let, the nth term be denoted by tn.
This problem can easily with the help of a general formula for these type of series,
The series given above is a quadratic series. They are special because the difference of consecutive terms of this series will be in arithmetic progression.
There general formula is given by:
General Formula = a*(n^2) + b*n + c
Now, by putting first 3 terms of series in general formula we can get values of a, b and c.
Sn = 5 + 12 + 30 + 68 + ......
tn = 2 * (n^2) + n + 2
Sn = 2 * (n * (n+1) * (2 * n+1)/6) + n * (n+1)/2 + 2 * (n)
Below is the implementation of above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int calculateSum( int n)
{
return 2 * (n * (n + 1) * (2 * n + 1) / 6)
+ n * (n + 1) / 2 + 2 * (n);
}
int main()
{
int n = 3;
cout << "Sum = " << calculateSum(n);
return 0;
}
|
Java
import java.io.*;
class GFG {
static int calculateSum( int n)
{
return 2 * (n * (n + 1 ) * ( 2 * n + 1 ) / 6 )
+ n * (n + 1 ) / 2 + 2 * (n);
}
public static void main (String[] args) {
int n = 3 ;
System.out.print( "Sum = " + calculateSum(n));
}
}
|
Python 3
def calculateSum(n) :
return ( 2 * (n * (n + 1 ) *
( 2 * n + 1 ) / / 6 ) + n *
(n + 1 ) / / 2 + 2 * (n))
if __name__ = = "__main__" :
n = 3
print ( "Sum =" ,calculateSum(n))
|
C#
using System;
class GFG
{
static int calculateSum( int n)
{
return 2 * (n * (n + 1) * (2 * n + 1) / 6) +
n * (n + 1) / 2 + 2 * (n);
}
public static void Main ()
{
int n = 3;
Console.WriteLine( "Sum = " + calculateSum(n));
}
}
|
PHP
<?php
function calculateSum( $n )
{
return 2 * ( $n * ( $n + 1) *
(2 * $n + 1) / 6) +
$n * ( $n + 1) /
2 + 2 * ( $n );
}
$n = 3;
echo "Sum = " . calculateSum( $n );
?>
|
Javascript
<script>
function calculateSum(n)
{
return 2 * (n * (n + 1) * (2 * n + 1) / 6)
+ n * (n + 1) / 2 + 2 * (n);
}
let n = 3;
document.write( "Sum = " + calculateSum(n));
</script>
|
Time Complexity: O(1), the code will run in a constant time.
Auxiliary Space: O(1), no extra space is required, so it is a constant.
Share your thoughts in the comments
Please Login to comment...