Data Structures & AlgorithmsVery hardProduct company OA

Exact count of the innermost statement for n = 30 (j advances by i, k advances by j). What is printed?

Exact count of the innermost statement for n = 30 (j advances by i, k advances by j). What is printed?
c = 0
n = 30
for i in range(1, n + 1):
    j = 1
    while j <= n:
        k = j
        while k <= n:
            c += 1
            k += j
        j += i
print(c)
  1. A. 111
  2. B. 133
  3. C. 900
  4. D. 1118

Correct answer: D. 1118

For a fixed j the k-loop runs ⌊30/j⌋ times; the j-loop visits 1, 1 + i, 1 + 2i, …. For i = 1 that alone is Σⱼ ⌊30/j⌋ = 111 (≈ n ln n); for large i only j = 1 survives, still contributing 30. Summing over all i gives 1118. 133 is the number of (i, j) pairs – the count without the innermost loop – and 900 is n² as if every loop ran n times.

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic