문제

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);
}
도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top