Wednesday 22 November 2017

C++ Program to Compute Combinations using Matrix Multiplication


Code:

#include    iostream

using namespace std;

// A function to find the factorial of a given number using matrix multiplication method.
int MatFactorial(int n)
{
int i, j, k, matA[n+1][n+1], matB[n+1][n+1], matC[n+1][n+1], count;
count = n;
// Assigning numbers from 1 to n to the super diagonal indexes of the matrix.
// Assigning result matric matC[][] to zero initially.
for(i = 0; i < n+1; i++)
{
for(j = 0; j < n+1; j++)
{
if(j == i+1)
matA[i][j] = i+1;
else
matA[i][j] = 0;

// Assign matB[][] equal to initially to compute square.
matB[i][j] = matA[i][j];
matC[i][j] = 0;
}
}

flag:
// Multiply matA[][] and matB[][] and store the data into matC[][].
for(i = 0; i < n+1; i++)
{
for(j = 0; j < n+1; j++)
{
for(k = 0; k < n+1; k++)
{
matC[i][j] += matA[i][k]*matB[k][j];
}
}
}

// Assign matB as the result matrix matC[][] and then assign matC[i][j] element to zero again.
for(i = 0; i < n+1; i++)
{
for(j = 0; j < n+1; j++)
{
matB[i][j] = matC[i][j];
matC[i][j] = 0;
}
}

count--;
// We need to compute the matA[][] raise to the power of n so if count is more than 1 then increase the power of matA[][].
if(count > 1)
goto flag;

// If matA[][] raise to n is calculated, then return the last element of the first row of matB[][], as the factorial of n.
return matB[0][n];
}

int main()
{
int n, r,  result;
cout<<"A program to find combination from nCr format using matrix multiplication method:-";
cout<<"\n\n\tEnter the value of n: ";
cin>>n;
cout<<"\tEnter the value of r: ";
cin>>r;

// Get result using formulae to calculate combinations.
result = MatFactorial(n)/(MatFactorial(r)*MatFactorial(n-r));

cout<<"\nThe number of possible combinations is: "<

return 0;
}


Output:

Case 1:
A program to find combination from nCr format using matrix multiplication method:-

        Enter the value of n: 5
        Enter the value of r: 3

The number of possible combinations is: 10

Case 2:
A program to find combination from nCr format using matrix multiplication method:-

        Enter the value of n: 10
        Enter the value of r: 3

The number of possible combinations is: 120



More C Programs:















100+ Best Home Decoration Ideas For Christmas Day 2019 To Make Home Beautiful

Best gifts for Christmas Day | Greeting cards for Christmas Day | Gift your children a new gift on Christmas day This Christmas d...