edited by
19,508 views
35 votes
35 votes

Consider the following C-program fragment in which $i$, $j$ and $n$ are integer variables. 

 for( i = n, j = 0; i > 0; i /= 2, j +=i );

Let $val(j)$ denote the value stored in the variable $j$ after termination of the for loop. Which one of the following is true? 

  1. $val(j)=\Theta(\log n)$
  2. $val(j)=\Theta (\sqrt{n})$
  3. $val(j)=\Theta( n)$
  4. $val(j)=\Theta (n\log n)$
edited by

10 Answers

1 votes
1 votes
C is the answer.

$\frac{n}{1}+\frac{n}{2}+\frac{n}{2^{2}}+....+\frac{n}{2^{logn}} = n(1+\frac{1}{2} +\frac{1}{2^{2}}+....+\frac{1}{2^{logn}})\Rightarrow \Theta (n)$
0 votes
0 votes
For n =4 j is getting added 3 times For n =8 j is getting added 4 times For n =16 j is getting added 5 times so we can see that the number of times j is getting added is (log n +1) so its THETA(log n)
Answer:

Related questions

90 votes
90 votes
12 answers
4