15.6 Exercises
Doing more practices is the best way to gain intuition when it comes to asymptotics!
Last updated
Doing more practices is the best way to gain intuition when it comes to asymptotics!
Last updated
Prove that .
What is the runtime of the following function?
Find the runtime of running print_fib
with for arbitrarily large n.
Do the above problem again, but change the body of the for loop in print_fib
to be:
Find the runtime of the function f
on an input of size n
, given the createArray
function as described below:
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.
From lecture, we know that fib(i)
runs in roughly time. If we run fib
for each i
from 1
to n
, we get a total work of . Note that this is a geometric sum with last term , so the overall runtime is actually still .
Again, we know that fib(i)
takes about time. However, this time we call fib(n)
each time in the loop n
total times. This gives a runtime of .
This function creates two recursive branches of half the size per call, with each node taking linear work. As such, each level has total work, and since we halve the input each time, there are total levels, for a runtime of .
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: .