📌  相关文章
📜  在系列5、13、25、41、61中找到N个项。

📅  最后修改于: 2021-05-31 23:30:05             🧑  作者: Mango

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

5, 13, 25, 41, 61...

例子:

Input : 3
Output : 25
For N = 3
Nth term = 3*3 + (3+1)*(3+1)
         = 25
Input : 5
Output : 61

仔细观察,给定级数的第N个项可以概括为:

Nth term = N2 + (N+1)2

下面是上述方法的实现:

C++
// CPP program to find N-th term of the series:
// 5, 13, 25, 41, 61...
#include 
using namespace std;
 
// calculate Nth term of series
int nthTerm(int N)
{
    return N * N + (N + 1) * (N + 1);
}
 
// Driver Function
int main()
{
    int N = 3;
 
    cout << nthTerm(N);
 
    return 0;
}


Java
// Java program to calculate Nth term of
// the series: 5, 13, 25, 41, 61...
 
import java.io.*;
 
class Nth {
    public static int nthTerm(int N)
    {
        // By using above formula
        return N * N + (N + 1) * (N + 1);
    }
     
    public static void main(String[] args)
    {
        int N = 3; // Nth term is 25
         
        // call and print Nth term
        System.out.println(nthTerm(N));
    }   
}


Python 3
# Python 3 program to find
# N-th term of the series:
# 5, 13, 25, 41, 61...
 
# Function to calculate
# Nth term of series
def nthTerm(N) :
    return N * N + (N + 1) * (N + 1)
 
# Driver Code
if __name__ == "__main__" :
 
    N = 3
 
    # function calling
    print(nthTerm(N))
 
# This code is contributed
# by ANKITRAI1


C#
// C# program to calculate Nth term of
// the series: 5, 13, 25, 41, 61...
using System;
 
class GFG
{
public static int nthTerm(int N)
{
    // By using above formula
    return N * N + (N + 1) * (N + 1);
}
 
// Driver Code
public static void Main()
{
    int N = 3; // Nth term is 25
     
    // call and print Nth term
    Console.Write(nthTerm(N));
}
}
 
// This code is contributed
// by ChitraNayal


PHP


Javascript


输出:
25

时间复杂度: O(1)

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