Find the Sum of the series 1 + 2 + 9 + 64 + 625 + 7776 … till N terms
Last Updated :
16 Aug, 2022
Given a number N, the task is to find the sum of the below series till N terms.
Examples:
Input: N = 2
Output: 3
1 + 2 = 3
Input: N = 5
Output: 701
1 + 2 + 9 + 64 + 625 = 701
Approach: From the given series, find the formula for Nth term:
1st term = 1 = 11-1
2nd term = 2 = 22-1
3rd term = 9 = 33-1
4th term = 64 = 44-1
.
.
Nth term = NN - 1
Therefore:
Nth term of the series
Then iterate over numbers in the range [1, N] to find all the terms using the above formula and compute their sum.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void printSeriesSum( int N)
{
long long sum = 0;
for ( int i = 1; i <= N; i++) {
sum += pow (i, i - 1);
}
cout << sum << endl;
}
int main()
{
int N = 5;
printSeriesSum(N);
return 0;
}
|
Java
class GFG{
static void printSeriesSum( int N)
{
long sum = 0 ;
for ( int i = 1 ; i <= N; i++) {
sum += Math.pow(i, i - 1 );
}
System.out.print(sum + "\n" );
}
public static void main(String[] args)
{
int N = 5 ;
printSeriesSum(N);
}
}
|
Python3
def printSeriessumm(N):
summ = 0
for i in range ( 1 ,N + 1 ):
summ + = pow (i, i - 1 )
print (summ)
N = 5
printSeriessumm(N)
|
C#
using System;
class GFG{
static void printSeriesSum( int N)
{
double sum = 0;
for ( int i = 1; i <= N; i++) {
sum += Math.Pow(i, i - 1);
}
Console.Write(sum + "\n" );
}
public static void Main(String[] args)
{
int N = 5;
printSeriesSum(N);
}
}
|
Javascript
<script>
function printSeriesSum( N)
{
let sum = 0;
for (let i = 1; i <= N; i++) {
sum += Math.pow(i, i - 1);
}
document.write(sum);
}
let N = 5;
printSeriesSum(N);
</script>
|
Time Complexity: O(N * log N)
Auxiliary Space: O(1), since no extra space has been taken.
Share your thoughts in the comments
Please Login to comment...