Data Structures & AlgorithmsVery hardProduct placement · Amazon/Microsoft

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

What does this loop-counting code print? (Python)
n, c = 12, 0
for i in range(1, n + 1):
    j = 1
    while j <= n:
        c += 1
        j += i
print(c)
  1. A. 40
  2. B. 41
  3. C. 144
  4. D. 43

Correct answer: B. 41

For each i the inner loop runs ⌈n/i⌉ times, so the total is the harmonic-like sum Σ⌈n/i⌉ = Θ(n log n). Exact count: 41.

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

Exams that ask this topic