The Matrix Solution of the Fibonacci series (implemented in java) and the Fibonacci Matrix

Source: Internet
Author: User

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 ;}}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.