Which is better way to calculate nCr

前端 未结 5 641
情深已故
情深已故 2020-11-30 23:48

Approach 1:
C(n,r) = n!/(n-r)!r!

Approach 2:
In the book Combinatorial Algorithms by wilf, i have found this:
C(n,r) can be written as C(n-1,r) + C

5条回答
  •  时光取名叫无心
    2020-12-01 00:20

    unsigned long long ans = 1,a=1,b=1;
            int k = r,i=0;
            if (r > (n-r))
                k = n-r;
            for (i = n ; k >=1 ; k--,i--)
            {
                a *= i;
                b *= k;
                if (a%b == 0)
                {
                    a = (a/b);
                    b=1;
                }
            }
            ans = a/b;
    

提交回复
热议问题