chore(CPlusPlus): add binomial coefficient (#449)
Co-authored-by: Ujjwal <75884061+UG-SEP@users.noreply.github.com>pull/502/head
parent
5e49928d84
commit
bc34f3bd19
|
@ -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 <bits/stdc++.h>
|
||||||
|
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;
|
||||||
|
}
|
|
@ -122,6 +122,7 @@
|
||||||
2. [Prime Number](Maths/prime-check.cpp)
|
2. [Prime Number](Maths/prime-check.cpp)
|
||||||
3. [Prime Sieve](Maths/prime-sieve.cpp)
|
3. [Prime Sieve](Maths/prime-sieve.cpp)
|
||||||
4. [Fibonacci Series](Maths/fibonaccci-series.cpp)
|
4. [Fibonacci Series](Maths/fibonaccci-series.cpp)
|
||||||
|
5. [Binomial Coefficient](Maths/binomial-coefficient.cpp)
|
||||||
5. [Armstrong Number](Maths/armstrong.cpp)
|
5. [Armstrong Number](Maths/armstrong.cpp)
|
||||||
6. [Palindrome](Maths/palindrome.cpp)
|
6. [Palindrome](Maths/palindrome.cpp)
|
||||||
7. [Reverse digit of a number](Maths/reverse-digits.cpp)
|
7. [Reverse digit of a number](Maths/reverse-digits.cpp)
|
||||||
|
|
Loading…
Reference in New Issue