If your goal is to find the largest fibonacci number that can be represented as an int in Java, you can simply calculate the following number until it overflows:
public static void main(String[] args) { System.out.println("Largest integer Fibonacci number: " + maxFibonacci()); } public static int maxFibonacci() { int n = Integer.MAX_VALUE; int fib = 1; int temp = 0; for (int i = 2; i < n; i++) { int last = fib; fib += temp; if (fib < 0) return last;
Now, obviously, your system can calculate a much larger number, for example, using BigInteger. In this case, the limit will be one of the following:
- time of processing
- available memory or
- (if you have a lot of memory and a lot of time) BigInteger restriction, which is supported by
int[] and therefore is limited by the size of the array 2 ^ 31.
Finally, it is probably worth saying that your problem can be solved mathematically.
If you need to find the largest Fibonacci number that is less than a certain number N , you can also use rounding calculation :
phi^n / sqrt(5) < N
which gives you:
n < log(N x sqrt(5)) / log(phi)
Then you can calculate the right side for your chosen N , round it to find N , and calculate the corresponding Fibonacci number with:
F(n) = floor(phi^n / sqrt(5))
source share