• edited by
1,837 views
1 1 vote

The time complexity for following piece of code is
```
i=n;
while (i>0)
{
k=1;
for (j = 1; j< = n; j + = k)
k++;
i = i/2;
}
```

1 Answer

Best answer
2 2 votes

Outer Loop $\Rightarrow$

Now,

Inside the rectangle : j values are $\rightarrow$

$\begin{align*} j = 1,3,6,10,15,21....... n \end{align*}$

Assuming we have m terms in that series.

From above image :

  • To get the $6th$ term we add $6$ to the previous term.
  • So, to get the $mth$ term we add $m$ in the last increment step.
  • $mth$ term is = $n$

$$\begin{align*} &\Rightarrow n = 1+2+3+4+5+6+......m \\ &\Rightarrow n = \frac{m(m+1)}{2} \\ &\Rightarrow m = O(\sqrt{n}) \end{align*}$$ 

Considering inner + outer loop   $ \Rightarrow$ $O(\sqrt{n}*\log n)$

• selected by
Position:
Show:

Related questions

0 0 votes
2 2 answers
3.6k
3.6k views
Gate Fever asked Sep 27, 2018
3,631 views
Consider the following piece of code for(i=1; i0; j=2){for(k=j; k
0 0 votes
1 1 answer
1.6k
1.6k views
GateAspirant999 asked Sep 16, 2018
1,560 views
Consider the following sorting algorithmSorting (A, low, high)Iif (low == high) return;if (low $+1==$ high)Iif $(\mathrm{A}[$ low $]>\mathrm{A}[$ high $])$swap (A[low], A...
0 0 votes
3 3 answers
2.6k
2.6k views
Deepalitrapti asked Sep 12, 2018
2,647 views
14Computer Science \& ITAlgorithm, DataQ. 78 Given a sorted array of n-elements where other than one element $x$ every other element repeat two times. Then how much time ...
1 1 vote
2 answers 2 answers
2.3k
2.3k views
srestha asked Aug 17, 2018
2,314 views
What will be TC here?Ans given $O(n^{2})$ , while I am getting $O(n)$What is the time complexity of function ()?void function (int $n$ ) {int sum = 0;for (int i=0;i0;j ...