• edited by
30,892 views
45 45 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)$

12 Answers

Best answer
81 81 votes
Answer will be $\Theta(n)$

$j = n/2+n/4+n/8+\ldots +1$

$\quad = n \left[1/2^1 + 1/2^2 + 1/2^3 +\ldots + 1/2^{\lg n}\right] $

(Sum of first $n$ terms of GP is $\left[a . \frac{1-r^n}{1-r}\right],$ where $a$ is the first term, $r$ is the common ratio $< 1,$ and $n$ is the number of terms)

$\quad = n \left[1/2 \frac{1 - (1/2)^{\lg n}}{1-1/2} \right]$

$\quad = n \left[\frac{n-1}{n}\right]$

$\quad = n-1 = \Theta(n)$
• edited by
22 22 votes

val(j)=\Theta( n)

is correct because i gets reduced log2(n) time  say for eg

  i=16 than 

  i=8   j=8

  i=4   j=12

   i=2   j=14

   i=1   j=15

   i=0 

hence val(j)=\Theta( n)

11 11 votes
The variable j is initially 0 and value of j is sum of values of i. i is initialized as n and is reduced to half in each iteration. j = n/2 + n/4 + n/8 + .. + 1 = Θ(n) Note the semicolon after the for loop, so there is nothing in the body.
1 1 vote
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)$
Answer:
Position:
Show:

Related questions

95 95 votes
14 answers 14 answers
50.1k
50.1k views
Rucha Shelke asked Sep 26, 2014
50,135 views
Given two arrays of numbers $a_{1},...,a_{n}$ and $b_{1},...,b_{n}$ where each number is $0$ or $1$, the fastest algorithm to find the largest span $(i, j)$ such that $ a...
57 57 votes
3 answers 3 answers
17.1k
17.1k views
Rucha Shelke asked Sep 26, 2014
17,128 views
Consider the following C-function in which $a[n]$ and $b[m]$ are two sorted integer arrays and $c[n+m]$ be another integer array,void xyz(int a[], int b [], int c []){ in...
25 25 votes
4 answers 4 answers
8.8k
8.8k views
Rucha Shelke asked Sep 26, 2014
8,802 views
A set $X$ can be represented by an array $x[n]$ as follows: $x\left [ i \right ]=\begin {cases} 1 & \text{if } i \in X \\ 0 & \text{otherwise} \end{cases}$Consider the ...
155 155 votes
18 answers 18 answers
37.6k
37.6k views
Rucha Shelke asked Sep 26, 2014
37,556 views
Let $T$ be a depth first search tree in an undirected graph $G$. Vertices $u$ and $ν$ are leaves of this tree $T$. The degrees of both $u$ and $ν$ in $G$ are at least $2$...