4
m=1;
for(i=1;i<=n;i++){
    m=m*2;
    for(j=1;j<=m;j++){
        do something that is O(1)
    }
}

What will be time complexity of the above code ?? Please tell me how to solve these types of problem.

Peter Coulton
  • 54,789
  • 12
  • 54
  • 72

3 Answers3

5

I prefer to look at these problems from the inside out. Removing the m, we have:

for(i=1;i<=n;i++){
    for(j=1;j<=2^i;j++){
        do something that is O(1)
    }
}

Or:

for(i=1;i<=n;i++){
    O(2^i)
}

So overall: sum_1^n O(2^i)=O(2^(n+1))=O(2^n).

Teepeemm
  • 4,331
  • 5
  • 35
  • 58
4

Inner loop will iterate 1 time, then 2 times, then ..., then 2^n times. So we have 1 + 2 + 4 + ... + 2^n = 2^(n + 1) - 1 = O(2^n) iterations of inner loop.

One iteration of inner loop has constant complexity, so summed_inner_loop_complexity = O(2^n).

Whole complexity is O(2^n).

Ari
  • 3,101
  • 2
  • 27
  • 49
0

Formally and methodically, you can use Sigma notation:

enter image description here