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 , for a fixed ,
xstarts at 1024. - In each step where , it executes
print("*")and recurses withCount(x/2, y). - The values of for which are: (exactly 10 values). Each prints one
*. - When , the
elsebranch executes: is decremented by 1 (), and it callsCount(1024, y).
This cycle repeats for every value of from 1024 down to 2:
The number of such values of is .
When , the outer condition if (y != 1) is false, and the function terminates without printing.
Total print executions:
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.