ProgrammingVery hardCAT · MBA placement

Count the pairs (i, j) with 1 <= i <= j <= 10 for which the product i j is a perfect square. The procedure below does this with two nested loops. What is printed?

Count the pairs (i, j) with 1 <= i <= j <= 10 for which the product i * j is a perfect square. The procedure below does this with two nested loops. What is printed?
count = 0
for i = 1 to 10
    for j = i to 10
        if i*j is a perfect square then count = count + 1
    end for
end for
Print count
  1. A. 4
  2. B. 41
  3. C. 14
  4. D. 13

Correct answer: C. 14

The diagonal pairs i = j always qualify (10 of them), and the four pairs (1,4), (1,9), (2,8) and (4,9) add to 14. Requiring i < j gives 4, counting the non-squares gives 41, and shrinking the range to 9 gives 13.

More Pseudocode and Code Tracing questions

Exams that ask this topic