
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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
- Related Articles
- Binomial Coefficient in java
- Maximum binomial coefficient term value in C
- How to find the binomial coefficient of two integers using JavaScript?
- Binomial Heap in C++?
- Binomial Random Variables in C++
- Memory representation of Binomial Heap in C++
- Sum of squares of binomial coefficients in C++
- C program for Binomial Coefficients table
- Find sum of even index binomial coefficients in C++
- Program to find correlation coefficient in C++
- Binomial Distribution in Data Structures
- Binomial Heaps in Data Structure
- C++ Program for Coefficient of variation
- Negative Binomial distribution in Data Structures
- What Is Binomial Nomenclature?
