# Factorial

• 09-30-2002
MethodMan
Factorial
Code:

```int Factorial(int n) {     if(n == 1){           return 1;     }           else{                 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?

Thanks
• 09-30-2002
MethodMan
Quote:

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
Salem
> What do you mean by 0! is 1(not 0)
It's in the definition of factorial
http://www.fidcal.com/puzzlets/factorialZero.htm
• 09-30-2002
Cshot
Yes, these guys are right.

Just change this:
if(n == 1)

to
if(n == 0)

and you should get the correct results.
• 09-30-2002
Nick
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.