📌  相关文章
📜  程序找到系列1、2、11、12、21…的第N个术语。

📅  最后修改于: 2021-04-22 02:53:08             🧑  作者: Mango

给定数字N,任务是找到级数的N个项:

例子:

Input : N = 2
Output : 2

Input : N = 5
Output : 21

方法:
该想法基于以下事实:序列中最后一位的值交替出现。例如,如果第i个数字的最后一位为1,则第(i-1)个和第(i + 1)个数字的最后一位必须为2。

因此,创建一个大小为(n + 1)的数组,然后将其推入1和2(这两个始终是序列的前两个元素)。

最后返回arr [n]。

下面是上述想法的实现:

C++
// C++ program to find
// the N-th term in the series
// 1, 2, 11, 12, 21...
  
#include 
using namespace std;
  
// Function to find N-th number in series
int printNthElement(int N)
{
    // create an array of size (N+1)
    int arr[N + 1];
    arr[1] = 1;
    arr[2] = 2;
  
    for (int i = 3; i <= N; i++) {
        // If i is odd
        if (i % 2 != 0) {
  
            arr[i] = arr[i / 2] * 10 + 1;
        }
        else {
  
            arr[i] = arr[(i / 2) - 1] * 10 + 2;
        }
    }
    return arr[N];
}
  
// Driver code
int main()
{
  
    // Get N
    int N = 5;
  
    // Get Nth term
    cout << printNthElement(N);
  
    return 0;
}


Java
// Java program to find
// the N-th term in the series
// 1, 2, 11, 12, 21...
  
class FindNth {
  
    // Function to find n-th number in series
    static int printNthElement(int n)
    {
        // create an array of size (n+1)
        int arr[] = new int[n + 1];
        arr[1] = 1;
        arr[2] = 2;
  
        for (int i = 3; i <= n; i++) {
            // If i is odd
            if (i % 2 != 0)
                arr[i] = arr[i / 2] * 10 + 1;
            else
                arr[i] = arr[(i / 2) - 1] * 10 + 2;
        }
        return arr[n];
    }
  
    // main function
    public static void main(String[] args)
    {
        int n = 5;
  
        System.out.println(printNthElement(n));
    }
}


Python3
# Python3 program to find
# the N-th term in the series
# 1, 2, 11, 12, 21...
  
# Return n-th number in series
def printNthElement(n) :  
          
    # create an array of size (n + 1)  
    arr =[0] * (n + 1);  
    arr[1] = 1
    arr[2] = 2
      
    for i in range(3, n + 1) :  
        # If i is odd  
        if (i % 2 != 0) :  
            arr[i] = arr[i // 2] * 10 + 1
        else :  
            arr[i] = arr[(i // 2) - 1] * 10 + 2
          
    return arr[n]  
          
# Driver code  
n = 5
print(printNthElement(n))


C#
// C# program to find
// the N-th term in the series
// 1, 2, 11, 12, 21...
using System;
  
class GFG 
{
  
// Function to find n-th
// number in series
static int printNthElement(int n)
{
    // create an array of size (n+1)
    int []arr = new int[n + 1];
    arr[1] = 1;
    arr[2] = 2;
  
    for (int i = 3; i <= n; i++)
    {
        // If i is odd
        if (i % 2 != 0)
            arr[i] = arr[i / 2] * 10 + 1;
        else
            arr[i] = arr[(i / 2) - 1] * 10 + 2;
    }
    return arr[n];
}
  
// Driver Code
public static void Main()
{
    int n = 5;
  
    Console.WriteLine(printNthElement(n));
}
}
  
// This code is contributed
// by inder_verma


PHP


输出:
21