前情提要:见斐波那契数列的矩阵乘法方法 ,本文是 O ( l o g n ) O(logn) O(logn) 算法的代码实现。
public class FibonacciProblem {
//暴力递归方式
public static int f1(int n) {
if (n < 1) {
return 0;
}
if (n == 1 || n == 2) {
return 1;
}
return f1(n - 1) + f1(n - 2);
}
//递推:O(n)
public static int f2(int n) {
if (n < 1) {
return 0;
}
if (n == 1 || n == 2) {
return 1;
}
int res = 1;
int pre = 1;
int tmp = 0;
for (int i = 3; i <= n; i++) {
tmp = res;
res = res + pre;
pre = tmp;
}
return res;
}
// O(logN)的解法
public static int f3(int n) {
if (n < 1) {
return 0;
}
if (n == 1 || n == 2) {
return 1;
}
// [ 1 ,1 ]
// [ 1, 0 ]
int[][] base = {
{ 1, 1 },
{ 1, 0 }
}; //二阶矩阵
int[][] res = matrixPower(base, n - 2); //求矩阵的n-2次方
//假设结果为res = {
// {x, y},
// {z, w}
// }
//因为 |F(n) F(n-1)| = |F(2) F(1)| * res
//所以 F(n) = F(2) * x + F(1) * z = x + z
//即res[0][0] 和 res[1][0]
return res[0][0] + res[1][0];
}
public static int[][] matrixPower(int[][] m, int p) {
int[][] res = new int[m.length][m[0].length];
for (int i = 0; i < res.length; i++) {
res[i][i] = 1; //对角线为1
}
// res = 矩阵中的1
int[][] t = m;// 矩阵1次方
for (; p != 0; p >>= 1) { //右移
if ((p & 1) != 0) { //p&1得到次方的二进制形式最后1位,如果为1表示当前的值需要
res = product(res, t);
}
t = product(t, t);
}
return res;
}
// 两个矩阵乘完之后的结果返回
public static int[][] product(int[][] a, int[][] b) {
int n = a.length; //a的行数
int m = b[0].length; //b的列数
int k = a[0].length; // a的列数同时也是b的行数
int[][] ans = new int[n][m];
for(int i = 0 ; i < n; i++) {
for(int j = 0 ; j < m;j++) {
for(int c = 0; c < k; c++) {
ans[i][j] += a[i][c] * b[c][j];
}
}
}
return ans;
}
public static void main(String[] args) {
int n = 19;
System.out.println(f1(n));
System.out.println(f2(n));
System.out.println(f3(n));
System.out.println("===");
}
}