C++ program to find permutation and combination npr and ncr :
This C++ program will show you how to find the permutation and combination using user-provided values. We will write one program that takes the values of n and r as input and finds out the required output.
Formula to find permutation and combination :
Before moving to the program, let’s check the formule required to solve it.
Permutation and combination are calculated by considering n distinct elements r at a time. So, we will take the values of n and r from the user. Below is the formula to find out permutation :
P(n,r) = n!/(n-r)!
Similarly, we can calculate the value of combination using the below formula:
C(n,r) = n!/r!(n-r)!
! is used to define factorial.
As you can see, if we know how to find the factorial of a number, we can easily find out npr and ncr values of any two numbers.
C++ program to find permutation and combination:
#include <iostream>
using namespace std;
int findFact(int n)
{
return n == 1 ? 1 : n * findFact(n - 1);
}
int findNpR(int n, int r)
{
return findFact(n) / findFact(n - r);
}
int findNcR(int n, int r)
{
return findFact(n) / (findFact(n - r) * findFact(r));
}
int main()
{
int n, r, nPr, nCr;
cout << "Enter the value of n:" << endl;
cin >> n;
cout << "Enter the value of r:" << endl;
cin >> r;
nPr = findNpR(n, r);
nCr = findNcR(n, r);
cout << "Permutation,nPr : "<< nPr << endl;
cout << "Combination,nCr : "<< nCr << endl;
}
Explanation :
- findFact method is used to find the factorial of a number.
- findNpR and findNcR methods are used to find out the permutation and combination. It takes the values of n and r and returns the values of permutation and combination.
Sample output :
Enter the value of n:
10
Enter the value of r:
3
Permutation,nPr : 720
Combination,nCr : 120
You can try to run this application and find out permutations and combinations for different values.