WAP to find out ncr factor by using a user defined function for factorial.
FORMULA : ncr = n! / ((n-r)! * r!)
Objective
Write a C++ program to calculate the combinations formula (nCr) using a Factorial function.
Algorithm / Approach
- Define a
fact()function. - In
main(), readnandr. - Calculate nCr using the mathematical formula:
fact(n) / (fact(n-r) * fact(r)). - Print the result.
main.cpp
#include<iostream>
using namespace std;
int fact(int);
int main(){
int n,r, res;
cout<<"Enter n: ";
cin>>n;
cout<<"Enter r: ";
cin>>r;
res = fact(n)/(fact(n-r)*fact(r));
cout<<"Result nCr Is: "<< res;
}
int fact(int x){
int i, f=1;
for(i=1; i<=x; i++){
f = f*i;
}
return f;
}
Expected Output
Enter n: 5 Enter r: 3 Result nCr Is : 10
Explanation of the Program
- This perfectly demonstrates the power of reusable functions.
- The combinations formula (nCr) requires calculating three separate factorials. Instead of writing three separate
forloops in our main code, we simply call our reusablefact()function three times in a single mathematical equation!
Complexity
Time Complexity
O(n) - Because fact(n) is O(n).
Space Complexity
O(1)