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;
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.