📌  相关文章
📜  在系列4,2,2,3,6,…中找到第N个项

📅  最后修改于: 2021-05-04 11:12:06             🧑  作者: Mango

给定数字N ,任务是找到序列4、2、2、3、6,…中的第N个
例子:

Input: N = 2
Output: 2

Input: N = 5
Output: 6

方法:

  • 该系列的第N个数字由下式获得
    1. 将前一个数字与前一个数字本身的位置相乘。
    2. 将获得的数字除以2。
  • 由于系列的起始编号是4
1st term = 4
2nd term = (4 * 1) / 2 = 2
3rd term = (2 * 2) / 2 = 2
4th term = (2 * 3) / 2 = 3
5th term = (3 * 4) / 2 = 6
And, so on....
  • 通常,第N个数字可通过以下公式获得:

下面是上述方法的实现:

C++
// C++ program to find Nth term
// of the series 4, 2, 2, 3, 6, ...
 
#include 
using namespace std;
 
// Function to find Nth term
int nthTerm(int N)
{
    int nth = 0, first_term = 4;
 
    int pi = 1, po = 1;
    int n = N;
    while (n > 1) {
        pi *= n - 1;
        n--;
        po *= 2;
    }
 
    // Nth term
    nth = (first_term * pi) / po;
 
    return nth;
}
 
// Driver code
int main()
{
    int N = 5;
 
    cout << nthTerm(N) << endl;
 
    return 0;
}


Java
// Java program to find Nth term
// of the series 4, 2, 2, 3, 6, ...
class GFG
{
 
// Function to find Nth term
static int nthTerm(int N)
{
    int nth = 0, first_term = 4;
 
    int pi = 1, po = 1;
    int n = N;
    while (n > 1)
    {
        pi *= n - 1;
        n--;
        po *= 2;
    }
 
    // Nth term
    nth = (first_term * pi) / po;
 
    return nth;
}
 
// Driver code
public static void main(String[] args)
{
    int N = 5;
 
    System.out.print(nthTerm(N) +"\n");
}
}
 
// This code is contributed by Rajput-Ji


Python3
# Python3 program to find Nth term
# of the series 4, 2, 2, 3, 6, ...
 
# Function to find Nth term
def nthTerm(N) :
 
    nth = 0; first_term = 4;
 
    pi = 1; po = 1;
    n = N;
    while (n > 1) :
        pi *= n - 1;
        n -= 1;
        po *= 2;
 
    # Nth term
    nth = (first_term * pi) // po;
 
    return nth;
 
# Driver code
if __name__ == "__main__" :
    N = 5;
    print(nthTerm(N)) ;
 
# This code is contributed by AnkitRai01


C#
// C# program to find Nth term
// of the series 4, 2, 2, 3, 6, ...
using System;
 
class GFG
{
 
// Function to find Nth term
static int nthTerm(int N)
{
    int nth = 0, first_term = 4;
 
    int pi = 1, po = 1;
    int n = N;
    while (n > 1)
    {
        pi *= n - 1;
        n--;
        po *= 2;
    }
 
    // Nth term
    nth = (first_term * pi) / po;
 
    return nth;
}
 
// Driver code
public static void Main(String[] args)
{
    int N = 5;
 
    Console.Write(nthTerm(N) +"\n");
}
}
 
// This code is contributed by PrinciRaj1992


Javascript


输出:
6