// I am learning about recursion in Java. /** I am trying to calculate the 45th Fibonacci number by using an array to shorten the time used, which does not work out well... error message: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 45 at Auf1.fib2(Auf1.java:25) at Auf1.main(Auf1.java:49) **/
public class Auf1 {
public static long[] feld;
public static long fib2(long n) {
if ((n == 1) || (n == 2)) {
return 1;
} else {
if (feld[(int) n] != -1) {
return feld[(int) n];
} else {
long result = fibo(n - 1) + fibo(n - 2);
feld[(int) n] = result;
return result;
}
}
}
public static void main(String[] args) {
long n = 45;
feld = new long[(int) n];
for (int i = 0; i < n; i++) {
feld[i] = -1;
}
long result = fib2(n);
System.out.println("Result: " + result);
}
}