LoLisSuck LoLisSuck - 6 months ago 9
Java Question

Using recursion but encounter "Source not found" and Stackoverflow

I wrote a function to recursively add and print 0~n.

i thought BigInteger can store and manipulate large number.

But I encountered some bug.
I tried to use sysout and set upBoundStr to 10000.

The bug is still there.
Could someone tell me what happened?




My code



package playground;

import java.math.BigInteger;

public class play1
{
String initStr = "0";
String dStr = "1";
String upBoundStr = "1000000";
private BigInteger i = new BigInteger(initStr);
private BigInteger diff = new BigInteger(dStr);
private BigInteger upBound = new BigInteger(upBoundStr);

public void countBigInteger()
{
i = i.add(diff);
System.out.printf("%s",i);
//System.out.println(i);
if(i.compareTo(upBound)==-1)
{
countBigInteger();
}
}

public static void main(String args[])
{
play1 p1 = new play1();
p1.countBigInteger();
}
}





Logs



enter image description here

enter image description here

Answer

The call stack has a limited size. I tried your code and got StackOverflowError after printing 6600 numbers. This means that the call stack had enough space for 6600 method calls before it ran out of space. That's the risk of running such a deep recursion.

This has nothing to do with BigInteger, since this code fails before you even get near the max value of int (or even short).

If the goal of this code is to test recursion, you found out that deep recursion has limits. If that code serves some other purpose, you can easily re-write it without using any recursion at all.