15.6 Exercises

Doing more practices is the best way to gain intuition when it comes to asymptotics!

Factual

  1. Prove that Θ(log2n)=Θ(log3n)\Theta(\log _{2} n) = \Theta(\log _{3} n).

  2. What is the runtime of the following function?

public static int f(int n) {
    if (n <= 1) {
        return 0;
    }
    return f(n - 1) + f(n - 1) + f(n - 1);
}
chevron-rightProblem 1hashtag

Using the properties of logs, we see that log2n=lognlog2=Θ(logn)\log_2 n = \frac{\log n}{\log 2} = \Theta(\log n). Similarly, log3n=lognlog3=Θ(logn)\log_3 n = \frac{\log n}{\log 3} = \Theta(\log n). So when consiering asymptotics relating to logarithms, the base does not matter (as long as it is some constant).

chevron-rightProblem 2hashtag

This is essentially fib with 3 recursive calls instead of 2. The runtime is Θ(3n)\Theta(3^n).

Procedural

  1. Find the runtime of running print_fib with for arbitrarily large n.

  1. Do the above problem again, but change the body of the for loop in print_fib to be:

  1. Find the runtime of the function f on an input of size n, given the createArray function as described below:

  1. Problem 8arrow-up-right from the Spring 2018 Midterm 2

  2. Problem 4arrow-up-right from the Spring 2017 Midterm 2

chevron-rightProblem 1hashtag

From lecture, we know that fib(i) runs in roughly 2i2^i time. If we run fib for each i from 1 to n, we get a total work of 20+21+...2n2^0 + 2^1 + ... 2^n. Note that this is a geometric sum with last term 2n2^n, so the overall runtime is actually still Θ(2n)\Theta(2^n).

chevron-rightProblem 2hashtag

Again, we know that fib(i) takes about 2i2^i time. However, this time we call fib(n) each time in the loop n total times. This gives a runtime of Θ(n2n)\Theta(n2^n).

chevron-rightProblem 3hashtag

This function creates two recursive branches of half the size per call, with each node taking linear work. As such, each level has nn total work, and since we halve the input each time, there are logn\log n total levels, for a runtime of Θ(nlogn)\Theta(n \log n).

chevron-rightProblem 4hashtag

Solutionsarrow-up-right and walkthrougharrow-up-right are linked here and on the course website.

chevron-rightProblem 5hashtag

Solutionsarrow-up-right are linked here and on the course website.

Metacognitive

  1. What would the runtime of modified_fib be? Assume that values is an array of size n. If a value in an int array is not initialized to a number, it is automatically set to 0.

chevron-rightProblem 1hashtag

This is an example of dynamic programming, a topic covered in more depth in CS170. Note that since values is saved across calls, we only recompute each value of n once. Computing a single value of n only takes constant time, since we just add two already-computed values or do an array access. As such, the overall runtime is linear: Θ(n)\Theta(n).