combinations.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.combinationsNumber = combinationsNumber;
  6. var _number = require("../../utils/number.js");
  7. var _product = require("../../utils/product.js");
  8. function combinationsNumber(n, k) {
  9. if (!(0, _number.isInteger)(n) || n < 0) {
  10. throw new TypeError('Positive integer value expected in function combinations');
  11. }
  12. if (!(0, _number.isInteger)(k) || k < 0) {
  13. throw new TypeError('Positive integer value expected in function combinations');
  14. }
  15. if (k > n) {
  16. throw new TypeError('k must be less than or equal to n');
  17. }
  18. var nMinusk = n - k;
  19. var answer = 1;
  20. var firstnumerator = k < nMinusk ? nMinusk + 1 : k + 1;
  21. var nextdivisor = 2;
  22. var lastdivisor = k < nMinusk ? k : nMinusk;
  23. // balance multiplications and divisions to try to keep intermediate values
  24. // in exact-integer range as long as possible
  25. for (var nextnumerator = firstnumerator; nextnumerator <= n; ++nextnumerator) {
  26. answer *= nextnumerator;
  27. while (nextdivisor <= lastdivisor && answer % nextdivisor === 0) {
  28. answer /= nextdivisor;
  29. ++nextdivisor;
  30. }
  31. }
  32. // for big n, k, floating point may have caused weirdness in remainder
  33. if (nextdivisor <= lastdivisor) {
  34. answer /= (0, _product.product)(nextdivisor, lastdivisor);
  35. }
  36. return answer;
  37. }
  38. combinationsNumber.signature = 'number, number';