Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Binomial Coefficient in C++
Binomial coefficient denoted as c(n,k) or ncr is defined as coefficient of xk in the binomial expansion of (1+X)n.
The Binomial coefficient also gives the value of the number of ways in which k items are chosen from among n objects i.e. k-combinations of n-element set. The order of selection of items not considered.
Here, we are given two parameters n and k and we have to return the value of binomial coefficient nck .
Example
Input : n = 8 and k = 3 Output : 56
There can be multiple solutions to this problem,
General Solution
There is a method to calculate the value of c(n,k) using a recursive call. The standard formula for finding the value of binomial coefficients that uses recursive call is −
c(n,k) = c(n-1 , k-1) + c(n-1, k)
c(n, 0) = c(n, n) = 1
The implementation of a recursive call that uses the above formula −
Example
#include <iostream>
using namespace std;
int binomialCoefficients(int n, int k) {
if (k == 0 || k == n)
return 1;
return binomialCoefficients(n - 1, k - 1) + binomialCoefficients(n - 1, k);
}
int main() {
int n=8 , k=5;
cout<<"The value of C("<<n<<", "<<k<<") is "<<binomialCoefficients(n, k);
return 0;
}
Output
The value of C(8, 5) is 56
Another solution might be using overlapping subproblem. So, we will use dynamic programming algorithm to avoid subproblem.
Example
#include <bits/stdc++.h>>
using namespace std;
int binomialCoefficients(int n, int k) {
int C[k+1];
memset(C, 0, sizeof(C));
C[0] = 1;
for (int i = 1; i <= n; i++) {
for (int j = min(i, k); j > 0; j--)
C[j] = C[j] + C[j-1];
}
return C[k];
}
int main() {
int n=8, k=5;
cout<<"The value of C("<<n<<", "<<k<<") is "<<binomialCoefficients(n,k);
return 0;
}
Output
The value of C(8, 5) is 56