-4
i=100
while i>=1:
  i=i//2
  print(i)

What is the time complexity in upper bound for the following code?

Barmar
  • 741,623
  • 53
  • 500
  • 612
Neel
  • 1
  • 2
  • Welcome to Stack Overflow! [How to ask homework question](https://meta.stackoverflow.com/questions/334822/how-do-i-ask-and-answer-homework-questions) – Barmar Nov 03 '20 at 02:34
  • Please see [How to Ask a Homework Question](https://meta.stackoverflow.com/questions/334822/how-do-i-ask-and-answer-homework-questions). Simply dumping your assignment here is not acceptable. – Prune Nov 03 '20 at 02:42
  • Thank you I will keep it in mind. Thank you for the answer. – Neel Nov 03 '20 at 02:48

2 Answers2

0

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.

samub10
  • 1
  • 2
0

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) : enter image description here

Matheus Felipe
  • 2,482
  • 25
  • 24