Why does factorial stop making smaller calls?

Why factorial stops

Theo Brooks

How recursion works

The trail from 2 to 1 to 0 is three calls deep because 0! = 1 needs no further call.

Transcript

To find the factorial of 2, the call on 2 starts a call on 1. That smaller input is your clue to why factorial finishes.

Look at the call on 1: its input is closer to zero because 2 minus 1 equals 1. That's still positive, so the call on 1 waits while it starts the call on 0, because 1 minus 1 equals 0. Subtracting exactly 1 means you can't stay put, and even from the smallest positive whole number, you land right on zero instead of skipping past it.

Now the call on 0 passes the test for a zero input, so it stops the call trail here and answers directly. Only a positive input needs a smaller call, so there's no fourth call on minus 1. Count the calls that haven't finished: the first 2 are waiting while the third is about to answer. The most calls open at once, counting the one you started with, is the maximum call depth. So for the factorial of 2, the maximum call depth is 3.

So the call on 0 gives its answer straight back: zero factorial equals 1. That 1 comes from the rule itself, so there's nothing a smaller call needs to find.

From 2 it took 2 steps down, and that works for any positive whole number because each step takes 1 off the distance left to zero. If you start at zero, you already have the answer without a step down. With that answer, the call on 1 finishes because 1 times 1 equals 1, then the call on 2 finishes because 2 times 1 equals 2. Follow the call trail back: each step down added just one call, so there are only so many calls to finish. So you reach zero and work your way back in finitely many steps, and finishing in finitely many steps is what termination means. That's why termination is guaranteed for factorial whenever you start with a whole number from zero up.