Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optimizing calculating combination and avoiding overflows

Tags:

c

overflow

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 simplification but am just curious about if there are any more sophisticated simplifications available out there.

(n)!/(n-k)!*k! = n*(n-1)*.....*(max(n-k+1, k))/(min(n-k, k-1))

Can there be any more simplification possible considering different cases for k as even or odd, just suggesting a way.

Any comment is appreciated.

like image 995
Aman Deep Gautam Avatar asked Sep 13 '25 10:09

Aman Deep Gautam


1 Answers

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
like image 83
Bartosz Moczulski Avatar answered Sep 15 '25 00:09

Bartosz Moczulski