Skip to content

Commit 97623e9

Browse files
committed
add code for computing Combinations(nCr)
1 parent 911a8a9 commit 97623e9

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

Math/Combinations (nCr)/nCr.cpp

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
#include <iostream>
2+
using namespace std;
3+
4+
// Returns n choose r. (i.e. The number of distinct sets of size k chosen from n items). [O(r)]
5+
// Note that C(n, r) = C(n, n - r)
6+
// So call the function with nCr(n, min(r, n-r)) for better performance.
7+
int nCr(int n, int r) {
8+
if (n < r)
9+
return 0;
10+
11+
if (r == 0)
12+
return 1;
13+
14+
return n * nCr(n - 1, r - 1) / r;
15+
}
16+
17+
int main(int argc, char** argv){
18+
19+
if(argc > 2){
20+
int n = atoi(argv[1]), r = atoi(argv[2]);
21+
printf("%d choose %d = %d\n", n, r, nCr(n,r));
22+
}
23+
24+
return 0;
25+
}

0 commit comments

Comments
 (0)