choose.c 553 B

12345678910111213141516171819202122232425
  1. #include "choose.h"
  2. #include "gcd.h"
  3. /*Computes the number of combinations of _n items, taken _m at a time without
  4. overflow.
  5. _n: The total number of items.
  6. _m: The number taken at a time.
  7. Return: The number of combinations of _n items taken _m at a time.*/
  8. unsigned choose(int _n,int _m){
  9. unsigned ret;
  10. int i;
  11. ret=1;
  12. for(i=1;i<=_m;_n--,i++){
  13. int nmi;
  14. nmi=_n%i;
  15. if(nmi==0)ret*=_n/i;
  16. else if(ret%i==0)ret=(ret/i)*_n;
  17. else{
  18. int d;
  19. d=gcd(i,nmi);
  20. ret=(ret/(i/d))*(_n/d);
  21. }
  22. }
  23. return ret;
  24. }