GATE Computer ScienceVery hardGATE CS (PYQ pattern)

int cnt = 0; int f(int n) { cnt++; if (n <= 1) return 1; if (n == 2) return f(1) + 1; return f(n - 1) + f(n - 2) + f(n - 3); } After f(6) returns, what are the return value and cnt?

  1. A. 24 and 30
  2. B. 24 and 32
  3. C. 21 and 32
  4. D. 27 and 34

Correct answer: B. 24 and 32

Let T(n) be the value and C(n) the number of calls: T(0) = T(1) = 1, T(2) = 2, then T(n) = T(n-1) + T(n-2) + T(n-3), giving T(6) = 24; C(n) = 1 + C(n-1) + C(n-2) + C(n-3) gives 32.

More Programming and Data Structures (GATE) questions

Exams that ask this topic