📌  相关文章
📜  使用Pell方程的第N个斐波那契数

📅  最后修改于: 2021-04-23 21:02:09             🧑  作者: Mango

给定整数N ,任务是找到第N斐波那契数。

方法:N斐波那契数可以使用法术方程的根找到。 Pells方程的形式通常为(x 2 )– n(y 2 )= | 1 |
在这里,考虑y 2 = x,n = 1 。同样,在右侧取正(+1)。
现在,等式变为x 2 – x = 1 ,与x 2 – x – 1 = 0相同
在这里, {x =(p i – q i )/(p – q)}被称为斐波那契数列的N项,其中i = n – 1(p,q)是法术方程的根。

下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
  
// Function to return the 
// nth fibonacci number
int fib(int n)
{
    // Assign roots of the pell's 
    // equation to p and q
    double p = ((1 + sqrt(5)) / 2);
    double q = ((1 - sqrt(5)) / 2);
    int i = n - 1;
    int x = (int) ((pow(p, i) - 
                    pow(q, i)) / (p - q));
    return x;
}
  
// Driver code
int main()
{
    int n = 5;
    cout << fib(n);
}
  
// This code is contributed by PrinciRaj1992


Java
// Java implementation of the approach
class GFG 
{
      
// Assign roots of the pell's 
// equation to p and q
static double p = ((1 + Math.sqrt(5)) / 2);
static double q = ((1 - Math.sqrt(5)) / 2);
  
// Function to return the 
// nth fibonacci number
static int fib(int n)
{
    int i = n - 1;
    int x = (int) ((Math.pow(p, i) - 
                    Math.pow(q, i)) / (p - q));
    return x;
}
  
// Driver code
public static void main(String[] args) 
{
    int n = 5;
    System.out.println(fib(n));
}
} 
  
// This code is contributed by 29AjayKumar


Python3
# Python3 implementation of the approach
import math
  
# Assign roots of the pell's 
# equation to p and q
p = (1 + math.sqrt(5)) / 2
q = (1 - math.sqrt(5)) / 2
  
# Function to return the 
# nth fibonacci number
def fib(n):
    i = n - 1
    x = (p**i - q**i) / (p - q)
    return int(x)
  
# Driver code
n = 5
print(fib(n))


C#
// C# implementation of the approach
using System;
  
class GFG
{
          
// Assign roots of the pell's 
// equation to p and q
static double p = ((1 + Math.Sqrt(5)) / 2);
static double q = ((1 - Math.Sqrt(5)) / 2);
  
// Function to return the 
// nth fibonacci number
static int fib(int n)
{
    int i = n - 1;
    int x = (int) ((Math.Pow(p, i) - 
                    Math.Pow(q, i)) / (p - q));
    return x;
}
  
// Driver code
static public void Main ()
{
    int n = 5;
    Console.Write(fib(n));
}
} 
  
// This code is contributed by @ajit..


输出:
3