Question 2: Recursion revisited.
[11]
Consider how to implement the "exponentiation" operation, i.e., given a real number (double)
a and a positive integer n, we want to find $a^n$. Let us call this function pow(a, n)
(a) [3] Consider the naïve implementation: pow(a, n) = a * pow(a, n-1), with the base case
of n = 1, where we return a. What is the running time of computing pow(a, n)? [Justify
your answer with a line of reasoning.]
(You may assume that multiplying two doubles takes O(1) time.)
(b) [4] You ask ChatGPT if there's a smarter way, and it produces the following pseudocode:
Algorithm 1 Procedure pow(a, n)
1: if n=1 then
2:
return a
3: end if
4: if n%2== 0 then
5: return pow($\frac{a}{2}$,$\frac{n}{2}$) * pow($\frac{a}{2}$,$\frac{n}{2}$)
6: else
7:
return a * pow(a, $\lfloor \frac{n}{2} \rfloor$) * pow(a, $\lfloor \frac{n}{2} \rfloor$)
8: end if
Assuming that n > 1 is a power of 2, write a recurrence for the running time of pow(a, n)
(note that it is a function only of n). Obtain a closed form.