factorial related problem

Hi all,

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47

#include<iostream>
using namespace 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;
		else
			return x * factorial(x-1);
	}
void c(int n,int r)
	{
		cout<<(factorial(n))/((factorial(r))*(factorial(n-r)));
	}

Last edited on
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)
C(n, K) = C(n-1, K-1) + C(n-1, K)
C(n, n) = C(n, 0) = 1

Last edited on
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.

Thank you fir your response...
Topic archived. No new replies allowed.