i=100
while i>=1:
i=i//2
print(i)
What is the time complexity in upper bound for the following code?
i=100
while i>=1:
i=i//2
print(i)
What is the time complexity in upper bound for the following code?
If i = 100
, i is a constant and hence the time complexity is O(1)
.
If i is a variable that changes based on the input, then the time complexity is O(log i)
as you keep dividing i by 2.
print(i)
is executed log i
times, hence it does not change the final time complexity.
Considering that i
can change or vary this is a O(log n)
logarithmic complexity. (Otherwise, it would be constant time)
The number of loops is logarithmically proportional to the size of i
.
See how it scales:
i size -> # of loops
10 -> 4
100 -> 7
1000 -> 10
10000 -> 14
100000 -> 17
For reference see how different complexities scale in time:
(extracted from https://medium.com/better-programming/a-gentle-explanation-of-logarithmic-time-complexity-79842728a702) :