nPr and nCr (Using Recursion)
- Annonymous
- Aug 5, 2015
- 1 min read
Q. Design a program to find the Permutation (nPr) and Combination (nCr) of 'r' objects out of 'n' distinct objects using Recursion.
SAMPLE INPUT :
n = 5
r = 2
SAMPLE OUTPUT :
nPr = 20
nCr = 10
PRE-REQUISITES :
- Functions, declaration and calling
- Recursion (a method in which the function calls itself)
CODE :
#include <iostream>
using namespace std;
int nfact(int x){
if(x==1){
return 1;
}else{
return x*nfact(x-1);
}
}
int rfact(int y){
if(y==1){
return 1;
}else{
return y*rfact(y-1);
}
}
int nminusrfact(int z){
if(z==1){
return 1;
}else{
return z*nminusrfact(z-1);
}
}
int main()
{
int n, r;
cout<< "n = ";
cin>> n;
cout<< "r = ";
cin>> r;
if(n>0 && r>=0 && r<=n){
cout<< endl << "nPr = " << nfact(n)/nminusrfact(n-r) << endl;
cout<< endl << "nCr = " << nfact(n)/(rfact(r)*nminusrfact(n-r));
}else{
cout<< endl << "Error Receiving Input!" << endl;
cout<< "Note: 0<=r<=n";
}
return 0;
}
Commentaires