Solution: Nested Loop with Multiplication (Advanced)
Explore how to evaluate time complexity for a nested loop where the inner loop's index doubles each iteration. Understand the derivation of the O(n log n) time complexity using properties of logarithms and factorials. This lesson helps you apply complexity measures to algorithm analysis in Python.
We'll cover the following...
Solution #
In the main function, the outer loop is as it iterates over n. The inner while loop iterates over i which is always less than n and j is doubled each time, therefore we can say that it is . Thus, the total time complexity of the program given above becomes:
Here’s another way to arrive at the same result. Let’s look at the inner loop once again.
The inner loop depends upon j which is less than i and is multiplied by 2 in each iteration. This means that the complexity of the inner loop is . But, the value of i at each iteration, of the outer loop, is different. The total complexity of the inner loop in terms of n can be calculated as such:
...