📜  求系列 1、4、27、16、125、36、343 的第 n 项……。

📅  最后修改于: 2022-05-13 01:57:58.994000             🧑  作者: Mango

求系列 1、4、27、16、125、36、343 的第 n 项……。

给定一个数 n,找出系列 1、4、27、16、125、36、343……中的第 n 项。
例子:

Input : 5
Output : 125

Input : 6
Output : 36

天真的方法:在这个序列中,如果第 N 项是偶数,那么第 N 项是 N 的平方,否则第 N 项是 N 的立方。

上述方法的实现如下:

C++
// CPP code to generate first 'n' terms
// of Logic sequence
#include 
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


Javascript


输出:

36

时间复杂度:O(1)