二分法求Fibonacci数列

package net.liuyx.algorithm;

public class Fibonacci {
    private static int[][] a = { { 1, 1 }, { 1, 0 } };

    /**
     * @param args
     */
    public static void main(String[] args) {
        int[][] result = fibonacciAlogrithm(3);
        System.out.println(result[1][1]);
    }

    private static int[][] fibonacciAlogrithm(int n) {
        int[][] result = { { 1, 1 }, { 1, 0 } };
        while (n != 0) {
            if ((n & 1) != 0) {
                result = multiply(result, a);
            }
            a = multiply(a, a);
            n = n >> 1;
        }
        return result;
    }

    private static int[][] multiply(int[][] a, int[][] b) {
        int[][] result = new int[2][2];
        result[0][0] = a[0][0] * b[0][0] + a[0][1] * b[1][0];
        result[0][1] = a[0][0] * b[0][1] + a[0][1] * b[1][1];
        result[1][0] = a[1][0] * b[0][0] + a[1][1] * b[1][0];
        result[1][1] = a[1][0] * b[0][1] + a[1][1] * b[1][1];
        return result;
    }

}

你可能感兴趣的:(二分法求Fibonacci数列)