Skip to content
Official PYQ · 2018

GATE CS 2018 Q45 — Asymptotic Worst Case Time and Space Complexity

Explain with AI

Consider the following program written in pseudo-code. Assume that xx and yy are integers.

Count (x, y) {
    if (y !=1 ) {
        if (x !=1) {
            print("*");
            Count (x/2, y);
        }
        else {
            y=y-1;
            Count (1024, y);
        }
    }
}

The number of times that the printprint statement is executed by the call Count(1024,1024)Count(1024, 1024) is _____

View worked solution

Answer: 10230

To find the number of times the print statement is executed, let us analyze the recursion behavior of Count(x, y) starting with Count(1024, 1024).

For any fixed value of y≠1y \neq 1:

  • The function checks if x≠1x \neq 1. If true, it prints "*" and recursively calls Count(x/2, y).
  • Starting with x=1024x = 1024, the sequence of xx values that trigger a print is:
    1024→512→256→128→64→32→16→8→4→21024 \to 512 \to 256 \to 128 \to 64 \to 32 \to 16 \to 8 \to 4 \to 2
    This sequence has exactly log⁡2(1024)=10\log_2(1024) = 10 steps. Thus, 10 asterisks are printed.
  • When xx reaches 11, the else block is executed: yy is decremented by 11, and the function is called again as Count(1024, y - 1).

This process repeats for each value of yy starting from 10241024 down to 22. When y=1y = 1, the outer condition y != 1 becomes false, and the recursion terminates.

The number of active values of yy is:

1024,1023,…,2  ⟹  1023 values1024, 1023, \dots, 2 \implies 1023 \text{ values}

Since exactly 10 prints occur for each of these 1023 values of yy, the total number of times the print statement is executed is:

1023×10=102301023 \times 10 = 10230

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

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