Exercises - Lecture 4

4A

The Fibonacci sequence starts with 0 and 1. After that, the \(n\)th fibonacci number, denoted \(f(n)\), is the sum of the prior two (\(f(n-2) + f(n-1)\)). Here’s a table with the first few values in the sequence:

\(n\) 0 1 2 3 4 5 6 7 8
f(\(n\)) 0 1 1 2 3 5 8 13 21

Here’s some pseudocode for a method that calculates the \(n\)th fibonacci number:

fib(n):
  if n <= 1:
    return n;
  return fib(n-1) + fib(n-2)
  1. If I call fib(3), how many times is fib called in total (including the call to fib(3))?
  2. What value does it return?
  3. If I call fib(4), how many times is fib called in total?
  4. Excluding the time it takes to make any recursive calls, what is the asymptotic runtime of each call to fib?

4B

  1. Find the two bugs in the following pseudocode. Hint: refer back to the four-step procedure for understanding recursive methods.

    duplicate(String s):
      if s.length() == 0:
         return s
    
      return s[0] + s[0] + duplicate(s)
  2. You asked to write a recursive method with the following specification:

    /** Sum the digits of n. Precondition: n >= 0. */

    Devise a recursive definition of the solution to this problem for all \(n > 0\). Hint: consider using mod and integer division.

  3. Write a line of code to replace the TODO comment in the method below to implement your recursive definition and correctly complete the method.

    /** Sum the digits of n. Precondition: n >= 0. */
    public static int sumDigits(int n) {
      if (n == 0) {
        return 0;
      }
      // TODO recursive case
    }

4C

  1. T/F Selection sort is an incremental algorithm.
  2. Because it splits the array in half at each step, we can describe binary search as a divide-and-conquer algorithm. Describe the operations performed in a single iteration of binary search in terms of divide, conquer, and combine phases. Keep in mind that some steps may be trivial (i.e., nothing needs to be done).