Very Large Fibonacci in Java

2019-08-09 18:09发布

问题:

I am trying to rapidly calculate large Fibonacci numbers. Here is my code. It is prohibitively slow for numbers above 1 million, how can it be improved?

public static BigInteger fib(BigInteger n) {

        int k = n.intValue();
        BigInteger ans = null;

        if(k == 0) { 
            ans = new BigInteger("0");
        } else if(Math.abs(k) <= 2) {
            ans = new BigInteger("1");
        } else {
            BigInteger km1 = new BigInteger("1");
            BigInteger km2 = new BigInteger("1");

            for(int i = 3; i <= Math.abs(k); ++i) {
                ans = km1.add(km2);
                km2 = km1;
                km1 = ans;
            }
        }

       if(k<0 && k%2==0) { ans = ans.negate(); }
       return ans;
    } 

Binet's worked well. Thanks guys!

回答1:

One way is to calculate the (N-1)th power of the 2x2 matrix:

A = ((1, 1), (1, 0))

Then we have

Fib(n) = A^(n-1)[0][0], for n >= 1

And the power of matrix A can be calculated efficiently using Exponentiation by squaring