📌  相关文章
📜  找出系列的第N个项,其中每个项f [i] = f [i – 1] – f [i – 2]

📅  最后修改于: 2021-04-22 10:00:24             🧑  作者: Mango

给定三个整数XYN ,任务是找到级数f [i] = f [i – 1] – f [i – 2]的N项, i> 1其中f [0] = X并且f [1] = Y。
例子:

方法:这里的一个重要观察结果是,在序列开始重复之前,最多会有6个不同的术语。因此,找到系列的前6个项,然后第N项与第(N%6)项相同。
下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
 
// Function to return the Nth term
// of the given series
int findNthTerm(int x, int y, int n)
{
    int f[6];
 
    // First and second term of the series
    f[0] = x;
    f[1] = y;
 
    // Find first 6 terms
    for (int i = 2; i <= 5; i++)
        f[i] = f[i - 1] - f[i - 2];
 
    // Return the Nth term
    return f[n % 6];
}
 
// Driver code
int main()
{
    int x = 2, y = 3, n = 3;
    cout << findNthTerm(x, y, n);
 
    return 0;
}


Java
// Java implementation of the approach
import java.io.*;
 
class GFG
{
     
    // Function to find the nth term of series
    static int findNthTerm(int x, int y, int n)
    {    
        int[] f = new int[6];
         
        f[0] = x;
        f[1] = y;
         
        // Loop to add numbers
        for (int i = 2; i <= 5; i++)
            f[i] = f[i - 1] - f[i - 2];
         
        return f[n % 6];
    }
 
     
    // Driver code
    public static void main(String args[])
    {
        int x = 2, y = 3, n = 3;
        System.out.println(findNthTerm(x, y, n));
    }
}
 
// This code is contributed by mohit kumar 29


Python3
# Python3 implementation of the approach
 
# Function to return the Nth term
# of the given series
def findNthTerm(x, y, n):
 
    f = [0] * 6
 
    # First and second term of
    # the series
    f[0] = x
    f[1] = y
 
    # Find first 6 terms
    for i in range(2, 6):
        f[i] = f[i - 1] - f[i - 2]
 
    # Return the Nth term
    return f[n % 6]
 
# Driver code
if __name__ == "__main__":
 
    x, y, n = 2, 3, 3
    print(findNthTerm(x, y, n))
 
# This code is contributed by
# Rituraj Jain


C#
// C# implementation of the approach
using System;
 
class GFG
{
     
    // Function to find the nth term of series
    static int findNthTerm(int x, int y, int n)
    {
        int[] f = new int[6];
         
        f[0] = x;
        f[1] = y;
         
        // Loop to add numbers
        for (int i = 2; i <= 5; i++)
            f[i] = f[i - 1] - f[i - 2];
         
        return f[n % 6];
    }
 
    // Driver code
    public static void Main()
    {
        int x = 2, y = 3, n = 3;
        Console.WriteLine(findNthTerm(x, y, n));
    }
}
 
// This code is contributed by Ryuga


PHP


Javascript


输出:
-2

时间复杂度: O(1)