Analysis of a Recursive Function
Performing an analysis of a recursive function is not all that different from performing an analysis of a non-recursive function. We are still going to use the same methodology to find a formula that will represent the number of operations required for a given data size. We will then use that formula to find a curve that best describes the resource usage growth rate.
Analysis of Factorial function
How would we perform an analysis on the following piece of code?
Start by declaring our mathematical variables and functions
Let represent the number we are finding the factorial of
Let represent the number of operations it takes to find n! using our recursive function
Similar to iterative version of our code, we will simply count our operations:
Now... by definition represents the number of ops needed to our function (factorial) requires when given as its argument. But this also means that would represent the number of ops needed by our function to find (n-1)! (ie number of operations performed by our function when n-1 is passed in as the argument.
Thus, we can actually rewrite our count summary as follows:
Now... how do we solve this though? So, lets start by looking at our base cases. If n <= 1, we do exactly 3 operations:
In otherwords, we can say the following:
Remember that is a function that represents how many operations our function requires to find factorial of the argument n. So if argument was 0, it takes 3 ops, if argument was 1, it takes 3 ops also. Notice how the analysis of this coincides with the base case of the recursive function
For n >= 2, we do the following 6 operations + we need count number of ops in the recursive call:
Thus, we can write the expression as following for the general for n >=2
Now... by definition T(n) represents the number of ops needed to find n! using our function. But this also means that T(n-1) would represent the number of ops needed to find (n-1) factorial using our function. Thus,
by the same token, we can say that
etc...
In other words T(n-1) = 6 + number of operations done by factorial(n-2). Similarly T(n-2) = 6 + number of operations done by factorial(n-3)
The above statement is true for all values of n >= 2. However, we also know that:
and
Thus, what we have is:
\begin{align*} T(n) &= 6 + T(n-1) \\ &= 6 + 6 + T(n-2) \\ &= 6 + 6 + 6+T(n-3) \\ ... \\ T(n) &= 6 + 6 + 6 + .... 6+ 3 \end{align*}
There are a total of (n-1) 6's.We know this because we need to reach T(1) to get the 3.
Thus:
Thus, is
Last updated