I have the following code which provides the correct values for n < 47.
public static int fib(int n) {
int nthTerm = 0;
if (n == 2)
nthTerm =
The reason you can't use int
is because fib(47)
is 2971215073
which overflows Java's signed 32-bit int
(231-1). You could use a memoization optimization to implement it with BigInteger like,
private static Map memo = new HashMap<>();
static {
memo.put(0, BigInteger.ZERO);
memo.put(1, BigInteger.ONE);
}
public static BigInteger fib(int n) {
if (memo.containsKey(n)) {
return memo.get(n);
}
BigInteger v = fib(n - 2).add(fib(n - 1));
memo.put(n, v);
return v;
}