ProgrammingVery hardProduct company OA · code-tracing level

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?
i = 2
while (i <= n)
    i = i * i
end while
  1. A. O(log n)
  2. B. O(√n)
  3. C. O(log log n)
  4. D. O(1)

Correct answer: C. O(log log n)

i goes 2, 4, 16, 256, 65536, …: after k steps i = 2^(2^k). The loop stops once 2^(2^k) > n, i.e. 2^k > log₂ n, k > log₂ log₂ n. So it runs O(log log n) times. O(log n) is the answer for i = i * 2, where the exponent grows by 1 each step instead of doubling.

More Pseudocode and Code Tracing questions

Exams that ask this topic