Error in exercise 1.1.19 as values become bigger than int max value
pmfer2016 opened this issue · 1 comments
First thanks for your work and sharing it! I really appreciate it.
Exercise 1.1.19 fails because values become much bigger than what supported by the primitive type int. It also wouldn't work with other primitive types. I know the course say you shouldn't import math, but that's the only way it will work when N becomes big (close to 100).
This code below should work:
import java.math.BigInteger;
public static BigInteger improvedFibonacci(int N, BigInteger[] resultArray) {
if (N == 0) return BigInteger.ZERO;
if (N == 1) return BigInteger.ONE;
BigInteger tempResult = resultArray[N - 2].add(resultArray[N - 1]);
resultArray[N] = tempResult;
return resultArray[N];
}
public static void main(String[] args) {
BigInteger[] resultArray = new BigInteger[100];
resultArray[0] = BigInteger.ZERO;
resultArray[1] = BigInteger.ONE;
for (int N = 0; N < 100; N++)
StdOut.println(N + " " + improvedFibonacci(N, resultArray));
}
I’m glad the repository is being useful to you!
You are right, to compute the Fibonacci values up to 100, the BigInteger
class is needed.
And I noticed that on older versions of the book the exercise requested values up to 100. However, on more recent versions of the book, this exercise has been updated to only require values up to 90, probably to make it solvable with primitive types.
For Fibonacci values up to 90, the long
primitive type is enough.
Originally I was using an int
type, it is now updated to use long
: 4ec42dc