Find n-th term of series 1, 4, 27, 16, 125, 36, 343 …….
Last Updated :
20 Feb, 2023
Given a number n, find the n-th term in the series 1, 4, 27, 16, 125, 36, 343……..
Examples:
Input : 5
Output : 125
Input : 6
Output : 36
Naive approach : In this Sequence, if the Nth term is even then the Nth term is square of N else Nth term is a cube of N.
N = 5
In this case, N is odd
N = N * N * N
N = 5 * 5 * 5
N = 125
Similarly,
N = 6
N = N * N
N = 6 * 6
N = 36 and so on..
Implementation of the above approach is given below:
C++
#include <bits/stdc++.h>
using namespace std;
int logicOfSequence( int N)
{
if (N % 2 == 0)
N = N * N;
else
N = N * N * N;
return N;
}
int main()
{
int N = 6;
cout << logicOfSequence(N) << endl;
return 0;
}
|
Java
class GFG {
public static int logicOfSequence( int N)
{
if (N % 2 == 0 )
N = N * N;
else
N = N * N * N;
return N;
}
public static void main(String args[])
{
int N = 6 ;
System.out.println(logicOfSequence(N));
}
}
|
Python 3
def logicOfSequence(N):
if (N % 2 = = 0 ):
N = N * N
else :
N = N * N * N
return N
N = 6
print (logicOfSequence(N))
|
C#
using System;
class GFG {
public static int logicOfSequence( int N)
{
if (N % 2 == 0)
N = N * N;
else
N = N * N * N;
return N;
}
public static void Main()
{
int N = 6;
Console.Write(logicOfSequence(N));
}
}
|
PHP
<?php
function logicOfSequence( $N )
{
if ( $N % 2 == 0)
$N = $N * $N ;
else
$N = $N * $N * $N ;
return $N ;
}
$N = 6;
echo logicOfSequence( $N );
?>
|
Javascript
<script>
function logicOfSequence( N)
{
if (N % 2 == 0)
N = N * N;
else
N = N * N * N;
return N;
}
let N = 6;
document.write(logicOfSequence(N));
</script>
|
Output:
36
Time Complexity: O(1)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...