Problem: Recursive Counting
Now we’ll try out hand at counting operations embedded in recursive functions. Recall that we use recurrence relations to capture these counts, mimicking the structure of the function. We then guess a closed-form solution to the recurrence and check it with an inductive proof.
In class, we analyzed a sorting example. In lab, we’ll analyze two implementations of the power/exponentiation function.
(define (pow1 x y)
(if (zero? y)
1
(* x (pow1 x (- y 1)))))
(define (pow2 x y)
(cond [(= 0 y) 1]
[(= 1 y) x]
[(even? y) (* (pow2 x (/ y 2)) (pow2 x (/ y 2)))]
[else (* x (pow2 x (/ (- y 1) 2)) (pow2 x (/ (- y 1) 2)))]))
For each of pow1
and pow2
:
Identify the critical operation to count.
Give a recurrence relation describing the number of critical operations the function performs as a function of the size of its input.
(Hint: which of the two inputs to
pow1
andpow2
contributes to its runtime?)Guess a closed-form solution to these recurrences by using the substitution method.
(Hint: for
pow2
the following summation identity will be useful:\[ \sum_{i=0}^{n} = 2^i = 2^{n+1} - 1.) \]
Check your closed-form solution with an inductive proof.