当我尝试计算大数的组合时,例如334选择179,使用Java Apache Math3
CombinatoricsUtils.binomialCoefficient()
方法,我收到一个Exception in thread "main" org.apache.commons.math3.exception.MathArithmeticException: arithmetic exception
我知道这是由于大量(很可能)造成的,所以我检查了几个 StackOverflow 帖子来修复它,但是没有成功。
我的原码:
public static void testCombinations(){
long test = CombinatoricsUtils.binomialCoefficient(334, 179);
System.out.println(test);
}
我修改它以适应大数字:
public static void testCombinations(){
BigInteger test = BigInteger.valueOf(CombinatoricsUtils.binomialCoefficient(334, 179));
System.out.println(test);
}
但这并不能解决问题。我使用标准计算器检查了这个示例的值,使用 nCr(334,179),它是 6.45769855268175x10^98。我不需要这么长的数字,也许数字的开头,也许前 5 或 10 个字符就足够了。但可能是计算过程中产生的错误。我该如何处理这个问题?