Back

Solution: 2019 Fall Midterm - 14

Author: Michiel Smid

Question

Consider the following recursive algorithm $\ElisaDrinksCider$, which takes as input an integer $n \geq 1$, which is a power of 2:

$\ElisaDrinksCider(n):$
$\quad \mathbf{if}\ n = 1\ \mathbf{then}$
$\quad \quad \text{then order Fibonachos}$
$\quad \mathbf{else}$
$\quad \quad \ElisaDrinksCider\left(n \middle/ 2 \right)$
$\quad \quad \mathrm{drink}\ n\ \text{bottles of cider}$
$\quad \quad \ElisaDrinksCider\left(n \middle/ 2 \right)$

For $n$ a power of 2, let $C(n)$ be the total number of bottles of cider that you drink when running algorithm $\ElisaDrinksCider(n)$. Which of the following is true for any $n \geq 1$ that is a power of 2?
(n.b., $\log$ denotes the base-2 logarithm)
(a)
$C(n) = n \log n - 1$
(b)
$C(n) = 2n \log n$
(c)
$C(n) = n \log n + 1$
(d)
$C(n) = n \log n$

Solution

  1. Determine the first couple of values of $C(n)$

    $C(1) = 0$

    $C(2) = 2 + C(1) + C(1) = 2 + 0 + 0 = 2$

    $C(4) = 4 + C(2) + C(2) = 4 + 2 + 2 = 8$

    $C(8) = 8 + C(4) + C(4) = 8 + 8 + 8 = 24$

  2. Check which formula it’s true for

  • $C(n) = n \log n - 1$
    C(8) = 8 \log 8 - 1 = 8 \cdot 3 - 1 = 24 - 1 = 23
  • $C(n) = 2n \log n$
    C(8) = 2 \cdot 8 \log 8 = 16 \cdot 3 = 48
  • $C(n) = n \log n + 1$
    C(8) = 8 \log 8 + 1 = 8 \cdot 3 + 1 = 24 + 1 = 25
  • $C(n) = n \log n$
    C(8) = 8 \log 8 = 8 \cdot 3 = 24
  1. Profit

    Since the last one is the only one that is correct, we have that $C(n) = n \log n$