📜  在系列1,6,18,40,75,…中找到Nth项。

📅  最后修改于: 2021-05-31 16:41:58             🧑  作者: Mango

给定数字n,任务是找到序列1,6,18,40,75,…中的第n个项
例子:

Input: N = 2
Output: 6
Explanation:
2nd term = (2^2*(2+1))/2
         = 6

Input: N = 5
Output: 75
Explanation:
5th term = (5^2*(5+1))/2
         = 75

方法:

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

C++
// CPP code to generate
// 'Nth' term of this sequence
 
#include 
using namespace std;
 
// Function to generate a fixed number
int nthTerm(int N)
{
    int nth = 0;
 
    //(N^2*(N+1))/2
    nth = (N * N * (N + 1)) / 2;
 
    return nth;
}
 
// Driver Method
int main()
{
    int N = 5;
 
    cout << nthTerm(N) << endl;
 
    return 0;
}


Java
// Java code to generate
// 'Nth' term of this sequence
 
class GFG {
 
    // Function to generate a fixed number
    public static int nthTerm(int N)
    {
        int nth = 0;
 
        //(N^2*(N+1))/2
        nth = (N * N * (N + 1)) / 2;
 
        return nth;
    }
 
    // Driver Method
    public static void main(String[] args)
    {
        int N = 5;
 
        System.out.println(nthTerm(N));
    }
    // This code is contributed by 29AjayKumar
}


Python3
# python program to find out'Nth' term of this sequence
 
# Function to generate a fixed number
def nthTerm(N):
    nth = 0
    nth = (N * N * (N + 1))//2
    return nth
 
# Driver code
N = 5
print(nthTerm(N))
 
# This code is contributed by Shrikant13


C#
// C# code to generate
// 'Nth' term of this sequence
 
using System;
public class GFG {
 
    // Function to generate a fixed number
    public static int nthTerm(int N)
    {
        int nth = 0;
 
        //(N^2*(N+1))/2
        nth = (N * N * (N + 1)) / 2;
 
        return nth;
    }
 
    // Driver Method
    public static void Main(string[] args)
    {
        int N = 5;
 
        Console.WriteLine(nthTerm(N));
    }
}
 
// This code is contributed by Shrikant13


PHP


Javascript


输出:
75

时间复杂度: O(1)

想要从精选的最佳视频中学习并解决问题,请查看有关从基础到高级C++的C++基础课程以及有关语言和STL的C++ STL课程。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”