Find Nth term of the series 1, 5, 32, 288 …
Last Updated :
19 Sep, 2022
Given a number n, the task is to find the n-th term in series 1, 5, 32, 288 …
Examples:
Input: N = 3
Output: 32
Explanation:
3rd term = 3^3 + 2^2 + 1^1
= 32
Input: N = 4
Output: 288
Explanation:
4th term = 4^4 + 3^3 + 2^2 + 1^1
= 288
Approach:
Nth term = n^n + (n-1)^(n-1) + (n-2)^(n-2) + ……..1^1.
Implementation of the above approach is given below:
C++
#include <bits/stdc++.h>
using namespace std;
int nthTerm( int N)
{
int nth = 0, i;
for (i = N; i > 0; i--) {
nth += pow (i, i);
}
return nth;
}
int main()
{
int N = 3;
cout << nthTerm(N) << endl;
return 0;
}
|
Java
import java.lang.Math;
class GFG {
public static int nthTerm( int N)
{
int nth = 0 , i;
for (i = N; i > 0 ; i--) {
nth += Math.pow(i, i);
}
return nth;
}
public static void main(String[] args)
{
int N = 3 ;
System.out.println(nthTerm(N));
}
}
|
Python3
def nthTerm(N):
nth = 0
for i in range (N, 0 , - 1 ):
nth + = pow (i, i)
return nth
N = 3
print (nthTerm(N))
|
C#
using System;
class GFG
{
public static int nthTerm( int N)
{
int nth = 0, i;
for (i = N; i > 0; i--)
{
nth +=( int )Math.Pow(i, i);
}
return nth;
}
public static void Main()
{
int N = 3;
Console.WriteLine(nthTerm(N));
}
}
|
PHP
<?php
function nthTerm( $N )
{
$nth = 0; $i ;
for ( $i = $N ; $i > 0; $i --)
{
$nth += pow( $i , $i );
}
return $nth ;
}
$N = 3;
echo (nthTerm( $N ));
?>
|
Javascript
<script>
function nthTerm(N)
{
let nth = 0, i;
for (i = N; i > 0; i--)
{
nth += Math.pow(i, i);
}
return nth;
}
let N = 3;
document.write(nthTerm(N));
</script>
|
Time Complexity: O(NlogN), since there is one loop used and the inbuilt pow function takes O(logN) time.
Auxiliary Space: O(1), since no extra space has been taken.
Share your thoughts in the comments
Please Login to comment...