• edited by
580 views
2 2 votes

13) Determine the time complexity of program segment given below:
```
i=n;
while (i>0)
{
k=1;
for (j=1;j<=n; j+=k)<br /> k++;
i = i/2;
}
```

  1. $\mathrm{O}\left(\mathrm{n}^{2}\right)$
  2. $\mathrm{O}(\mathrm{n} \cdot \operatorname{logn})$
  3. $O\left(\log ^{2} n\right)$
  4. $\mathrm{O}(\log n \sqrt{n})$

1 Answer

Best answer
3 3 votes

We have to count the maximum no. of times any instruction is executed- which would be inside the inner most loop. So, we can count the no. of times for loop and while loop execute independently and their product will be our answer. 

for loop:

$ j = 1, 1+2, 1+2+3, ... , 1+2+ ... + l$, where $l$ is the no. of times the loop iterates (for one iteration of while loop). 

From loop exit condition,

$1+2+\dots + l > n$

$\frac{l. (l+1)}{2} > n$

So, $l = \Theta (\sqrt n)$. 

(See, I used $\Theta$ meaning $l$ and $\sqrt n$ have the same order of growth. If LHS has lower or same growth rate we should use big-O and not big-Theta)

while loop

Now, we have to solve the outer while loop. Here $i$ goes like $n, n/2, n/4, \dots n/2^m$, where $m$ is the no. of times the loop iterates. As per the loop exit condition, we can get

$2^m > n$ (which gives an integer value 0)

$\implies m > \log n$

$m = \Theta (\log n)$. 

So, time complexity of code is $m . l = \Theta (\log n \sqrt n)$. 

$\Theta$ means both $O$ and $\Omega$ are also true. Hence option d is correct. 

As per definition of big O, even options A and B are correct though D is the best pick. 

• selected by
Position:
Show:

Related questions

2 2 votes
1 1 answer
1.5k
1.5k views
Narasimhan asked Nov 7, 2017
1,454 views
// func() is any constant root functionfor (int i = n; i 0; i = func(i)){ // some O(1) expressions or statements}"In this case, i takes values n, n1/k, (n1/k)1/k = n1/...
1 1 vote
1 answers 1 answer
1.6k
1.6k views
Payal Rastogi asked Nov 14, 2015
1,577 views
38. Consider the piece of code given below void fun(int n)\{if $(\mathrm{n}==1)$ thencall A( );else\{ fun(n/2);fun(n/2);call B(n);\}\}If A() is $\mathrm{O}(1)$ and $\math...
1 1 vote
1 answers 1 answer
787
787 views
worst_engineer asked Oct 7, 2015
787 views
In my opinion , Option a is correct . Am i right ?Consider the following three claims:(1) $(\mathrm{n}+\mathrm{k})^{\mathrm{m}}=\mathrm{O}\left(\mathrm{n}^{3 \pi}\right)$...
0 0 votes
2 2 answers
3.7k
3.7k views
Gate Fever asked Sep 27, 2018
3,698 views
Consider the following piece of code for(i=1; i0; j=2){for(k=j; k