Chapter 2: Introduction to Algorithm Design
Question 1
Find the time complexity of the following Python snippets:
-
i=1 while(i<n): i*=2 print("data") -
i =n while(i>0): print("complexity") i/ = 2 -
for i in range(1,n): j = i while(j<n): j*=2 -
i=1 while(i<n): print("python") i = i**2
Solution
- The complexity will be
O(log(n)).As we are multiplying the integer
iby2in each step there will be exactlylog(n)steps. (1,2,4, …… tilln).
- The complexity will be
O(log(n)).As we are dividing the integer
iby2in each step there will be exactlylog(n)steps. (n,n/2,n/4, …… till1).
- The outer loop will run
ntimes for eachiin the outer loop, while the innerwhileloop will runlog(i)times because we are multiplying...