Time complexity for dependant nested for loop?

前端 未结 3 1977
庸人自扰
庸人自扰 2021-01-13 04:43

Can you explain me how to find time complexity for this?

sum=0;
for(k=1;k<=n;k*=2)
  for(j=1;j<=k;j++)
     sum++;

So, i know the out

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-13 05:24

    Just see how many times the inner loop runs:

    1 + 2 + 4 + 8 + 16 +...+ n
    

    Note that if n = 32, then this sum = 31 + 32. ~ 2n.
    This is because the sum of all the terms except the last term is almost equal to the last term.

    Hence the overall complexity = O(n).

    EDIT:

    The geometric series sum (http://www.mathsisfun.com/algebra/sequences-sums-geometric.html) is of the order of:

    (2^(logn) - 1)/(2-1) = n-1.
    

提交回复
热议问题