Data Structures and Algorithms

A function fib(n) for Fibonacci numbers is defined recursively as “if n is 1 or less, return n; otherwise return fib(n−1) + fib(n−2)”. When fib(5) is called, how many times is fib called, including the first call?

  1. A6
  2. B9
  3. C15
Show answer and explanation

Answer: C. 15

Let C(n) be the number of calls for fib(n). Then C(0) = C(1) = 1 and C(n) = 1 + C(n−1) + C(n−2), so C(2) = 3, C(3) = 5, C(4) = 9 and C(5) = 15. Because the same values are recomputed again and again, the count grows exponentially with n; fib(30) makes about 2.69 million calls. With memoization (a form of dynamic programming), which stores computed values in a table, only the six values fib(0) to fib(5) are computed and the calls drop to 9 (2n − 1). 6 is the number of distinct arguments, and 9 is the number of calls with memoization.

  • A. This is the number of distinct arguments fib(0) to fib(5); it does not count recomputation of the same values.
  • B. This is the number of calls with memoization, where a value already computed is returned from a table.
  • C. Correct. From C(n) = 1 + C(n−1) + C(n−2), C(5) = 15.
Practice this topic Back to topic

Related calculators

Books on Data Structures and Algorithms Ad

As an Amazon Associate I earn from qualifying purchases.

More Data Structures and Algorithms questions

  1. You pay 8 yen with coins of 1 yen, 4 yen and 6 yen. Which correctly relates the number of coins chosen by a greedy algorithm, which uses as many of the largest coin as possible first, to the minimum number of coins?
  2. A knapsack with capacity 8 is filled with items chosen from four items with (weight, value) of (2, 3), (3, 4), (4, 5) and (5, 6). There is only one of each item and items cannot be split. What is the maximum total value with a total weight of 8 or less?
  3. Which is a characteristic of the Boyer-Moore algorithm for finding a pattern in a string?
  4. A dynamic array, when an element is added while it is full, allocates a new area with twice the capacity and copies all elements into it. If 1,000 elements are added one at a time to an empty array of capacity 1, how many element copies are made in total?
  5. For a hash table with many elements kept at a load factor of about 0.5, which is the most appropriate reason that open addressing with linear probing tends to be faster than chaining (linking elements with linked lists)?