int a = 0, i = N;
while (i > 0) {
a += i;
i /= 2;
}
What is time complexity of this?Pls explain
While loop will run till i is greater than 0 and in each iteration i becomes half. So if i was initially N after one iteration it’ll become N/2 then N/2^2 and so on and lets say that after m iterations it becomes one and then zero. So N/2^m = 1 which can be written as,
N = 2^m
taking log on both sides m = log(m)
so complexity is O(m +1 ) = O(m) = O(logN)
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.