Question
Consider the following ANSI C program.
#include <stdio.h>
int foo(int x, int y, int q)
{
if ((x <= 0) && (y <= 0))
return q;
if (x <= 0)
return foo(x, y - q, q);
if (y <= 0)
return foo(x - q, y, q);
return foo(x, y - q, q) + foo(x - q, y, q);
}
int main()
{
int r = foo(15, 15, 10);
printf("%d", r);
return 0;
}
The output of the program upon execution is ______.
Official answer and solution
- Official answer
- 60
- From
- Official GATE 2021 answer key
Solution
Trace the recursive calls of foo(15, 15, 10) using dynamic programming/memoization of subproblem values.
The function is called with foo(15, 15, 10), where .
Let denote foo(x, y, 10). Note that is symmetric with respect to and .
Base cases and transitions:
- If both and : returns .
- If and : returns .
- If and : returns .
- If both and : returns .
Compute subproblems bottom-up:
- For negative coordinates:
By symmetry, and .
- For :
- For :By symmetry, .
- For :
Final answer
60
The answer is the one in the official GATE answer key. The solution is this site's own explanation.
Source
- Paper
- GATE 2021 Computer Science and Information Technology - Session 2 (CS2)
- Question
- 59 of 65, printed as CS Q.49
- Section
- Computer Science and Information Technology
Report an error in this question
GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.