java.lang.StackOverFlow使用BigInteger计算第二类Stirling数时出错



我的主要目标是计算第二类Stirling数,输入为1到500。在不使用BigInteger选项/import的情况下,代码工作得很完美,但当我使用上述导入时,我遇到了java.lang.StackOverFlowError,因为BigInteger k(我绝望地尝试将其转换为d(。

希望有人能帮忙。如果可能的话,如果你发现任何错误,请指出其他错误。非常感谢。

import java.util.*;
import java.math.*;
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
try{
System.out.print("Please enter the r: ");
BigInteger n = sc.nextBigInteger();
System.out.print("Please enter the n: ");
BigInteger k = sc.nextBigInteger();
BigInteger constant= new BigInteger("0");
BigInteger result = new BigInteger("1");
BigInteger result2 = new BigInteger("500");
int result3 = n.compareTo(result);
int result4 = n.compareTo(result2);
int result5 = k.compareTo(result);
int result6 = k.compareTo(result2);
int result7 = n.compareTo(constant);
int result8 = k.compareTo(constant);

if (result3 == -1 || result4==1){
System.out.println("n must be 1 to 500");
}
if (result5 ==-1 || result6 == 1){
System.out.println("k must be 1 to 500");
}
else if (result7 == 1 && result4 == -1 && result8 == 1 && result6 == -1){
System.out.println("The answer is: " + StirlingFunction(n, k));
}
}
catch(InputMismatchException a){
System.out.println("The input must be an integer.");
}
}

public static BigInteger StirlingFunction(BigInteger n, BigInteger k){
BigInteger d= new BigInteger("0").add(k);
BigInteger a = BigInteger.ONE;
if (k.compareTo(BigInteger.ONE) == 0 || k == n){
return BigInteger.ONE;
}
else{
BigInteger x = (StirlingFunction(n.subtract(a), d));
BigInteger y = (StirlingFunction(n.subtract(a), k.subtract(a)));
return k.multiply(x).add(y);
}
}
}

这是结果/输出

修改以回答错误。

k==n

从来都不是真的,因为它们是不同的对象,所以您的代码永远不会碰到它的基本情况。将其更改为

`k.equals(n)`

使您的代码快速给出正确答案,没有任何错误。

以下内容翻译自递归函数中的第一个分区、stirling数和切比雪夫多项式的帖子,可能有帮助,也可能没有帮助。我试着让事情尽可能接近这一点,尽可能简单,同时几乎模仿你的代码。

public static BigInteger StirlingFunction(BigInteger n, BigInteger k){
if (BigInteger.ZERO.equals(n) && BigInteger.ZERO.equals(k)){
return BigInteger.ONE;
}
//still here, not both zero
if (BigInteger.ZERO.equals(n) || BigInteger.ZERO.equals(k)){
return BigInteger.ZERO;
}
BigInteger x = StirlingFunction(n.subtract(BigInteger.ONE), k);
BigInteger y = StirlingFunction(n.subtract(BigInteger.ONE), k.subtract(BigInteger.ONE));
//S2(n, k) = k * S2(n - 1, k) + S2(n - 1, k - 1)
return k.multiply(x).add(y);
}

最新更新