Created
August 3, 2012 06:09
-
-
Save athap/3244973 to your computer and use it in GitHub Desktop.
Fibonacci sequence in log(n) using matrix multiplication
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* | 1 1 |n |Fn+1 Fn | | |
* | 1 0 | = |Fn Fn-1 | | |
* | |
* Figure 1 | |
*/ | |
public int FibonacciLogN(int n) | |
{ | |
if(n <= 0) | |
return 0; | |
if(n == 1 || n == 2) | |
return 1; | |
// calculate n - 1 term (see above figure 1) | |
return FibonacciMatrix(FIBONACCI_MATRIX, n - 1)[0][0]; | |
} | |
private int[][] FibonacciMatrix(int[][] m, int n) | |
{ | |
if(n == 1) | |
return FIBONACCI_MATRIX; | |
if(n == 2) | |
return multiply(FIBONACCI_MATRIX, FIBONACCI_MATRIX); | |
int solution[][] = FibonacciMatrix(m, n/2); | |
solution = multiply(solution, solution); | |
if(n%2 != 0) | |
solution = multiply(solution, FIBONACCI_MATRIX); | |
return solution; | |
} | |
// for quick multiplication | |
private int[][] multiply(int[][] m, int[][] n) | |
{ | |
int[][] result = new int[2][2]; | |
result[0][0] = m[0][0] * n[0][0] + m[0][1] * n[1][0]; | |
result[0][1] = m[0][0] * n[0][1] + m[0][1] * n[1][1]; | |
result[1][0] = m[1][0] * n[0][0] + m[1][1] * n[1][0]; | |
result[1][1] = m[1][0] * n[0][1] + m[1][1] * n[1][1]; | |
return result; | |
} | |
private int[][] FIBONACCI_MATRIX = new int[][] { {1,1}, {1,0} }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment