Search⌘ K
AI Features

Solution: Big O of Nested Loop with Multiplication

Explore how to evaluate the time complexity of nested loops that feature multiplicative growth. This lesson helps you understand how to break down the loops' behavior, sum geometric series, and correctly determine the Big O notation as linear time O(n). You will gain the skills to analyze runtime complexity in scenarios where inner loops grow exponentially relative to the iterations of the outer loop.

We'll cover the following...

Solution #

Python 3.5
n = 10 # Can be anything
sum = 0
pie = 3.14
var = 1
while var < n:
print(pie)
for j in range(var):
sum += 1
var *= 2
print(sum)

Explanation

The answer is O(n)O(n). Have a look at the slides below for an in-depth explanation of the answer.

In the slides below, rtc abbreviates the running time complexity.

Time Complexity

The above slides give a detailed, step-by-step analysis of the code. Here, we provide a more summarized version.

The outer loop here runs log(n)log(n) times. In the first iteration of the outer loop, the body of the inner loop runs once. In the second iteration, it runs twice, and so on. The number of executions of the body of the inner loop increases in powers of 2. So, if kk is the number of iterations of the outer loop, the body of the inner loop runs a total of 1+2+4+8++2k1+2+4+8+\cdots+2^k times. This geometric series sums to 2k+112^{k+1}-1. The inner loop condition requires that in the last time the inner loop runs, it runs at most nn times. This requires 2 ...