使用modInverse计算大数的C(n,k)组合

时间:2014-08-18 03:39:57

标签: java algorithm combinations combinatorics modular-arithmetic

我想计算 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));

    }

}

1 个答案:

答案 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();

您可以考虑缓存反因子和阶乘。