Added BigNumber support to combinations (and tests)

This commit is contained in:
Daniel Levin 2014-01-07 13:27:56 +02:00
parent 17acaaf9eb
commit f6fa5bf575
3 changed files with 30 additions and 2 deletions

View File

@ -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);
};
};

View File

@ -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');

View File

@ -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)});