Consider the following program written in pseudo-code. Assume that and 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 statement is executed by the call 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 :
- The function checks if . If true, it prints
"*"and recursively callsCount(x/2, y). - Starting with , the sequence of values that trigger a print is:
This sequence has exactly steps. Thus, 10 asterisks are printed. - When reaches , the
elseblock is executed: is decremented by , and the function is called again asCount(1024, y - 1).
This process repeats for each value of starting from down to . When , the outer condition y != 1 becomes false, and the recursion terminates.
The number of active values of is:
Since exactly 10 prints occur for each of these 1023 values of , the total number of times the print statement is executed is:
Free practice · Your answers on this page are not saved.
