simple-squiggle

A restricted subset of Squiggle
Log | Files | Refs | README

combinations.js (1400B)


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