public class FibonacciProblem {
public static void main(String[] args) {
// 1,1,2,3,5,8,13
int n = 7;
System.out.println(f3(n));
}
public static int f3(int n){
if (n < 1){
return 0;
}
if(n == 1 || n == 2){
return 1;
}
int[][] base = {
{1,1},
{1,0}
};
int[][] res = matrixPower(base, n-2);
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; // 对角线
}
// res=矩阵中的1
int[][] t = m; // 矩阵1次方
for (; p != 0; p >>= 1){
if((p&1) != 0){
res = mulMatrix(res, t);
}
t = mulMatrix(t,t);
}
return res;
}
// 两个矩阵相乘. 第一个矩阵的行数等于第二个矩阵的列数
public static int[][] mulMatrix(int[][] m1, int[][] m2){
int res[][] = new int[m1.length][m2[0].length];
for (int i = 0; i < m1.length; i++) {
for (int j = 0; j < m2[0].length; j++) {
for (int k = 0; k < m2.length; k++) {
res[i][j] += m1[i][k] * m2[k][j];
}
}
}
return res;
}
}
08-19
953
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
08-20
320
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
08-20
837
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)