[英]tail Recursion multiplication using BigInteger
I am trying to modify my multiplication by addition function to incorporate two things:- 我正在尝试通过加法函数修改乘法以合并两件事:-
(1) tail recursion (2) bigIntegers (1)尾递归(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.
我什至尝试使用-Xss开关运行程序来扩展堆栈,但仍然没有运气。 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? 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.
增加堆栈大小只会充当临时绷带……您真正想要的是消除尾部调用,而Java出于各种原因没有此功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.