View Full Version : Factorial

09-30-2002, 04:27 PM
int Factorial(int n)
if(n == 1){
return 1;
return n * Factorial(n -1);

The textbook asks, why might Factorial(0) return 0, and to be honest I have no clue. The call trace would look like:
Facorial(0) = 0 * Factorial(-1)
= 0* (-1) * Factorial(-2)...
it would just go into an infinite regress.

The only way I see it returning 0, if it runs out of resources, and somehow returns a 0, or grabs some piece of memory, which could have been a 0.

Any other possibilities?


09-30-2002, 04:37 PM
Originally posted by Salem
Looks like the book and the code are both broken

0! is 1 (not 0)

And your analysis is correct - as written, that code is off into infinity (and beyond) when called with zero as a parameter.

What do you mean by 0! is 1(not 0)

and I had n + Fatorial
should ahve been n * Factorial

09-30-2002, 04:45 PM
> What do you mean by 0! is 1(not 0)
It's in the definition of factorial

09-30-2002, 05:29 PM
Yes, these guys are right.

Just change this:
if(n == 1)

if(n == 0)

and you should get the correct results.

09-30-2002, 06:15 PM
Eventually in 2's complement n will go back to 1. I think
your stack will overflow by then though. There's always
the remote possibility that the compiler will take out the recursion
but most arn't smart enough.