简体   繁体   中英

tail Recursion multiplication using BigInteger

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM