Data Structures & AlgorithmsVery hardProduct Company SDE · CP practice

Problem: How many ordered pairs (x, y) with 1 <= x < y <= 50 have x y a perfect square? Run the code.

Problem: How many ordered pairs (x, y) with 1 <= x < y <= 50 have x * y a perfect square? Run the code.
print(sum(1 for x in range(1, 51) for y in range(x + 1, 51) if int(round((x * y) ** 0.5)) ** 2 == x * y))
What is printed?
  1. A. 44
  2. B. 94
  3. C. 88
  4. D. 21

Correct answer: A. 44

x·y is a square exactly when x and y have the same squarefree part; there are 44 such pairs with x < y. Allowing x = y adds 50 for 94, ordered pairs give 88, and 21 counts only pairs of perfect squares.

More Coding Interview Problems questions

Exams that ask this topic