I'm on a new assignment. Im suppose to write a code that prompts the user to enter value for "n" and "r," where n is the total number of items in a group, and r is the number of a select items in the group. the output will be c(n,r)= the number of different ways r can be selected from n, using the formula c(n,r)=n!/(r!(n-r)!).
I wrote a code that gave me the right results, but the problem is when I enter a number for n that is greater than 12, I get the wrong result and I dont know why, but I believe the problem is with the factorial itself (lines37-43). Any help would be appreciated.
Thanks in advance.
#include<iostream>
usingnamespace std;
//Prototype of functions
void c(int,int);
//Main Program(User Prompt>input collect>function application>outputpresent)
int main()
{
int n,r;
cout<<"This program will calculate the number of ways you can\nselect a number of certain items from a group of total items...\n\n";
while(cin)
{
cout<<"Please enter the total number of items in the group: \n\n";
cin>>n;
n=abs(n);
cout<<"\nPlease enter the number of certain items in the group: \n\n";
cin>>r;
r=abs(r);
if(n<r)
{
cout<<"The number of (certain items) cannot \nexceed the (total) number of items in a group\n\n";
continue;
}
cout<<"\nYou can select the "<<"("<<r<<")"<<" certain items\nfrom the group of "<<"("<<n<<")"<<" items in \n--> (";
c(n,r);
cout<<") different ways.\n\n";
}
return 0;
}
//definitions of functions
int factorial(int x)
{
if(x==0)
return 1;
elsereturn x * factorial(x-1);
}
void c(int n,int r)
{
cout<<(factorial(n))/((factorial(r))*(factorial(n-r)));
}
The code is fine, the problem is overflow (your number is too big).
However there is a nice dynamic approach to obtain the combinatorial numbers (avoiding bignum calculation)
ne555,
I've adressed the overflow with my professor, and he will decide whether to set a limit on the input or still require a more "dynamic formula," in which case I benefit from your suggestion.