i = 1;
while(i<N) {
i*=2;
}
I think the time complexity of the above code is O(N) but i'm not sure about it. Can you please let me know if you think its O(Log N) and the reason?
i = 1;
while(i<N) {
i*=2;
}
I think the time complexity of the above code is O(N) but i'm not sure about it. Can you please let me know if you think its O(Log N) and the reason?
Time complexity si proportional to number of cycles. And number of cycles is exactly equal to Log(N)/Log(2)
, where Log is any logarithm. Or just Log2(N)
, where Log2 is logarithm with base 2. It is therefore O(Log N).
example: N = 10 while loop runs 1, 2, 4, 8, 16 (5 times)
if you double N, N = 20 you would expect the time complexity to also double if it were O(N). however, that loop runs 1, 2, 4, 8, 16, 32 (6 times)
and again, N = 40, that loop runs 1, 2, 4, 8, 16, 32, 64 (7 times)
This is O(log N) since the time complexity decreases as N becomes larger.
Time Complexity of i*=2 or i/=2 will be the same and it will be log2(n).
Misread i*=2 as i+=2.
It's just O(N), more precisely it would be O(N/2).
Why would you think that this would be O(log N)?