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 q=10q = 10.
Let F(x,y)F(x, y) denote foo(x, y, 10). Note that F(x,y)F(x, y) is symmetric with respect to xx and yy.

Base cases and transitions:

  • If both x≤0x \le 0 and y≤0y \le 0: returns q=10q = 10.
  • If x≤0x \le 0 and y>0y > 0: returns F(x,y−10)F(x, y - 10).
  • If x>0x > 0 and y≤0y \le 0: returns F(x−10,y)F(x - 10, y).
  • If both x>0x > 0 and y>0y > 0: returns F(x,y−10)+F(x−10,y)F(x, y - 10) + F(x - 10, y).

Compute subproblems bottom-up:

  1. For negative coordinates:
    F(−5,−5)=10F(-5, -5) = 10
    F(5,−5)=F(5−10,−5)=F(−5,−5)=10F(5, -5) = F(5 - 10, -5) = F(-5, -5) = 10
    F(15,−5)=F(15−10,−5)=F(5,−5)=10F(15, -5) = F(15 - 10, -5) = F(5, -5) = 10
    By symmetry, F(−5,5)=10F(-5, 5) = 10 and F(−5,15)=10F(-5, 15) = 10.
  1. For (5,5)(5, 5):
    F(5,5)=F(5,−5)+F(−5,5)=10+10=20F(5, 5) = F(5, -5) + F(-5, 5) = 10 + 10 = 20
  1. For (15,5)(15, 5):
    F(15,5)=F(15,−5)+F(5,5)=10+20=30F(15, 5) = F(15, -5) + F(5, 5) = 10 + 20 = 30
    By symmetry, F(5,15)=30F(5, 15) = 30.
  1. For (15,15)(15, 15):
    F(15,15)=F(15,5)+F(5,15)=30+30=60F(15, 15) = F(15, 5) + F(5, 15) = 30 + 30 = 60
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.