Sum of the first N terms of the series 2,10, 30, 68,….
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 = 2 + 10 + 30 + 68 + … upto n terms
Examples:
Input: N = 2
Output: 12
2 + 10
= 12
Input: N = 4
Output: 40
2 + 10 + 30 + 68
= 110
Approach: Let, the nth term be denoted by tn.
This problem can easily be solved by splitting each term as follows :
Sn = 2 + 10 + 30 + 68 + ......
Sn = (1+1^3) + (2+2^3) + (3+3^3) + (4+4^3) +......
Sn = (1 + 2 + 3 + 4 + ...unto n terms) + (1^3 + 2^3 + 3^3 + 4^3 + ...upto n terms)
We observed that Sn can broken down into summation of two series.
Hence, the sum of first n terms is given as follows:
Sn = (1 + 2 + 3 + 4 + ...unto n terms) + (1^3 + 2^3 + 3^3 + 4^3 + ...upto n terms)
Sn = n*(n + 1)/2 + (n*(n + 1)/2)^2
Below is the implementation of above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int calculateSum( int n)
{
return n * (n + 1) / 2
+ pow ((n * (n + 1) / 2), 2);
}
int main()
{
int n = 3;
cout << "Sum = " << calculateSum(n);
return 0;
}
|
Java
public class GFG {
static int calculateSum( int n)
{
return n * (n + 1 ) / 2
+ ( int )Math.pow((n * (n + 1 ) / 2 ), 2 );
}
public static void main(String args[])
{
int n = 3 ;
System.out.println( "Sum = " + calculateSum(n));
}
}
|
Python3
def calculateSum(n):
return (n * (n + 1 ) / / 2 +
pow ((n * (n + 1 ) / / 2 ), 2 ))
n = 3
print ( "Sum = " , calculateSum(n))
|
C#
using System;
class gfg
{
public void calculateSum( int n)
{
double r = (n * (n + 1) / 2 +
Math.Pow((n * (n + 1) / 2), 2));
Console.WriteLine( "Sum = " + r);
}
public static int Main()
{
gfg g = new gfg();
int n = 3;
g.calculateSum(n);
Console.Read();
return 0;
}
}
|
PHP
<?php
function calculateSum( $n )
{
return $n * ( $n + 1) / 2 +
pow(( $n * ( $n + 1) / 2), 2);
}
$n = 3;
echo "Sum = " , calculateSum( $n );
?>
|
Javascript
<script>
function calculateSum(n)
{
return n * (n + 1) / 2
+ Math.pow((n * (n + 1) / 2), 2);
}
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.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...