Solution: Big (O) of a Nested Loop with Addition
This review provides a detailed analysis of the time complexity of the nested loop with addition problem!
We'll cover the following...
We'll cover the following...
Given code
Solution breakdown
The first for loop on line 7 can be broken down into 3 parts:
- initialization
- comparison
- incrementation
Since the initialization (int var = 0) only happens once in the entire program, it takes one unit of time. The comparison (var < n) gets executed times and the increment runs times.
Similarly, (int j = 0) runs times , the comparison (j < n) runs (the test case runs once more than the whole loop where boundary check fails!), and the increment (j = j + 2) gets executed times for each iteration of the outer loop–which makes it run a total of ...