mirror of
https://github.com/josdejong/mathjs.git
synced 2026-01-25 15:07:57 +00:00
Added BigNumber support to combinations (and tests)
This commit is contained in:
parent
17acaaf9eb
commit
f6fa5bf575
@ -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);
|
||||
};
|
||||
};
|
||||
|
||||
@ -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');
|
||||
|
||||
@ -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)});
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user