Question

Consider the following program written in pseudo-code. Assume that x and y 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 print statement is executed by the call Count(1024,1024) is _____.

Official answer and solution
Official answer
10230
From
Official GATE 2018 answer key

Solution

Analyze loop iterations and recursive invocations to count print executions.

Trace the recursive execution of Count(x, y) when invoked with Count(1024, 1024):

  • While y≠1y \neq 1, for a fixed yy, x starts at 1024.
  • In each step where x≠1x \neq 1, it executes print("*") and recurses with Count(x/2, y).
  • The values of xx for which x≠1x \neq 1 are: 1024,512,256,128,64,32,16,8,4,21024, 512, 256, 128, 64, 32, 16, 8, 4, 2 (exactly 10 values). Each prints one *.
  • When x=1x = 1, the else branch executes: yy is decremented by 1 (y=y−1y = y - 1), and it calls Count(1024, y).

This cycle repeats for every value of yy from 1024 down to 2:

y=1024,1023,…,2y = 1024, 1023, \dots, 2

The number of such values of yy is 1024−2+1=10231024 - 2 + 1 = 1023.

When y=1y = 1, the outer condition if (y != 1) is false, and the function terminates without printing.

Total print executions:

Total=1023×10=10230\text{Total} = 1023 \times 10 = 10230
Final answer

10230

The answer is the one in the official GATE answer key. The solution is this site's own explanation.

Source

Paper
GATE 2018 Computer Science and Information Technology (CS)
Question
55 of 65, printed as CS Q.45
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.