Back

Solution: 2017 Fall Final - 10

Author: Michiel Smid

Question

Consider the recursive algorithm $\IFeelLikeSinging$, which takes as input an integer $n \geq 0$:

$\mathbf{Algorithm}\ \IFeelLikeSinging(n)\mathrm{:}$
$\mathbf{if}\ n = 0\ \mathrm{or}\ n = 1$
$\mathbf{then}\ \mathrm{sing}\ {\it O\ Canada}$
$\mathbf{else}\ \mathbf{if}\ n\ \text{is odd}$
$\elsesp \mathbf{then}\ \IFeelLikeSinging(n + 1)$
$\elsesp \mathbf{else}\ \IFeelLikeSinging(\frac{n}{2});$
$\elsesp \elsesp \IFeelLikeSinging(\frac{n}{2} - 1)$
$\elsesp \mathbf{endif};$
$\mathbf{endif}$

If you run algorithm $\IFeelLikeSinging(9)$, how many times do you sing O Canada?
(a)
8
(b)
9
(c)
7
(d)
6

Solution

Let’s draw out the tree

To fit the tree on the page, IFLS = IFeelLikeSinging

image

In total, O Canada is sung 8 times.