前言
斐波拉契数列的递推公式为f(n) = f(n - 1) + f(n - 2),如果只是求f(n),可以通过dfs模拟,动态规划,快速幂,特征方程与通项公式。 这里主要记录O(logn)的快速幂的两种实现,递归和迭代实现。
一、递归
public class Fib {
public int fib(int n) {
int[][] M = new int[][]{{1, 1}, {1, 0}};
int[][] R = power(n, M);
return R[1][0];
}
private int[][] power(int n, int[][] M) {
if (0 == n) return new int[][]{{1, 0}, {0, 1}};
int[][] rs = power(n >>> 1, M);
rs = multiply(rs, rs);
if ((n & 1) == 1) rs = multiply(rs, M);
return rs;
}
private int[][] multiply(int[][] rs1, int[][] rs2) {
int[][] r = new int[2][2];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
r[i][j] = rs1[i][0] * rs2[0][j] + rs1[i][1] * rs2[1][j];
}
}
return r;
}
}
二、迭代
class Fib2 {
public int fib(int n) {
int[][] R = new int[][]{{1, 0}, {0, 1}};
int[][] T = new int[][]{{1, 1}, {1, 0}};
while (n > 0) {
if ((n & 1) == 1) R = multiply(R, T);
T = multiply(T, T);
n >>>= 1;
}
return R[1][0];
}
private int[][] multiply(int[][] rs1, int[][] rs2) {
int[][] r = new int[2][2];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
r[i][j] = rs1[i][0] * rs2[0][j] + rs1[i][1] * rs2[1][j];
}
}
return r;
}
}
总结
1)斐波拉契数列的快速幂
|