Data Structures & AlgorithmsHardTCS NQT · counting

Problem: How many integers in [1, 1000] are perfect squares or perfect cubes?

Problem: How many integers in [1, 1000] are perfect squares or perfect cubes?
print(sum(1 for x in range(1, 1001) if any(k * k == x for k in range(1, 32)) or any(k ** 3 == x for k in range(1, 11))))
What is printed?
  1. A. 41
  2. B. 37
  3. C. 31
  4. D. 38

Correct answer: D. 38

There are 31 squares (1 to 31²), 10 cubes (1 to 10³), and 3 numbers that are both, the sixth powers 1, 64 and 729, so 31 + 10 − 3 = 38. Forgetting the overlap gives 41, stopping k at 30 misses 961 (37), and counting only squares gives 31.

More Coding Interview Problems questions

Exams that ask this topic