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?
- A. 18, 19 calls
- B. 18, 11 calls
- C. 19, 19 calls
- 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).
Practise more Programming and Data Structures (GATE) questionsProgramming and Data Structures (GATE): notes and key points
More Programming and Data Structures (GATE) questions
- void r(char s) { if (s[0] == 0 || s[1] == 0) { printf("%s", s); return; } printf("%c%c", s[1], s[0]); r(s + 2); printf("%c", s[0]); } What…
- int t(int n) { return n == 0 ? 0 : n % 3 + 10 t(n / 3); } What is t(97) + t(t(7))?
- int g(int a, int b) { return b == 0 ? a : g(b, a % b); } How many calls to g (including the first) does g(610, 987) make, and how many…
- int w(int n) { if (n < 0) return 0; if (n == 0) return 1; return w(n - 1) + w(n - 3) + w(n - 4); } What does w(10) return, and how many…
- int x = 0; void q(int n) { if (n > 0) { x += n; q(n - 1); printf("%d ", x); if (n > 2) q(n - 2); } } What does q(4) print?
- Integers 1, 2, 3, 4, 5 are pushed on an initially empty stack in this order; pops may be interleaved with pushes at any time. How many of…