📌  相关文章
📜  在系列1、5、32、288中找到第N个项…

📅  最后修改于: 2021-04-23 06:52:43             🧑  作者: Mango

给定数字n,任务是找到序列1、5、32、288中的第n个项。
例子:

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

方法:

下面给出了上述方法的实现:

C++
// CPP code to generate  'Nth' terms
// of this sequence
 
#include 
using namespace std;
 
// Function to generate a fixed \number
int nthTerm(int N)
{
    int nth = 0, i;
 
    // Finding nth term
    for (i = N; i > 0; i--) {
 
        nth += pow(i, i);
    }
    return nth;
}
 
// Driver Method
int main()
{
    int N = 3;
    cout << nthTerm(N) << endl;
    return 0;
}


Java
// Java code to generate 'Nth' terms
// of this sequence
import java.lang.Math;
class GFG {
 
    // Function to generate a fixed \number
    public static int nthTerm(int N)
    {
        int nth = 0, i;
 
        // Finding nth term
        for (i = N; i > 0; i--) {
 
            nth += Math.pow(i, i);
        }
        return nth;
    }
 
    // Driver Method
    public static void main(String[] args)
    {
        int N = 3;
        System.out.println(nthTerm(N));
    }
}
// This code is contributed by 29AjayKumar


Python3
# Python3 code to generate 'Nth'
# terms of this sequence
 
# Function to generate a
# fixed number
def nthTerm(N):
    nth = 0
 
    # Finding nth term
    for i in range(N, 0, -1):
        nth += pow(i, i)
    return nth
 
# Driver code
N = 3
print(nthTerm(N))
 
# This code is contributed
# by Shrikant13


C#
// C# code to generate 'Nth' terms
// of this sequence
using System;
 
class GFG
{
 
    // Function to generate a fixed \number
    public static int nthTerm(int N)
    {
        int nth = 0, i;
 
        // Finding nth term
        for (i = N; i > 0; i--)
        {
            nth +=(int)Math.Pow(i, i);
        }
        return nth;
    }
 
    // Driver Method
    public static void Main()
    {
        int N = 3;
        Console.WriteLine(nthTerm(N));
    }
}
 
// This code is contributed by Code_Mech.


PHP
 0; $i--)
    {
 
        $nth += pow($i, $i);
    }
    return $nth;
}
 
// Driver Code
$N = 3;
echo(nthTerm($N));
 
// This code is contributed by Code_Mech.
?>


Javascript


输出:
32

时间复杂度: O(N)