📌  相关文章
📜  程序找到系列2、4、3、4、15的N个项。

📅  最后修改于: 2021-06-01 01:56:02             🧑  作者: Mango

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

2, 4, 3, 4, 15...

例子:

Input: N = 5
Output: 15
Explanation:
For N = 5,
Nth term = ( N * ( (N%2) + (N%3) ) 
         = ( 5 * ( (5%2) + (5%3) ) 
         = ( 5 * ( 1 + 2 )
         = 15

Input: N = 4 
Output: 4

该系列的广义第N个术语:

Nth term = ( N * ( (N%2) + (N%3) ) )

下面是上述方法的实现:

C++
// CPP program to find N-th term of the series:
// 2, 4, 3, 4, 15...
 
#include 
using namespace std;
 
// function to calculate Nth term of series
int nthTerm(int N)
{
    // By using above formula
    return (N * ((N % 2) + (N % 3)));
}
 
// Driver Function
int main()
{
 
    // get the value of N
    int N = 5;
 
    // Calculate and print the Nth term
    cout << "Nth term for N = "
         << N << " : "
         << nthTerm(N);
 
    return 0;
}


Java
import java.io.*;
 
// Class to calculate Nth term of series
class Nth {
    public int nthTerm(int N)
    {
        // By using above formula
        return (N * ((N % 2) + (N % 3)));
    }
}
 
// Main class for main method
class GFG {
 
    public static void main(String[] args)
    {
 
        // get the value of N
        int N = 5;
 
        // create object of Class Nth
        Nth a = new Nth();
 
        // Calculate and print the Nth term
        System.out.println("Nth term for N = "
                           + N + " : "
                           + a.nthTerm(N));
    }
}


Python3
# Python3 program to find N-th term of the series:
# 2, 4, 3, 4, 15...
 
 
 
# function to calculate Nth term of series
def nthTerm( N):
 
    # By using above formula
    return (N * ((N % 2) + (N % 3)))
 
 
# Driver Function
 
 
# get the value of N
if __name__=='__main__':
    N = 5
 
    # Calculate and print the Nth term
    print("Nth term for N = ", N , " : ",nthTerm(N))
 
# This code is contributed by ash264


C#
// C# program to find
// N-th term of the series:
// 2, 4, 3, 4, 15...
using System;
 
class GFG
{
public int nthTerm(int N)
{
    // By using above formula
    return (N * ((N % 2) + (N % 3)));
}
 
public static void Main()
{
 
    // get the value of N
    int N = 5;
 
    GFG a = new GFG();
 
    // Calculate and print the Nth term
    Console.Write("Nth term for N = " +
                            N + " : " +
                         a.nthTerm(N));
}
}
 
// This code is contributed
// by ChitraNayal


PHP


Javascript


输出:
Nth term for N = 5 : 15

时间复杂度:O(1)