Data Structures & AlgorithmsHardProduct Company SDE · CP practice

Problem: How many integers in [1, 500] are perfect squares or multiples of 7? Run the code.

Problem: How many integers in [1, 500] are perfect squares or multiples of 7? Run the code.
print(sum(1 for x in range(1, 501) if any(k * k == x for k in range(1, 23)) or x % 7 == 0))
What is printed?
  1. A. 93
  2. B. 90
  3. C. 71
  4. D. 87

Correct answer: B. 90

22 squares + 71 multiples of 7 − 3 overlaps (49, 196, 441) = 90. Not removing the overlap gives 93, 71 counts only multiples of 7, and subtracting the overlap twice gives 87.

More Coding Interview Problems questions

Exams that ask this topic