[转]Geeks 面试题:Fibonacci numbers 优化为lgn效率

来源:互联网 发布:冒险岛2女生捏脸数据 编辑:程序博客网 时间:2024/05/16 15:08

转自:http://blog.csdn.net/kenden23/article/details/20854533


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

  F_n = F_{n-1} + F_{n-2}

with seed values

   F_0 = 0 \quad\text{and}\quad F_1 = 1.

Write a function int fib(int n) that returns F_n. For example, if n = 0, then fib() should return 0. If n = 1, then it should return 1. For n > 1, it should return F_{n-1} + F_{n-2}

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:
     \begin{pmatrix} 1 & 1 \\ 1 & 0 \end{pmatrix}^n = \begin{pmatrix} F_{n+1} & F_n \\ F_n & F_{n-1} \end{pmatrix}.


通过这个矩阵相乘的方法,得到的时间复杂度依然是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 in this post)


下面是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];}};


0 0
原创粉丝点击