The combination number is defined as Cnm mn m n Write a fu

The combination number is defined as C^n_m = m!/n! (m - n)! Write a function comb which calculates the combination number C^n_m Comb should be defined as below: int comb (int m, int n) For example, function call comb(6, 3) should return 20.

Solution

main.cpp

#include <iostream>
using namespace std;
#define MAX 100
// function declaration
int comb(int m, int n);

int main () {

   int a;
   int b;
   int ret;
   cout<<\"Enter the value of m : \"<<endl;
   cin>>a;
   cout<<\"Enter the value of n : \"<<endl;
   cin>>b;
   ret = comb(a, b);
   cout << \"Combination number is : \" << ret << endl;
   return 0;
}

int comb(int m, int n) {
int mat[MAX][MAX];
    int i, j;
    if (n > m) return 0;
    if( (n == 0) || (m == n) ) return 1;
    for(j = 0; j < n; j ++)
    {
        mat[0][j] = 1;
        if (j == 0)
        {
            for (i = 1; i<= m - n; i ++ ) mat[i][j] = i + 1;
        }
        else
        {
            for (i = 1; i<= m - n; i ++) mat[i][j] = mat[i - 1][j] + mat[i][j - 1];
        }
    }
    return (mat[m - n][n - 1]);
}

Output :

 The combination number is defined as C^n_m = m!/n! (m - n)! Write a function comb which calculates the combination number C^n_m Comb should be defined as below

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site