Skip to main content

Posts

Showing posts with the label STL

Binomial coefficient using C++

  We are aware of the Binomial coefficient, which is a mathematical term used to  represent the number of ways to select a certain number of items/objects from a larger set, without regard to their order. It's denoted by a symbol C(n, k)(n choose k or n over k). It gets computed by following formula:  C(n, k) = n! / (k! * (n - k)!)   The C++ implementation using the above formula is:  int factorial( int n) {     if (n <= 1 )         return 1 ;     else         return n * factorial(n - 1 ); } int binomialCoefficient( int n, int r) {     if (r > n)         return 0 ;     int numerator = factorial(n);     int denominator = factorial(r) * factorial(n - r);     int result = numerator / denominator;     return result; } int main() {      std::cout << "Value of C(" << 5 << ", " << 2 << ") is "          << binomialCoefficient( 5 , 2 ) << "\n" ; } So, the number of ways to choose two i