Fastest way to generate binomial coefficients

后端 未结 11 1761
[愿得一人]
[愿得一人] 2020-12-13 02:20

I need to calculate combinations for a number.

What is the fastest way to calculate nCp where n>>p?

I need a fast way to generate binomial coefficients for a

11条回答
  •  眼角桃花
    2020-12-13 03:08

    nCp = n! / ( p! (n-p)! ) =
          ( n * (n-1) * (n-2) * ... * (n - p) * (n - p - 1) * ... * 1 ) /
          ( p * (p-1) * ... * 1     * (n - p) * (n - p - 1) * ... * 1 )
    

    If we prune the same terms of the numerator and the denominator, we are left with minimal multiplication required. We can write a function in C to perform 2p multiplications and 1 division to get nCp:

    int binom ( int p, int n ) {
        if ( p == 0 ) return 1;
        int num = n;
        int den = p;
        while ( p > 1 ) {
            p--;
            num *= n - p;
            den *= p;
        }
        return num / den;
    }
    

提交回复
热议问题