ProgrammingHardTCS Digital · Infosys SP

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 (i = 1; i * i <= n; i = i + 1)
    for (j = 1; j <= n; j = j * 2)
        count = count + 1
    end for
end for
  1. A. O(n log n)
  2. B. O(n^(1/2) log n)
  3. C. O(n^(1/2))
  4. D. O(n)

Correct answer: B. O(n^(1/2) log n)

The outer loop stops when i² > n, so it runs about √n times; the inner loop doubles j up to n, about log₂ n times. Total O(√n · log n), written O(n^(1/2) log n).

More Pseudocode and Code Tracing questions

Exams that ask this topic