Consider the following segment of C-code:
int j, n;
j = 1;
while (j <= n)
j = j*2;
The number of comparisons made in the execution of the loop for any n > 0 is:
Base of Log is 2 in all options.
(A) CEIL(logn) + 2
(B) n
(C) CEIL(logn)
(D) FLOOR(logn) + 2
Answer: (D)
Explanation:
We can see it by taking few examples like n = 1, n = 3, etc.
For example, for n=5 we have the following (4) comparisons:
------------------------
1 <= 5 (T)
2 <= 5 (T)
4 <= 5 (T)
8 <= 5 (F)
------------------------
FLOOR(log_2 n)+2 = FLOOR(log_2 5) + 2 = FLOOR(2.3) + 2 = 2 + 2 = 4
Quiz of this Question
Level Up Your GATE Prep!
Embark on a transformative journey towards GATE success by choosing
Data Science & AI as your second paper choice with our specialized course. If you find yourself lost in the vast landscape of the GATE syllabus, our program is the compass you need.