15.2 Recursion
Here we go again...
Now that we've done a couple of nested for loops, let's take a look at our favorite problem: recursion.
Consider the recursive function f3
below:
What does this function do?
Let's think of an example of calling f3(4)
:
The first call will return
f3(4-1) + f3(4-1)
Each
f3(3-1)
call will branch out tof3(2-1) + f3(2-1)
Then for each
f3(2-1)
call, the conditionif (n <= 1)
will be true, which will return 1.What we observe at the end is that 1 will be returned 8 times, meaning we have
f3(2-1)
summed 8 times.Therefore,
f3(4)
will return 8.
We can visualize this as a tree, where each level represents a recursive call and each node value represents the argument to the function :
Method 1: Intuition
Based on the visualization below, we can notice that every time we add one to n
we double the amount of work that has to be done:
Method 2: Algebra
Another way to approach this problem is to count the number of calls to f3
involved. Utilizing the same tree visualization above, we can see that the number of calls to f3 at each recursive level is equivalent to the number of nodes at each recursive level of the tree. For instance, the number of calls we made to f3
at the top level is 1, at the second level is 2, at the third level is 4, etc.
The total number of calls to f3 then is the sum of the number of nodes at each recursive level, which can be expressed as the equation below:
Applying the formula we saw earlier for the sum of the first powers of 2:
Method 3: Recurrence Relation (Out of Scope)
This method is not required reading and is outside of the course scope, but worth mentioning for interest's sake.
We can use a "recurrence relation" to count the number of calls, instead of an algebraic approach. This looks like:
Last updated