I'm trying to compute large numbers of the Fibonacci sequence, hence why I am using big integer. I can get up to about 10000 the way it is, but I run out of stack space. I realize I can increase stack and heap space, but it is my understanding that tail recursion can get around the space issue. Here is my code..
public class FibRecursion{
static BigInteger[] fval;
public static void main(String[] args) {
int index;
Scanner input = new Scanner(System.in);
index = input.nextInt();
fval = new BigInteger[index + 1];
System.out.println(fib_rec(index));
}
public static BigInteger fib_rec(int index){
BigInteger result = BigInteger.ONE;
if(index <= 2){
return result;
}
else{
if(fval[index] != null){
result=fval[index];
}
else{
result = fib_rec(index-1).add(fib_rec(index-2));
fval[index] = result;
}
return result;
}
}
}
A simple recursion to achieve the series you want could be :
To avoid stack limitations, you can limit the recursion depth and do the resurrection in a few "pieces". Here is an example of a series of 50 elements, calculated with depth limited to 10 (
RECURRSION_DEPTH = 10
):This of course has other limitations, not related to stack size.