矩阵快速幂求斐波那契数列

来源:互联网 发布:华融新兴产业投资 知乎 编辑:程序博客网 时间:2024/05/16 20:00

快速幂

求数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));    }}
0 0
原创粉丝点击