ProgrammingHardTCS NQT · Accenture pattern

What will be the output of the following pseudocode (counting pairs (i,j) with i<=j<=n whose product is divisible by n)?

What will be the output of the following pseudocode (counting pairs (i,j) with i<=j<=n whose product is divisible by n)?
Integer n = 12, c = 0
for (each i from 1 to n)
    for (each j from i to n)
        if ((i * j) mod n == 0)
            c = c + 1
        end if
    end for
end for
Print c
  1. A. 18
  2. B. 21
  3. C. 24
  4. D. 15

Correct answer: B. 21

Checking every pair i<=j in 1..12 for whether i*j is a multiple of 12 (e.g. i=3,j=4 gives 12; i=6,j=any even j works since 6*even is divisible by 12 when the other factor supplies the remaining factor of 2, etc.) gives a total count of 21 qualifying pairs.

More Pseudocode and Code Tracing questions

Exams that ask this topic