ProgrammingVery hardGoldman Sachs OA · Amazon OA

What is the time complexity of the following pseudocode, as a function of n?

What is the time complexity of the following pseudocode, as a function of n?
for (each i from 1 to n)
    for (each j from 1 to i * i)
        if (j mod i == 0)
            for (each k from 1 to j)
                count = count + 1
            end for
        end if
    end for
end for
  1. A. O(n⁴)
  2. B. O(n⁵)
  3. C. O(n³)
  4. D. O(n² log n)

Correct answer: A. O(n⁴)

The k-loop runs only when j is a multiple of i: j = i, 2i, …, i·i, costing i + 2i + … + i·i ≈ i³/2. Summing over i gives about n⁴/8; the j-loop's own i² checks add only O(n³). So O(n⁴), not the O(n⁵) the three nested loops suggest.

More Pseudocode and Code Tracing questions

Exams that ask this topic