Optimizing calculating combination and avoiding overflows

前端 未结 2 1295
借酒劲吻你
借酒劲吻你 2021-01-25 01:42

I am solving a programming problem which is stuck at calculating nCr efficiently and at the same time avoiding overflows. I have made the following trivial simplifi

2条回答
  •  后悔当初
    2021-01-25 02:31

    I found an interesting solution here: http://blog.plover.com/math/choose.html

        unsigned choose(unsigned n, unsigned k) {
          unsigned r = 1;
          unsigned d;
          if (k > n) return 0;
          for (d=1; d <= k; d++) {
            r *= n--;
            r /= d;
          }
          return r;
        }
    

    This avoids overflows (or at least limits the problem) by performing multiplication and division alternatively.

    E.g. for n = 8, k = 4:

    result = 1;
    result *= 8;
    result /= 1;
    result *= 7;
    result /= 2;
    result *= 6;
    result /= 3;
    result *= 5;
    result /= 4;
    done
    

提交回复
热议问题