I have one algorithm for which I have to find time complexity of number of time x=x+1 is executed:
j=n;
while(j>=1){
for i=1 to j
x =x+1
j=j/2
}
What I am doing is : while loop will run for logN times and so as for loop.
That's why T(n) = (logN) * (logN)
Am I correct?
On the first iteration of the
whileloop, notice that $j$ is still equal to $n$, and therefore theforloop will execute $n$ times. That is, we already have executedx=x+1$n$ times. For large $n$, we find that $n > (\log n)^2,$ so unfortunately right away we know the time complexity cannot be $(\log n)\cdot(\log n).$Sometimes it's better to just count the innermost loop. In this case the first time the
forloop runs, it iterates $n$ times. The next time theforloop starts, it iterates $n/2$ times (rounded down), the time after that iterates $n/4$ times (rounded down), and so forth until the last time through, when it iterates just once (because $j=1$).So to find the number of times we execute
x=x+1altogether, just add up the iterations for each time theforloop starts. These are at most:$$n + \frac n2 + \frac n4 + \frac n8 + \ldots + 1.$$
The exact answer will be a little less when $n$ is not a power of $2,$ but not too much less. It is easy to add up this total and to find its asymptotic form.