GATE Computer ScienceHardGATE CS (PYQ pattern)

int f(int n) { if (n <= 2) return 1; return f(n − 1) + f(n − 2) + f(n − 3); } How many calls to f (including the first) does f(8) make as written, and how many if f is memoised (a call whose result is already cached still counts as a call but returns at once, and n ≤ 2 is a base case that is also cached)? The maximum stack depth is the same in both cases.

  1. A. 85 and 19
  2. B. 85 and 7
  3. C. 80 and 19
  4. D. 85 and 22

Correct answer: A. 85 and 19

Plain: C(n) = 1 for n ≤ 2 and 1 + C(n−1) + C(n−2) + C(n−3) otherwise: C(3) = 4, C(4) = 7, C(5) = 13, C(6) = 25, C(7) = 46, C(8) = 85. Memoised: each of f(3)…f(8) runs its body once, making 3 calls, and everything else is a cache hit: 6 × 3 + 1 = 19. The depth is 7 in both (f(8), f(7), …, f(2)).

More Compiler Design questions

Exams that ask this topic