Data Structures & AlgorithmsVery hardAmazon/Microsoft SDE pattern

What does this loop-counting code print? (Python)

What does this loop-counting code print? (Python)
n, c = 22, 0
i = 1
while i < n:
    j = i
    while j < n:
        c += 1
        j *= 2
    i += 1
print(c)
  1. A. 39
  2. B. 38
  3. C. 49
  4. D. 41

Correct answer: A. 39

For each i from 1 to n − 1, the inner loop doubles j from i until it reaches n, running about log₂(n/i) + 1 times; summing this over all i gives Θ(n), and the exact count for n = 22 is 39.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic