The Matrix Solution of the Fibonacci series (implemented in java) and the Fibonacci Matrix
The binary method is used.
Import java. util. returns;/*** returns the Fibonacci sequence <br/> * <pre> * [F (n + 1) F (n)] [1] ^ n (n, can be proved by induction) <br/> * ||||< br/> * [F (n) F (n-1)] [1 0] <br/> * </pre> * @ author bing **/public class F {// join matrix private static final int [] [] UNIT = {{ 1, 1 },{ 1, 0 }}; // all 0 matrix private static final int [] [] ZERO = {0, 0}, {0, 0 }}; public static void main (String [] args) {custom region = new region (System. in); while (true) {// the nth Fibonacci number, starting from 0 int n = nth. nextInt (); int [] [] m = fb (n); long t1 = System. currentTimeMillis (); System. out. println (m [0] [1]); long t2 = System. currentTimeMillis (); System. out. println ("Time is:" + (t2-t1 ));}} /*** find the Fibonacci sequence ** @ param n * @ return */public static int [] [] fb (int n) {if (n = 0) {return ZERO;} if (n = 1) {return UNIT;} // n is an odd number if (n & 1) = 0) {int [] [] matrix = fb (n> 1); return matrixMultiply (matrix, matrix );} // n is an even int [] [] matrix = fb (n-1)> 1); return matrixMultiply (matrix, matrix), UNIT );} /*** multiply the matrix ** @ param m * r1 * c1 * @ param n * c1 * c2 * @ return new matrix, r1 * c2 */public static int [] [] matrixMultiply (int [] [] m, int [] [] n) {int rows = m. length; int cols = n [0]. length; int [] [] r = new int [rows] [cols]; for (int I = 0; I <rows; I ++) {for (int j = 0; j <cols; j ++) {r [I] [j] = 0; for (int k = 0; k <m [I]. length; k ++) {r [I] [j] + = m [I] [k] * n [k] [j] ;}} return r ;}}