Consider the following program written in pseudo-code. Assume that x and y are…
2018
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 _____.
Attempted by 152 students.
Show answer & explanation
Correct answer: 10230
Answer: 10230
Key idea: The function repeatedly divides x by 2 and prints until x becomes 1, then decreases y by 1 and resets x to 1024. Count how many prints occur per y-step and how many y-steps happen.
One cycle for a given y value: starting from x = 1024, the code prints each time x != 1 and replaces x with x/2 until x reaches 1.
Since 1024 = 2^10, dividing by 2 repeatedly produces 10 prints before x becomes 1.
The outer loop runs for y from 1024 down to 2 (stops when y == 1), so there are 1023 such cycles.
Total prints = 10 prints per cycle × 1023 cycles = 10230.
A video solution is available for this question — log in and enroll to watch it.