GATE Computer ScienceVery hardGATE CS (PYQ pattern)

int f(int n); int g(int n) { return n <= 0 ? 1 : f(n - 1) + g(n - 2); } int f(int n) { return n <= 0 ? 0 : g(n - 1) + n; } What does f(6) return, and how many calls to f and g in total (including the first) does it make?

  1. A. 18, 19 calls
  2. B. 18, 11 calls
  3. C. 19, 19 calls
  4. D. 17, 18 calls

Correct answer: A. 18, 19 calls

Tabulate both with f(n) = 0 and g(n) = 1 for n <= 0: f(n) = g(n-1) + n and g(n) = f(n-1) + g(n-2). f(1) = 2, g(1) = 1; f(2) = 3, g(2) = 3; f(3) = 6, g(3) = 4; f(4) = 8, g(4) = 9; f(5) = 14, g(5) = 12; f(6) = 18, g(6) = 23. Call counts follow cf(n) = 1 + cg(n-1) and cg(n) = 1 + cf(n-1) + cg(n-2) (1 for n <= 0), giving 19 calls for f(6).

More Programming and Data Structures (GATE) questions

Exams that ask this topic