Solution: Nested Loop with Multiplication (Pro)
Explore how nested loops with a multiplying inner loop affect the time complexity of an algorithm. Understand the step-by-step execution counts and learn to derive the Big O notation as O(n) from the given Java code example.
We'll cover the following...
We'll cover the following...
Given Code #
The outer loop has n iterations as it iterates on var from 0 to n-1. If the condition j < var is true, the inner loop is entered. However, immediately, j is doubled. Note that j is not reset to 1 in the code. The inner while loop will run at most once for each iteration of the outer loop. Therefore, lines 12 and 13 run times, each. Since we are interested in an upper bound on the worst-case running time, let’s assume these statements run exactly n times.
| Statement | Number of Executions |
|---|---|
int n = 10; |
|
int sum = 0; |
|
int j = 1; |
|
double pie = 3.14; |
|
int var=0; |
|
var<n; |
|