Skip to content

Commit 67f0a95

Browse files
committed
Updated combinations.md
1 parent 49b2835 commit 67f0a95

File tree

1 file changed

+10
-3
lines changed

1 file changed

+10
-3
lines changed

snippets/javascript/mathematical-functions/combinations.md

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,10 @@ tags: math,number-theory,algebra
77

88
```js
99
function combinations(n, r) {
10+
if (n < 0 || r < 0 || n < r) {
11+
throw new Error('Invalid input: n and r must be non-negative and n must be greater than or equal to r.');
12+
}
13+
1014
function factorial(x) {
1115
if (x === 0 || x === 1) return 1;
1216
let result = 1;
@@ -15,10 +19,13 @@ function combinations(n, r) {
1519
}
1620
return result;
1721
}
18-
return factorial(n) / (factorial(r) * factorial(n - r));
22+
23+
const numerator = factorial(n);
24+
const denominator = factorial(r) * factorial(n - r);
25+
return numerator / denominator;
1926
}
2027

2128
// Usage:
22-
combinations(12,24); // Returns: 7.720248753351544e-16
23-
combinations(1,22); // Returns: 8.896791392450574e-22
29+
combinations(24,22); // Returns: 276
30+
combinations(5,3); // Returns: 10
2431
```

0 commit comments

Comments
 (0)