The Fibonacci numbers are the numbers in the following integer sequence.
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 141, ……..
In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation
![]()
with seed values
![]()
Write a functionint fib(int n)that returns
. For example, ifn= 0, thenfib()should return 0. If n = 1, then it should return 1. For n > 1, it should return![]()
Following are different methods to get the nth Fibonacci number.
http://www.geeksforgeeks.org/program-for-nth-fibonacci-number/斐波那契数列大家都很熟悉了,递归和动态规划法这里就不讲了。
原来有一个更加优化的方法,时间效率为O(lgn)。
Method 4 ( Using power of the matrix {{1,1},{1,0}} )
This another O(n) which relies on the fact that if we n times multiply the matrix M = {{1,1},{1,0}} to itself (in other words calculate power(M, n )), then we get the (n+1)th Fibonacci number as the element at row and column (0, 0) in the resultant matrix.
The matrix representation gives the following closed expression for the Fibonacci numbers:![]()
通过这个矩阵相乘的方法,得到的时间复杂度依然是O(n),但是可以进一步使用二分法,把复杂度降低到O(lgn)。
Method 5 ( Optimized Method 4 )
The method 4 can be optimized to work in O(Logn) time complexity. We can do recursive multiplication to get power(M, n) in the prevous method (Similar to the optimization done inthispost)
下面是Method4 和5的程序:
void mulMatrix(int F[2][2])
{
int a = F[0][0];
int b = F[1][0];
F[0][0] = a+b;
F[0][1] = a;
F[1][0] = a;
F[1][1] = b;
}
void powMatrix(int F[2][2], int n)
{
for (int i = 2; i < n; i++)
mulMatrix(F);
}
int fib(int n)
{
if (n == 0) return 0;
int F[2][2] = {{1,1},{1,0}};
powMatrix(F, n);
return F[0][0];
}
class OptiFib
{
public:
void mulOneMatrix(int F[2][2])
{
int a = F[0][0];
int b = F[1][0];
F[0][0] = a+b;
F[0][1] = a;
F[1][0] = a;
F[1][1] = b;
}
void pow2Matrix(int F1[2][2])
{
int a = F1[0][0];
int b = F1[0][1];
int c = F1[1][0];
int d = F1[1][1];
F1[0][0] = a*a+b*c;
F1[0][1] = a*b+b*d;
F1[1][0] = c*a+c*d;
F1[1][1] = c*b+d*d;
}
void powMatrix(int F[2][2], int n)
{
if (n < 2) return;
int mid = n>>1;
powMatrix(F, mid);
pow2Matrix(F);
if (n%2 == 1) mulOneMatrix(F);
}
int fib(int n)
{
if (n == 0) return 0;//注意:不要遗漏这个特例!
int F[2][2] = {{1,1},{1,0}};
powMatrix(F, n-1);
return F[0][0];
}
};
本文介绍了一种计算斐波那契数列的新方法,该方法利用矩阵乘法并通过优化实现O(log n)的时间复杂度,显著提高了计算效率。
1920

被折叠的 条评论
为什么被折叠?



