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.
- A. 85 and 19
- B. 85 and 7
- C. 80 and 19
- 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
- For S → A B; A → a A | ε; B → b B | ε (augmented), in how many states of the LR(0) automaton is there a conflict, and is the grammar SLR(1)?
- With the Sethi–Ullman labelling (a left leaf is 1, a right leaf is 0 because it can be a memory operand; an interior node is max(l1, l2)…
- For S → S ( S ) | ε (augmented with S′ → S), how many states do the LR(0) and canonical LR(1) automata have?
- Consider G: S → A | x b; A → a A b | B; B → x. Which statements are true? I. G is LL(1). II. G is LR(0). III. G is SLR(1). IV. G is LALR(1).
- In the code 1: a = 4; 2: b = n 2; 3: i = 0; 4: L1: t1 = a b; 5: t2 = t1 + 8; 6: t3 = i a; 7: t4 = t2 + t3; 8: c = t1 - 3; 9: t5 = c + t2…
- For 1: a = 0; 2: if p > 0 goto L2; 3: L1: a = a + 1; 4: if a < m goto L1; 5: goto L3; 6: L2: b = 1; 7: if q > 0 goto L1; 8: L3: return a…