# Thread: recursive factorial function

1. ## recursive factorial function

I am having trouble getting started writing a recursive function to calculate a factorial, like this:

n!/r!*(n-r)!

Where n and r and numbers entered by the user and the ! represents the factorial process. It needs to be a single function.

Any ideas on getting started?

2. You could try naming the successive calls to the function different names to keep things straight in your mind, and then at the end change them all to the same name.

3. Here is what I have so far:

Code:
``` #include <iostream>

unsigned long factorial(unsigned long n, unsigned long r);	//	function prototype

int main()
{
unsigned long answer, things, sets;
cout << "Please enter the number of items: " << endl;
cin >> things;
cout << "Please enter the number of sets: " << endl;
cin >> sets;
answer = factorial (things, sets);
cout << "The answer is: " << answer << endl;

return 0;

}

unsigned long factorial(unsigned long n, unsigned long r)	//	recursive function
{
unsigned long a, b;

while (n > 1)
{
a = n * factorial((n -1), r);
}

while (r >1)
{
b = r * factorial((r-1), n);
}

if (r <= 1 && n <= 1)
return  a/( b *(a-b));
}```
This will compile, but not much else.

4. Why does it "have" to be one function. It certainly won't work the way you've done it, I'm afraid.

Something like this might be better:
ans = factorial(n) / factorial(r) * (n - r)

5. I agree that would be a simpler and more direct solution. How would I get both my variables into the function in the first place?

6. Have you tried looking on the Internet? Also, how about some CS texts or algorithm books. This should be simple.

7. A correct recursive factorial function would be
Code:
```unsigned int fac(unsigned int i)
{
return (i <= 1) ? 1 : (i * fac(i-1));
}```
Or iterative:
Code:
```unsigned int fac(unsigned int i)
{
int ret = 1;
for(;i>1;--i)
ret *= i;
return ret;
}```
Iterative is better of course.

To calculate this
n!/r!*(n-r)!
you would write
Code:
`unsigned int res = fac(n)/fac(r)*fac(n-r);`

Popular pages Recent additions