ProgrammingVery hardProduct company OA · code-tracing level

What will be the output of the following pseudocode?

What will be the output of the following pseudocode?
Integer n = 30, c = 0, j
for (each i from 1 to n)
    j = i
    while (j <= n)
        c = c + 1
        j = j + i
    end while
end for
Print c
  1. A. 120
  2. B. 111
  3. C. 465
  4. D. 96

Correct answer: B. 111

For each i the inner loop visits i, 2i, 3i, … ≤ 30, i.e. ⌊30/i⌋ times. So c = Σ ⌊30/i⌋, which also equals the total number of divisors of the numbers 1…30. Adding: 30 + 15 + 10 + 7 + 6 + 5 + 4 + 3 + 3 + 3 + 2×5 (i = 11…15) + 1×15 (i = 16…30) = 111. 465 = 1 + … + 30 treats the inner loop as running 31 − i times.

More Pseudocode and Code Tracing questions

Exams that ask this topic