GATE | GATE-CS-2007 | Question 85
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
Please Login to comment...