Question

I am trying to modify my multiplication by addition function to incorporate two things:-

(1) tail recursion (2) bigIntegers

However, for large integers I am still struggling since I got a stack overflow. I even tried to run my program using a -Xss switch to expand the stack but still no luck. I think there is something wrong with my method. Appreciate any advice.

<!-- language-all: lang-java -->
public static BigInteger multiRecursive(int multiplicand, int multiplier) {
    return multiTailRecursive(multiplicand, multiplier, multiplicand);
}

public static BigInteger multiTailRecursive(int multiplicand, int multiplier, int result){      
    if (multiplicand == 0 || multiplier == 0) {
        return BigInteger.valueOf(0);
    }
    if (multiplier == 1) {
        return BigInteger.valueOf(result);
    }

    return multiTailRecursive(multiplicand, multiplier - 1, result + multiplicand);
}
Was it helpful?

Solution

This issue has already been discussed at Stack overflows from deep recursion in Java?:

Increasing the stack size will only serve as a temporary bandage ... what you really want is tail call elimination, and Java does not have this for various reasons.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top