这些天我自己在学习java。该功能是计算组合。但是,我发现这个函数中 n 和 k 的数量有一个非常小的限制。每次如果我输入一个大的 n 或 k,例如 100,它就会给我
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Combination.combination(Combination.java:29)
at Combination.main(Combination.java:47)
或者给我一个负数...
有没有办法让它适用于像 10000 这样的大数字?
谢谢!
import java.util.HashMap; import java.util.Map;
public class Combination {
private Map<Long,Long> factorialMap = new HashMap<Long,Long>();
public Long getFactorial(int number) {
Long val = factorialMap.get(number);
if(val != null) {
return val;
} else {
val = getFactorialRecursive(number);
factorialMap.put((long) number, val);
return val;
}
}
public Long getFactorialRecursive(int number) {
if(number == 1 || number == 0) {
return 1L;
} else {
return number * getFactorialRecursive(number-1);
}
}
public Long combination(int fromVal, int chooseVal) {
return getFactorial(fromVal)/(getFactorial(chooseVal)*getFactorial(fromVal-chooseVal));
}
public static void main(String[] args) {
int n, k;
Combination comb = new Combination();
java.util.Scanner console = new java.util.Scanner(System.in);
while (true) // will break with k > n or illegal k or n
{ System.out.print ("Value for n: ");
n = console.nextInt();
if ( n < 0 ) break;
System.out.print ("Value for k: ");
k = console.nextInt();;
if ( k > n || k < 0 )
break;
System.out.print(n +" choose " + k + " = ");
System.out.println(comb.combination(n,k));
}
console.nextLine(); // Set up for "Press ENTER...
} }