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 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
| public class _509斐波那契数 {
public int fib_matrix(int n) { if (n < 2) { return n; } int[][] q = {{1, 1}, {1, 0}}; int[][] res = pow(q, n - 1); return res[0][0]; }
public int[][] pow(int[][] a, int n) { int[][] ret = {{1, 0}, {0, 1}}; while (n > 0) { if ((n & 1) == 1) { ret = multiply(ret, a); } n >>= 1; a = multiply(a, a); } return ret; }
public int[][] multiply(int[][] a, int[][] b) { int[][] c = new int[2][2]; for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { c[i][j] = a[i][0] * b[0][j] + a[i][1] * b[1][j]; } } return c; }
public int fib_simulate(int n) { if (n < 2) { return n; } int start = 0, end = 1; for (int i = 2; i <= n; i++) { int temp = end; end = start + end; start = temp; } return end; }
public int fib_math_(int n) { double sqrt5 = Math.sqrt(5); double fibN = Math.pow((1 + sqrt5) / 2, n) - Math.pow((1 - sqrt5) / 2, n); return (int) Math.round(fibN / sqrt5); }
public int fib_math_sum(int n) { if (n <= 1) return n; int beforeIdx = n, beforeCnt = 1, afterCnt = 0; while (beforeIdx > 1) { beforeIdx--; int tempCnt = beforeCnt; beforeCnt = beforeCnt + afterCnt; afterCnt = tempCnt; } return beforeCnt; }
public int fib_dynamic(int n) { dp = new int[n + 1]; return fib_dp(n); }
int[] dp;
private int fib_dp(int n) { if (n <= 1) return n; if (dp[n] != 0) return dp[n]; dp[n] = fib_dp(n - 1) + fib_dp(n - 2); return dp[n]; }
public int fib_recursion(int n) { if (n <= 1) return n; return fib_recursion(n - 1) + fib_recursion(n - 2); }
public static void main(String[] args) { _509斐波那契数 fib = new _509斐波那契数(); System.out.println(fib.fib_simulate(10)); System.out.println(fib.fib_dynamic(10)); } }
|