考虑以下 C 代码段:
int j, n;
j = 1;
while (j <= n)
j = j*2;
对于任何 n > 0,在循环执行中进行的比较次数为:
在所有选项中,对数基数为 2。
(A) CEIL(logn) + 2
(B) n
(C) CEIL(logn)
(D)楼层(logn) + 2答案: (D)
解释:
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
这个问题的测验