Skip to content

Commit 88c6a21

Browse files
authored
Merge pull request #232 from i-priyanshu/master
Binomial Coefficient in C++ using DP fixes #222
2 parents 21edf8c + 378cf49 commit 88c6a21

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
// Write a function that takes two parameters n and k and returns the value of Binomial Coefficient C(n, k).
2+
// For example, our function should return 6 for n = 4 and k = 2, and it should return 10 for n = 5 and k = 2.
3+
4+
// The idea we have used here is inspired by the pascal triangle.
5+
/*
6+
1
7+
1 1
8+
1 2 2 1
9+
1 3 4 3 1 */
10+
11+
#include <bits/stdc++.h>
12+
using namespace std;
13+
14+
int binomial(int n, int r)
15+
{
16+
if (r > n)
17+
return 0;
18+
if (r == 0 || r == n)
19+
return 1;
20+
21+
int dp[n + 1][r + 1];
22+
for (int i = 1; i <= n; i++)
23+
{
24+
for (int j = 1; j <= r; j++)
25+
{
26+
if (i == j || j == 0) // Base Condition
27+
dp[i][j] = 1;
28+
else
29+
{ // we have taken a mod, so that higher results can be calculted too.
30+
dp[i][j] = (dp[i - 1][j - 1] + dp[i - 1][j]) % 10000007;
31+
}
32+
}
33+
}
34+
return dp[n][r];
35+
}
36+
37+
int main()
38+
{
39+
int n;
40+
int r;
41+
cin >> n >> r;
42+
return binomial(n, r);
43+
}

0 commit comments

Comments
 (0)