第一年农场有1只成熟的母牛A,往后的每年:

  1. 每一只成熟的母牛都会生一只母牛
  2. 每一只新出生的母牛都在出生的第三年成熟
  3. 每一只母牛永远不会死

返回N年后牛的数量。

抽象公式就是 F(N) = F(N-1) + F(N-3).
矩阵公式:
|F4, F3, F2| = |F3,F2,F1| * 3阶矩阵
|F5, F4, F3| = |F4,F3,F2| * 3阶矩阵
|F6, F5, F4| = |F5,F4,F3| * 3阶矩阵
通过3个公式求出3阶矩阵

public class FibonacciProblem {
    public static void main(String[] args) {
        // 1,1,2,3,5,8,13
        int n = 19;
        System.out.println(c1(n));
        System.out.println(c3(n));

    }

    // 递归解
    public static int c1(int n){

        if (n < 0){
            return 0;
        }

        if (n == 1 || n == 2 || n == 3){
            return n;
        }

        return c1(n-1) + c1(n-3);
    }

    // 矩阵解
    public static int c3(int n){
        if (n < 1){
            return 0;
        }

        if(n == 1 || n == 2){
            return 1;
        }

        int[][] base = {
                {1,1,0},
                {0,0,1},
                {1,0,0}
        };

        int[][] res = matrixPower(base, n-3);

        //|F3,F2,F1| * (3阶矩阵的n-3次方)
        return 3*res[0][0] + 2*res[1][0] + res[2][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;
    }
}