In Fibonacci sequence each item is the sum of the previous two.
fibonacci(1) == 1, fibonacci(0) == 0;
fibonacci(2) = fibonacci(1) + fibonacci(0);
...
After searching the web I find this algorithm to solve:
And here is my code:
import java.math.BigInteger;
public class Fibonacci {
public static BigInteger fib(BigInteger n) {
double p = (1 + Math.sqrt(5)) / 2;
double q = (1 - Math.sqrt(5) / 2;
BigInteger result = BigInteger.ZERO;
result = ( Math.pow(p, n) - Math.pow(q, n) ) / Math.sqrt(5); //error
return result;
}
}
How to solve that error, I want the parameter is BigInteger, not Integer, and the return number is BigInteger, too.
Instead of
Math.pow()
you need to use BigDecimal#pow().Because
Math.pow()
returnsdouble
, but ifp
andn
are too large than it will easily produce primitive overflow and error will occur.Now
result
gotp^n
asBigDecimal
. Hope you understand theBigDecimal
calculation.The standard mathematical operators in Java is not overridden for
Big
numbers. These are just objects. So you have to work with them as objects.Updated:
As @Gassa said, the above method accumulates error because
but we need much more.
So we can use sqrt method for
BigDecimal
from here: