diff --git a/lib/function/probability/combinations.js b/lib/function/probability/combinations.js index 912c95155..d00ce258d 100644 --- a/lib/function/probability/combinations.js +++ b/lib/function/probability/combinations.js @@ -34,6 +34,27 @@ module.exports = function (math) { } return Math.floor(math.factorial(n) / (math.factorial(k) * math.factorial(n-k))); } + + var isPositiveInteger = function(x) { + if (!x.round().equals(x) || x.lt(0)) { + return false; + } + return true; + }; + + if (n instanceof BigNumber) { + // make sure k is a BigNumber as well + k = new BigNumber(k); + if (isPositiveInteger(n) && isPositiveInteger(k)) { + return math.floor(math.divide(math.factorial(n), + math.multiply(math.factorial(k), + math.factorial(math.subtract(n, k))))); + } + else { + throw new TypeError('Positive integer value expected in function permutations'); + } + } + throw new math.error.UnsupportedTypeError('combinations', n); }; }; diff --git a/lib/function/probability/permutations.js b/lib/function/probability/permutations.js index b4f67270e..c1b2a1552 100644 --- a/lib/function/probability/permutations.js +++ b/lib/function/probability/permutations.js @@ -59,11 +59,13 @@ module.exports = function (math) { if (n instanceof BigNumber) { if (k === undefined && isPositiveInteger(n)) - return math.factorial(n); + return math.factorial(n); // make sure k is a BigNumber as well k = new BigNumber(k); if (isPositiveInteger(n) && isPositiveInteger(k)) { - return math.divide(math.factorial(n), math.factorial(math.subtract(n, k))); + return math.floor(math.divide(math.factorial(n), + math.factorial( + math.subtract(n, k)))); } else { throw new TypeError('Positive integer value expected in function permutations'); diff --git a/test/function/probability/combinations.test.js b/test/function/probability/combinations.test.js index ecd0fa1a1..395ec3c9c 100644 --- a/test/function/probability/combinations.test.js +++ b/test/function/probability/combinations.test.js @@ -11,6 +11,11 @@ describe('combinations', function() { assert.equal(combinations(63, 7), 553270671); }); + it('should calculate the combinations of n items taken k at a time with BigNumbers', function() { + assert.deepEqual(combinations(math.bignumber(7), math.bignumber(5)), math.bignumber(21)); + assert.deepEqual(combinations(math.bignumber(20), math.bignumber(15)), math.bignumber(15504)); + }); + it('should not work with non-integer and negative input', function() { assert.throws(function() {combinations(0.5, 3)}); assert.throws(function() {combinations(3, 5)});