[Math] Time Complexity of the code snippet

algorithmscomputational complexity

enter image description here

I know the outer while loop runs log(n) times. In the 'for' loop i am having problem. I tried with putting different values of 'n' and then seeing how many times 'for' loop runs , but im not getting a definite answer. For Eg. with n=100 , it runs 13 times, which is neither log(n) nor sqrt(n).

Best Answer

You can deduce an expression for $j$ at each iteration from its recursive formula.

To do that, notice that at the $l$-th iteration you just add $l$ in the previous value of $j$. Let $j_l$ be the value of $j$ in the the $l$-th iteration.

Then \begin{align} j_l&=j_{l-1} + l\\ j_1 &=1 \end{align}

It is clear now that \begin{equation} j_l = \sum_{i=1}^l i = \frac{l(l+1)}{2} \end{equation} where we used this to calculate the sum.

Now find the value of $l$ at which the inner loop will finish \begin{align} j_l > n\\ \frac{l(l+1)}{2} > n \end{align} Finally, we will overestimate $l$ to simplify the procedure. Notice that this overestimation makes no difference assymptotically.

\begin{align} l^2 &> 2n\\ l &> \sqrt{2n} \end{align}

So the overall complexity of this code is $\mathcal{O}(\sqrt{n}\log n)$.