Skip to content
Official PYQ · 2021

GATE CS 2021 Set 2 Q49 — Asymptotic Worst Case Time and Space Complexity

Explain with AI

Consider the following ANSI C\text{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 _________

View worked solution

Answer: 60 : 60

We need to find the value returned by the call foo(15, 15, 10). Throughout the execution, the parameter q=10q = 10 remains constant. Let us denote the function as f(x,y)f(x, y) for simplicity.

The base cases and recursive steps are defined as follows:

  1. If x≤0x \le 0 and y≤0y \le 0, then f(x,y)=q=10f(x, y) = q = 10.
  2. If x≤0x \le 0 and y>0y > 0, then f(x,y)=f(x,y−10)f(x, y) = f(x, y-10). Since xx remains ≤0\le 0, this eventually reduces to f(x,y′)=10f(x, y') = 10 where y′≤0y' \le 0. Thus, f(x,y)=10f(x, y) = 10 for any x≤0x \le 0.
  3. Similarly, if y≤0y \le 0 and x>0x > 0, then f(x,y)=10f(x, y) = 10 for any y≤0y \le 0.
  4. If x>0x > 0 and y>0y > 0, then f(x,y)=f(x,y−10)+f(x−10,y)f(x, y) = f(x, y-10) + f(x-10, y).

Now, we compute the values bottom-up for positive arguments in steps of 1010:

  • For f(5,5)f(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
  • For f(15,5)f(15, 5) and f(5,15)f(5, 15):
    f(15,5)=f(15,−5)+f(5,5)=10+20=30f(15, 5) = f(15, -5) + f(5, 5) = 10 + 20 = 30
    f(5,15)=f(5,5)+f(−5,15)=20+10=30f(5, 15) = f(5, 5) + f(-5, 15) = 20 + 10 = 30
  • For f(15,15)f(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

Thus, the output of the program is 60.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Asymptotic Worst Case Time and Space Complexity questions