My main goal is to compute the Stirling number of the second kind with an input of 1 to 500. Without using the BigInteger option/import, the code works flawlessly but the moment I use the said import, I encounter java.lang.StackOverFlowError because of BigInteger k (I tried converting it to d out of desperation).
Hope someone can help. And if possible, please point out other errors if you will spot any. Thank you!
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);
}
}
}