performance - Very Large Fibonacci in Java -
i trying rapidly calculate large fibonacci numbers. here code. prohibitively slow numbers above 1 million, how can 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 = 3; <= 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. guys!
one way calculate (n-1)th
power of 2x2 matrix:
a = ((1, 1), (1, 0))
then have
fib(n) = a^(n-1)[0][0], n >= 1
and power of matrix a
can calculated efficiently using exponentiation squaring