Fibonacci Numbers - Iteratively and Recursively
Anoniem
Also there is another solution using linear recurrences will compute f[n] in O(lg n) using matrix multiplication int[][] arr = {{1, 1}, {1, 2}}; public int fib(int n) { n--; int[][] fib = matrixPow(arr, n/2); if (n % 2 == 0) { return fib[0][0] + fib[0][1]; } else { return fib[1][0] + fib[1][1]; } } public int[][] multiply(int[][] a1, int[][] a2) { int[][] ret = new int[2][2]; for (int i = 0; i < ret.length; i++) { for (int j = 0; j < ret.length; j++) { for (int k = 0; k < ret.length; k++) { ret[i][j] += a1[i][k] * a2[k][j]; } } } return ret; } public int[][] matrixPow(int[][] a, int pow) { if (pow == 1) { return arr; } int[][] tmp = matrixPow(a, pow/2); if (pow % 2 == 0) { return multiply(tmp, tmp); } else { return multiply(tmp, multiply(tmp, arr)); } }