Data Structures & AlgorithmsVery hardProduct Company SDE · CP practice

Problem: How many subsets of {1, 2, ..., 6} have a product that is a perfect square? Run the code (the empty set has product 1).

Problem: How many subsets of {1, 2, ..., 6} have a product that is a perfect square? Run the code (the empty set has product 1).
import math
print(sum(1 for m in range(1 << 6) if int(round(math.prod([i + 1 for i in range(6) if m >> i & 1] or [1]) ** 0.5)) ** 2 == math.prod([i + 1 for i in range(6) if m >> i & 1] or [1])))
What is printed?
  1. A. 8
  2. B. 7
  3. C. 4
  4. D. 16

Correct answer: A. 8

Square products: {}, {1}, {4}, {1,4}, {2,3,6} and those with 1 or 4 added, 8 in all, which is 2^(6 − 3) for the 3 independent primes 2, 3, 5. Leaving out the empty set gives 7, using only {1, 4} gives 4, and forgetting prime 5 gives 16.

More Coding Interview Problems questions

Exams that ask this topic