我写了一个方法来计算2个数字的组合,它适用于n=10和r=3的较小数字,但当输入n为100和r为3时,它会引发算术异常"/乘零";
import java.util.Scanner;
public class Combination {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter n: ");
int n = scan.nextInt();
System.out.print("nEnter r: ");
int r = scan.nextInt();
scan.close();
int ans = factorial(n) / (factorial((n-r)) * factorial(r));
System.out.print("nThe combination is: "+ans);
}
static int factorial(int num) {
for(int i = num; i>1; --i) {
num *= (i - 1);
}
return num;
}
}
但我不知道问题出在哪里。它适用于较小数量的n。
您所乘的值导致一个数字太大,无法放入整数中。
如果你在for
循环中打印出num
,你会注意到它最终要么为负,要么为零。这是由于溢出造成的。
对于n=100
和r=3
的例子,即使是long
也不行。你需要使用类似BigInteger
的东西。
请记住,与使用基元相比,使用BigInteger
会大大降低程序的速度。
如果你对拥有这么大的数字不感兴趣,只是好奇为什么它不起作用,那么如果你使用的是Java 8
或更高版本,你也可以使用Math.multiplyExact(int x, int y)
或Math.multiplyExact(long x, long y)
。
通过使用这些方法,您将避免处理溢出的副作用,因为如果结果溢出,它们将抛出ArithmeticException
。
将num的数据类型从int更改为double