From bc34f3bd19f2231e6305f76782d302014288fd85 Mon Sep 17 00:00:00 2001 From: Ipsita Goel <45857758+ipsitagoel@users.noreply.github.com> Date: Wed, 29 Sep 2021 18:42:42 +0530 Subject: [PATCH] chore(CPlusPlus): add binomial coefficient (#449) Co-authored-by: Ujjwal <75884061+UG-SEP@users.noreply.github.com> --- .../CPlusPlus/Maths/binomial-coefficient.cpp | 40 +++++++++++++++++++ algorithms/CPlusPlus/README.md | 1 + 2 files changed, 41 insertions(+) create mode 100644 algorithms/CPlusPlus/Maths/binomial-coefficient.cpp diff --git a/algorithms/CPlusPlus/Maths/binomial-coefficient.cpp b/algorithms/CPlusPlus/Maths/binomial-coefficient.cpp new file mode 100644 index 00000000..1bab52fe --- /dev/null +++ b/algorithms/CPlusPlus/Maths/binomial-coefficient.cpp @@ -0,0 +1,40 @@ +// C++ code to find the Binomial Coefficient +// Description: Given two parameters n and r, find the value of the Binomial Coefficient i.e. C(n, r) +// Method: Change r to n-r if r is greater than n-r and store it in a variable. Run a loop from 0 to r-1 and in every iteration update result to be (ans*(n-i))/(i+1). Hence, the result will be ((n/1)*((n-1)/2)*…*((n-r+1)/r!) i.e. nCr. +// Time Complexity: O(r) +// Space Complexity: O(1) + +#include +using namespace std; + +int findBinCoeff(int n, int r) +{ + int result = 1; + + if (r > n - r) + { + r = n - r; // C(n, r) = C(n, n-r) + } + + // Find [n*(n-1)*...*(n-r+1)]/[r*(r-1)*...*1] + for (int i = 0; i < r; ++i) + { + result = result * (n - i); + result = result / (i + 1); + } + return result; +} + +int main() +{ + int n; + cout << "Enter the value of n: "; + cin >> n; // Eg value of n: 6 + int r; + cout << "Enter the value of r: "; + cin >> r; // Eg value of r: 2 + // C(6,2) = 6!/(4!*2!) = 15 + cout << "The Binomial Coefficient is: "; + cout << findBinCoeff(n, r) << endl; //Eg output: 15 + return 0; +} \ No newline at end of file diff --git a/algorithms/CPlusPlus/README.md b/algorithms/CPlusPlus/README.md index 13ee1c3b..3352545f 100644 --- a/algorithms/CPlusPlus/README.md +++ b/algorithms/CPlusPlus/README.md @@ -122,6 +122,7 @@ 2. [Prime Number](Maths/prime-check.cpp) 3. [Prime Sieve](Maths/prime-sieve.cpp) 4. [Fibonacci Series](Maths/fibonaccci-series.cpp) +5. [Binomial Coefficient](Maths/binomial-coefficient.cpp) 5. [Armstrong Number](Maths/armstrong.cpp) 6. [Palindrome](Maths/palindrome.cpp) 7. [Reverse digit of a number](Maths/reverse-digits.cpp)