I compare

1
2
3
i=1
while i <=n:
    i*=2

What is the number of comparisons made in the execution of the while loop shown above?

Details and Assumptions

n 1 n\geq 1

log 2 n \left\lceil \log_2n \right\rceil log 2 n + 2 \left\lfloor \log_2n \right\rfloor +2 n n log 2 n \left\lfloor \log_2n \right\rfloor log 2 n + 2 \left\lceil \log_2n \right\rceil +2

This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try refreshing the page, (b) enabling javascript if it is disabled on your browser and, finally, (c) loading the non-javascript version of this page . We're sorry about the hassle.

1 solution

Shourya Pandey
May 15, 2016

Essentially, we keep doubling i i unless it doesn't exceed n n . The values compared in the while loop are

1 , 2 , 2 2 , . . . , 2 k , 2 k + 1 1,2,2^2,...,2^k,2^{k+1} ,

where k k is such that 2 k n < 2 k + 1 2^{k} \leq n < 2^{k+1} , or l o g 2 n 1 < k l o g 2 n log_{2}n - 1 <k \leq log_{2}n , so that k = l o g 2 n k =\lfloor log_{2}n \rfloor . In all , k + 2 = l o g 2 n + 2 k+2 = \lfloor log_{2}n \rfloor+2 comparisons were made.

0 pending reports

×

Problem Loading...

Note Loading...

Set Loading...