edited by
37,152 views
64 votes
64 votes

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:

  1. $\lceil \log_2n \rceil +1$

  2. $n$

  3. $\lceil \log_2n \rceil$

  4. $\lfloor \log_2n \rfloor +1$

edited by

15 Answers

1 votes
1 votes
No one is right option .

n=2 comparision done 3

n=4 comparision done 4

n=5 comparision done 4

n=6 comparision done 4
0 votes
0 votes

For n=1, loop execution for success = 1, for failure = 1

n=2, for success = 2 for failure =1

n=3, for success = 2 for failure =1

n=4, for success = 3 for failure = 1

..

Now if you consider no. of comparison for while execution excluding failure condition answer should be D($\left \lfloor logn \right \rfloor +1$)

otherwise with failure condition answer should be ($\left \lfloor logn \right \rfloor +2$)

0 votes
0 votes

n is compared with 20, 21 , ........ 2floor(lgn) , 2floor(lgn) + 1

So 0 to floor(lgn) + 1, and the expression always evaluates to false for j =  floor(lgn) + 1,

Hence, in both the cases floor(lgn) + 2 comparisons are made

Here is an example to make things clearer:

.We need to consider two cases

1) When n = 2k   

        Take 8 . (1<=8),(2<=8),(4<=8),(8<=8),(16<=8)

        five comparisons are made.

2) When  n != 2

      Take 11.  (1<=11),(2<=11),(4<=11),(8<=11),(16<=11)

      Again five comparisons are made . 

0 votes
0 votes

Value of j is updated as: 1,2,4,8,16,...,(2^k)

Condition for which loop will be executed:

         j <= n

         2^k <= n

         k <= log n

         k = ⌊logn⌋ 

Number of times loop will be executed: (k+1) i.e (⌊logn⌋ +1)

Number of times comparisons will be made: (Number of times loop will be executed + 1) i.e. (⌊logn⌋ +2)

 

 

Answer:

Related questions

27 votes
27 votes
4 answers
9
Kathleen asked Sep 21, 2014
33,988 views
The message $11001001$ is to be transmitted using the CRC polynomial $x^3 +1$ to protect it from errors. The message that should be transmitted is:$11001001000$$110010010...
33 votes
33 votes
4 answers
11