...

/

Solution: Nested Loop With Multiplication (Pro)

Solution: Nested Loop With Multiplication (Pro)

This review provides a detailed analysis of the different ways to solve the nested loop with multiplication challenge.

We'll cover the following...

Solution #

Press + to interact
n = 10 # can be anything
sum = 0
pie = 3.14
j = 1
for var in range(n):
while j < var:
sum += 1
j *= 2
print(sum)

The outer loop in the main function has nn iterations as it iterates on the list generated from range(n). If the condition j < var is true, the inner loop is entered. However, immediately, j is doubled. Note that j is not reset to 11 in the code. The inner while loop will run at most once for each iteration of the outer loop. Therefore, lines 6, 7 and 8 run O(n)O(n) times each. Since we are interested in an upper bound on the worst case running time, let’s assume these statements run exactly ...