📌  相关文章
📜  查找系列0、2、4、8、12、18的N个项。

📅  最后修改于: 2021-04-27 06:27:56             🧑  作者: Mango

给定数字N。任务是编写一个程序来查找以下系列中的第N个术语:

例子:

Input: 3
Output: 4
For N = 3
Nth term = ( 3 + ( 3 - 1 ) * 3 ) / 2
         = 4
Input: 5 
Output: 12

仔细观察,以上系列中的第N术语可以概括为:

Nth term = ( N + ( N - 1 ) * N ) / 2

下面是上述方法的实现:

C++
// CPP program to find N-th term of the series:
// 0, 2, 4, 8, 12, 18...
#include 
using namespace std;
 
// Calculate Nth term of series
int nthTerm(int N)
{
    return (N + N * (N - 1)) / 2;
}
 
// Driver Function
int main()
{
    int N = 5;
 
    cout << nthTerm(N);
 
    return 0;
}


Java
// Java program to find N-th term of the series:
// 0, 2, 4, 8, 12, 18...
import java.io.*;
 
// Main class for main method
class GFG {
    public static int nthTerm(int N)
    {
        // By using above formula
        return (N + (N - 1) * N) / 2;
    }  
  
    // Driver code
    public static void main(String[] args)
    {
        int N = 5; // 5th term is 12
             
        System.out.println(nthTerm(N));
    }
}


Python 3
# Python 3 program to find N-th term of the series:
# 0, 2, 4, 8, 12, 18.
 
# Calculate Nth term of series
def nthTerm(N) :
     
    return (N + N * (N - 1)) // 2
 
# Driver Code
if __name__ == "__main__" :
 
    N = 5
 
    print(nthTerm(N))
 
# This code is contributed by ANKITRAI1


C#
// C# program to find N-th term of the series:
// 0, 2, 4, 8, 12, 18...
using System;
class gfg
{  
    // Calculate Nth term of series
    public int nthTerm(int N)
    {
        int n = ((N + N * (N - 1)) / 2);
        return n;
    }
 
    //Driver program
    static void Main(string[] args)
    {
        gfg p = new gfg();
        int a = p.nthTerm(5);
        Console.WriteLine(a);
        Console.Read();
    }
}
//This code is contributed by SoumikMondal


PHP


Javascript


输出:
12

时间复杂度: O(1)

要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”