📜  第N个XOR斐波那契数

📅  最后修改于: 2021-06-26 23:11:20             🧑  作者: Mango

给定三个整数abN ,其中ab是XOR斐波纳契数列的前两个项,任务是找到第N项。
XOR斐波那契数列的第N个项定义为F(N)= F(N – 1)^ F(N – 2) ,其中^是按位XOR。
例子:

方法:因为, a ^ a = 0 ,所以给定

可以看出,答案每3个数字就会重复一次。因此答案是F(N%3) ,其中F(0)= a,F(1)= b和F(2)= a ^ b
下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
 
// Function to return the nth XOR Fibonacci number
int nthXorFib(int n, int a, int b)
{
    if (n == 0)
        return a;
    if (n == 1)
        return b;
    if (n == 2)
        return (a ^ b);
 
    return nthXorFib(n % 3, a, b);
}
 
// Driver code
int main()
{
    int a = 1, b = 2, n = 10;
 
    cout << nthXorFib(n, a, b);
 
    return 0;
}


Java
// Java implementation of the above approach
class GFG
{
         
    // Function to return the
    // nth XOR Fibonacci number
    static int nthXorFib(int n, int a, int b)
    {
        if (n == 0)
            return a;
        if (n == 1)
            return b;
        if (n == 2)
            return (a ^ b);
     
        return nthXorFib(n % 3, a, b);
    }
     
    // Driver code
    public static void main (String[] args)
    {
        int a = 1, b = 2, n = 10;
     
        System.out.println(nthXorFib(n, a, b));
    }
}
 
// This code is contributed by AnkitRai01


Python3
# Python3 implementation of the approach
 
# Function to return
# the nth XOR Fibonacci number
def nthXorFib(n, a, b):
    if n == 0 :
        return a
    if n == 1 :
        return b
    if n == 2 :
        return a ^ b
 
    return nthXorFib(n % 3, a, b)
 
# Driver code
a = 1
b = 2
n = 10
print(nthXorFib(n, a, b))
 
# This code is contributed by divyamohan123


C#
// C# implementation of the above approach
using System;
     
class GFG
{
         
    // Function to return the
    // nth XOR Fibonacci number
    static int nthXorFib(int n, int a, int b)
    {
        if (n == 0)
            return a;
        if (n == 1)
            return b;
        if (n == 2)
            return (a ^ b);
     
        return nthXorFib(n % 3, a, b);
    }
     
    // Driver code
    public static void Main (String[] args)
    {
        int a = 1, b = 2, n = 10;
     
        Console.WriteLine(nthXorFib(n, a, b));
    }
}
 
// This code is contributed by Princi Singh


Javascript


输出:
2

时间复杂度: O(1)

如果您希望与行业专家一起参加现场课程,请参阅《 Geeks现场课程》和《 Geeks现场课程美国》。