Lecture 03: Practice Problems

1. Loop Analysis

count = 0;
for (int i = 0; i < n; i++)
   for (int j = 0; j < i; j++)
      count++;
        

What is the exact value of count in terms of n?

Show Answer

Answer: n(n-1)/2.

It sums 0 + 1 + 2 + ... + (n-1). This is the arithmetic series up to n-1.

Approx = n^2 / 2 = O(n^2).

2. Triple Loop

for (i=0; i
        

Complexity?

Show Answer

Answer: O(n^3).

3. What's the Precondition?

You have a function computeSquareRoot(double x).

Show Answer

Precondition: x >= 0.