矩陣快速冪求斐波那契數列

快速冪

求數an 次冪,可以採用二分法進行快速計算,即

an={an2an2,aan2an2,nn
public int power(int a, int n){
    int result = 1;
    while (n > 0) {
        if (n % 2 == 1) {
            result *= a;
        }
        n /= 2;
        a *= a;
    }
    return result;
}

矩陣快速冪

和上述思路完全一樣,只是全部對於矩陣乘法。斐波那契數列定義如下

f(n)=0,1,f(n2)+f(n1),n=0n=1n2

可以構造矩陣A=[1110] ,則[f(n+1)f(n)f(n)f(n1)]=An 。其中An 就可以使用矩陣快速冪計算。

public class Fibonacci {
    static int[][] dot(int[][] A, int[][] B) {
        int Arows = A.length;
        int Acols = A[0].length;
        int Brows = B.length;
        int Bcols = B[0].length;
        assert (Acols == Brows);
        int tmp;
        int[][] R = new int[Arows][Bcols];
        for (int i = 0; i < Arows; i++) {
            for (int j = 0; j < Bcols; j++) {
                tmp = 0;
                for (int k = 0; k < Acols; k++) {
                    tmp += A[i][k] * B[k][j];
                }
                R[i][j] = tmp;
            }
        }
        return R;
    }

    static int fibonacci(int n) {
        if (n == 0) return 0;
        n -= 1;
        int[][] result = new int[][]{{1, 0}, {0, 1}};
        int[][] A = new int[][]{{1, 1}, {1, 0}};
        while (n > 0) {
            if (n % 2 == 1) {
                result = dot(result, A);
            }
            n /= 2;
            A = dot(A, A);
        }
        return result[0][0];
    }

    public static void main(String[] args) {
        System.out.println(fibonacci(100000));
    }
}
發佈了57 篇原創文章 · 獲贊 41 · 訪問量 16萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章