Algorithm for Calculating Binomial Coefficient

前端 未结 5 2000
别跟我提以往
别跟我提以往 2020-12-10 05:30

I need a way of calculating combinations without running out of memory. Here\'s what i have so far.

public static long combination(long n, long k) // nCk
{
          


        
5条回答
  •  误落风尘
    2020-12-10 06:04

    One of the best methods for calculating the binomial coefficient I have seen suggested is by Mark Dominus. It is much less likely to overflow with larger values for N and K than some other methods.

    public static long GetBinCoeff(long N, long K)
    {
       // This function gets the total number of unique combinations based upon N and K.
       // N is the total number of items.
       // K is the size of the group.
       // Total number of unique combinations = N! / ( K! (N - K)! ).
       // This function is less efficient, but is more likely to not overflow when N and K are large.
       // Taken from:  http://blog.plover.com/math/choose.html
       //
       long r = 1;
       long d;
       if (K > N) return 0;
       for (d = 1; d <= K; d++)
       {
          r *= N--;
          r /= d;
       }
       return r;
    }
    

提交回复
热议问题