x <--1
for i <--0 to n do
k <-- i
while k> 0 do
x <-- x*2
k <-- k-1
return x
Is it O (n)? Do while loop increase the complexity?
When i = 0
, inner loop runs 0
time
When i = 1
, inner loop runs 1
time
When i = 2
, inner loop runs 2
times
When i = 3
, inner loop runs 3
times
...
When i = n
, inner loop runs n
times
Adding it all up: 0+1+2+3+...+n = n*(n+1)/2
So the time complexity is O(n^2)