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++
// CPP code to generate first 'n' terms // of Logic sequence #include <bits/stdc++.h> using namespace std; // Function to generate a fixed \number int logicOfSequence( int N) { if (N % 2 == 0) N = N * N; else N = N * N * N; return N; } // Driver Method int main() { int N = 6; cout << logicOfSequence(N) << endl; return 0; } |
Java
// JAVA code to generate first // 'n' terms of Logic sequence class GFG { // Function to generate // a fixed \number public static int logicOfSequence( int N) { if (N % 2 == 0 ) N = N * N; else N = N * N * N; return N; } // Driver Method public static void main(String args[]) { int N = 6 ; System.out.println(logicOfSequence(N)); } } // This code is contributed by Jaideep Pyne |
Python 3
# Python code to generate first # 'n' terms of Logic sequence # Function to generate a fixed # number def logicOfSequence(N): if (N % 2 = = 0 ): N = N * N else : N = N * N * N return N N = 6 print (logicOfSequence(N)) # This code is contributed by # Vishal Gupta |
C#
// C# code to generate first // 'n' terms of Logic sequence using System; class GFG { // Function to generate // a fixed number public static int logicOfSequence( int N) { if (N % 2 == 0) N = N * N; else N = N * N * N; return N; } // Driver Method public static void Main() { int N = 6; Console.Write(logicOfSequence(N)); } } // This code is contributed by nitin mittal |
PHP
<?php // PHP code to generate first 'n' terms // of Logic sequence // Function to generate a fixed number function logicOfSequence( $N ) { if ( $N % 2 == 0) $N = $N * $N ; else $N = $N * $N * $N ; return $N ; } // Driver Code $N = 6; echo logicOfSequence( $N ); // This code is contributed by nitin mittal. ?> |
Javascript
<script> // JavaScript code to generate first 'n' terms // of Logic sequence // Function to generate a fixed \number function logicOfSequence( N) { if (N % 2 == 0) N = N * N; else N = N * N * N; return N; } // Driver Function let N = 6; document.write(logicOfSequence(N)); // This code contributed by Rajput-Ji </script> |
Output:
36
Time Complexity: O(1)
Auxiliary Space: O(1)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!