斐波那契数列= 0、1、1、2、3、5、8、13、21、34,……..
已经讨论了找到第n个斐波那契数的不同方法。查找第n个斐波那契数的另一种简单方法是使用黄金比率,因为斐波那契数保持近似黄金比率直至无限。
黄金比例:
例子:
Input : n = 9
Output : 34
Input : n = 7
Output : 13
方法:
黄金比例可能会给我们错误的答案。
如果在每个点上取整结果,我们都可以得到正确的结果。
第n个斐波那契数=舍入(n-1个斐波那契数X黄金比率)f n =舍入(f n-1 * )
直到第四个学期,该比率与黄金比率并不太接近(因为3/2 = 1.5,2 / 1 = 2,…)。因此,我们将从第五个学期开始考虑获得下一个斐波那契数。找出第9个斐波那契数f9(n = 9):
f6 =舍入(f5 * )= 8 f7 =舍入(f6 * )= 13 f8 =舍入(f7 * )= 21 f9 =舍入(f8 * )= 34
注意:此方法可以正确计算前34个斐波那契数。之后,可能与正确值有所不同。
下面是上述方法的实现:
CPP
// CPP program to find n-th Fibonacci number
#include
using namespace std;
// Approximate value of golden ratio
double PHI = 1.6180339;
// Fibonacci numbers upto n = 5
int f[6] = { 0, 1, 1, 2, 3, 5 };
// Function to find nth
// Fibonacci number
int fib (int n)
{
// Fibonacci numbers for n < 6
if (n < 6)
return f[n];
// Else start counting from
// 5th term
int t = 5, fn = 5;
while (t < n) {
fn = round(fn * PHI);
t++;
}
return fn;
}
// driver code
int main()
{
int n = 9;
cout << n << "th Fibonacci Number = "
<< fib(n) << endl;
return 0;
}
Java
// Java program to find n-th Fibonacci number
class GFG
{
// Approximate value of golden ratio
static double PHI = 1.6180339;
// Fibonacci numbers upto n = 5
static int f[] = { 0, 1, 1, 2, 3, 5 };
// Function to find nth
// Fibonacci number
static int fib (int n)
{
// Fibonacci numbers for n < 6
if (n < 6)
return f[n];
// Else start counting from
// 5th term
int t = 5;
int fn = 5;
while (t < n) {
fn = (int)Math.round(fn * PHI);
t++;
}
return fn;
}
// Driver code
public static void main (String[] args)
{
int n = 9;
System.out.println(n + "th Fibonacci Number = "
+fib(n));
}
}
// This code is contributed by Anant Agarwal.
Python3
# Python3 code to find n-th Fibonacci number
# Approximate value of golden ratio
PHI = 1.6180339
# Fibonacci numbers upto n = 5
f = [ 0, 1, 1, 2, 3, 5 ]
# Function to find nth
# Fibonacci number
def fib ( n ):
# Fibonacci numbers for n < 6
if n < 6:
return f[n]
# Else start counting from
# 5th term
t = 5
fn = 5
while t < n:
fn = round(fn * PHI)
t+=1
return fn
# driver code
n = 9
print(n, "th Fibonacci Number =", fib(n))
# This code is contributed by "Sharad_Bhardwaj".
C#
// C# program to find n-th Fibonacci
// number
using System;
class GFG {
// Approximate value of golden ratio
static double PHI = 1.6180339;
// Fibonacci numbers upto n = 5
static int []f = { 0, 1, 1, 2, 3, 5 };
// Function to find nth
// Fibonacci number
static int fib (int n)
{
// Fibonacci numbers for n < 6
if (n < 6)
return f[n];
// Else start counting from
// 5th term
int t = 5;
int fn = 5;
while (t < n) {
fn = (int)Math.Round(fn * PHI);
t++;
}
return fn;
}
// Driver code
public static void Main ()
{
int n = 9;
Console.WriteLine(n + "th Fibonacci"
+ " Number = " + fib(n));
}
}
// This code is contributed by vt_m.
PHP
Javascript
输出:
9th Fibonacci Number = 34
通过使用有效的方法来计算功率,我们可以优化O(Log n)中的上述解决方案工作。
由于涉及浮点计算,因此上述方法可能不会总是产生正确的结果。这就是原因,即使可以对其进行优化以使其在O(Log n)中运行,该方法实际上仍未使用。请参阅下面的MIT视频以获取更多详细信息。
https://www.youtube.com/watch?v=-EQTVuAhSFY