Consider the following segment of C++ code. int j, n;
Consider the following segment of C++ code.
int j, n;
for(j = 1; j <= n;)
j = j*2;
What is the number of comparisons made in the execution of the loop for any n > 0?
Show answerHide answer
Correct answer: (D) log₂n + 1
Explanation
j takes the values 1, 2, 4, ... while j ≤ n, so the loop condition is checked about log₂n + 1 times, which is the keyed answer. Strictly, the final failing test makes it ⌊log₂n⌋ + 2.