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) ? Algorithms algorithms time-complexity + – Khyati Tuli 1.2k views answer comment Share Follow Print See all 2 Comments 2 2 Comments reply vijaycs commented Jun 3, 2016 reply Follow flag Thus sum = 1 + 2 + 4 + 8 + ..... log(n) /// while(k<n) So, T(n) = (2log(n)+1 - 1) / (2-1) = O(n). 3 3 replyShare Rachana jay commented Aug 14, 2020 reply Follow flag 1+2+2^2+2^3+2^4+.+2^k is in geometric progression solving it we get 2n-1 i.e O(n) 0 0 replyShare Please log in or register to add a comment.
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. rude answered Jun 4, 2016 • selected Jun 4, 2016 by rude rude comment Share Follow 0 reply Please log in or register to add a comment.