View Single Post
Old Jul 26th, 2007, 8:38 PM   #6
Bench
Newbie
 
Join Date: Feb 2006
Posts: 20
Rep Power: 0 Bench is on a distinguished road
Quote:
Originally Posted by 357mag View Post
All I see is a succession of function calls, over and over. What I don't see is where the actual calculations are carried out. The return statement does not say return 4 * 3, or return 3 * 2, or return 2 * 1, or whatever. It actually says return 4 * factorial(3). Then the function calls itself again, and it says return 3 * factorial(2). Then the function calls itself again, and it says return 2 * factorial(1). I realize that somehow it ends up as 4 * 3 * 2 * 1, but the code doesn't really look like that to me. How are the actual calculations carried out? All I see is just the function calling itself until we get down to where the value in number is 1, meaning the function terminates.
No, the function doesn't terminate, it returns a value to itself. What you have is essentially a function call within a function call within a function call within a function call...

If you were to roll it out, it might look something like this (psuedocode)
{
    number * function (number-1)
    {
        number-1 * function (number-2)
        {
            number-2 * function (number-3)
            {
                number-3 * function (number-4)
                {
                    1
                }
            }
        }
    }
}
Just remember that each call to "function" is replaced by ALL the successive blocks of code which stem from that call. Each call is an extra layer of indirection.

Since the function calls only provide indirection, and no actual calculation, the above "unrolling" ends up looking like this
{
    number * 
    {
        number-1 * 
        {
            number-2 * 
            {
                number-3 * 
                {
                    1
                }
            }
        }
    }
}

Last edited by Bench; Jul 26th, 2007 at 8:47 PM. Reason: Adjusted formatting
Bench is offline   Reply With Quote