我想计算 C(n,k)的组合,其中 n 和 k 可能非常大。我试图通过使用模块化反转如下,但即使是小数字也没有给出正确的输出。谁能告诉我哪里错了?
import java.math.BigInteger;
public class Test {
public static int[] factorials = new int[100001];
public static int mod = 1000000007;
public static BigInteger MOD = BigInteger.valueOf(1000000007);
public static void calculateFactorials() {
long f = 1;
for (int i = 1; i < factorials.length; i++) {
f = (f * i) % mod;
factorials[i] = (int) f;
}
}
// Choose(n, k) = n! / (k! * (n-k)!)
public static long nCk(int n, int k) {
if (n < k) {
return 0;
}
long a = BigInteger.valueOf(k).modInverse(MOD).longValue();
long b = BigInteger.valueOf(n - k).modInverse(MOD).longValue();
// Left to right associativity between * and %
return factorials[n] * a % mod * b % mod;
}
public static void main(String[] args) {
calculateFactorials();
System.out.println(nCk(5, 2));
}
}
答案 0 :(得分:3)
行
long a = BigInteger.valueOf(k).modInverse(MOD).longValue();
long b = BigInteger.valueOf(n - k).modInverse(MOD).longValue();
应该是
long a = BigInteger.valueOf(factorials[k]).modInverse(MOD).longValue();
long b = BigInteger.valueOf(factorials[n - k]).modInverse(MOD).longValue();
您可以考虑缓存反因子和阶乘。