edited by
1,174 views
1 1 vote
What should be the time complexity of :

k=1;
while (k<=n) do      
    j=1;
    while (j<=k) do        
        sum=sum+1;
        j=j+1;
    k=k*2;

According to me:
For K=1, j= 1 time

for K=2, j=2 times

For K=4, j=4 times..

And so on...

Thus sum= 1+2+4+8....n

This is I think 2n+1-1

So should the answer be O(2n) ?

1 Answer

Best answer
6 6 votes

Let Consider $n = 2^k$

Then total work done by the inner loop is 

$T(n)$ = $2^0$ + $2^1$ + $2^2$ + $2^3$ + $2^4$ + ..................... + $2^k$

        <= $2^{(k+1)}$

        <= $2^{((logn)+1)}$

        <= $2n$

$T(n) = O(n)$. This will be the correct time complexity of the above code snippet.

selected by
Position:
Show:

Related questions

1 1 vote
3 answers 3 answers
4.5k
4.5k views
Manu Thakur asked Aug 29, 2017
4,530 views
The innermost loop will execute when j is multiple of i, and that will happen exactly i times. Please help me to find the time complexity of the below program:
0 0 votes
1 1 answer
812
812 views
usdid asked Jul 2, 2022
812 views
what is the running time of the following iterative algorithm?b) It is possible to talk about the best, average and worst running times for this algorithm. Why? pseudo co...
0 0 votes
0 0 answers
447
447 views
usdid asked Apr 16, 2022
447 views
1 question:a) Calculate the running time of the following iterative algorithm. For this purpose, write the working time of each row in the corresponding column of the tab...
0 0 votes
0 0 answers
523
523 views
usdid asked Apr 16, 2022
523 views
a) what is the iterative equation showing the running time of the algorithm whose pseudocode is given below? b) What is this repeated equation in asymptotic notation usin...