Find the sum of N terms of the series 1, 4, 13, 40, 121, …
Given a positive integer, n. Find the sum of the first n term of the series:
1, 4, 13, 40, 121, …..
Examples:
Input: n = 5
Output: 179
Input: n = 3
Output: 18
Approach:
The sequence is formed by using the following pattern. For any value N-
The above solution can be derived following the series of steps-
Let Tn be the nth term and Sn be the sum to n terms of the given series.
Thus, we have
-(1)
Equation (1) can be written as-
S_{n}=1+4+13+40+121+…+T_{n-1}+T_{n} -(2)
Subtracting equation (2) from equation (1), we get
The above equation 3, 9, 27, 81, … is a G.P. with common ratio 3 and first term 3.
Thus, we have
Since,
Therefore,
Thus, sum of n terms is
Illustration:
Input: n = 5
Output: 179
Explanation:
=
=
=179
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int findSum( int N)
{
return ( pow (3, N + 1) -
3 - 2 * N) / 4;
}
int main()
{
int N = 5;
cout << findSum(N);
return 0;
}
|
Java
import java.util.*;
public class GFG
{
static int findSum( int N)
{
return ( int )(Math.pow( 3 , N + 1 ) -
3 - 2 * N) / 4 ;
}
public static void main(String args[])
{
int N = 5 ;
System.out.print(findSum(N));
}
}
|
Python3
def findSum(N):
return ( 3 * * (N + 1 ) - 3 - 2 * N) / / 4 ;
N = 5 ;
print (findSum(N));
|
C#
using System;
class GFG
{
static int findSum( int N)
{
return ( int )(Math.Pow(3, N + 1) -
3 - 2 * N) / 4;
}
public static void Main()
{
int N = 5;
Console.Write(findSum(N));
}
}
|
Javascript
<script>
function findSum(N) {
return Math.floor((Math.pow(3, N + 1) -
3 - 2 * N) / 4);
}
let N = 5;
document.write(findSum(N));
</script>
|
Time Complexity: O(log3N) because using inbuilt pow function
Auxiliary Space: O(1)
Last Updated :
16 Aug, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...