Data Structures & AlgorithmsModerateProduct Company SDE · CP practice

Problem: How many squares (k k with k >= 1) are at most 10^6? Run the code.

Problem: How many squares (k * k with k >= 1) are at most 10^6? Run the code.
print(sum(1 for k in range(1, 10 ** 6) if k * k <= 10 ** 6))
What is printed?
  1. A. 999
  2. B. 100
  3. C. 1000
  4. D. 31

Correct answer: C. 1000

k² ≤ 10⁶ holds for k = 1..1000, and 1000 < 10⁶ − 1, so the loop bound does not cut it. A strict k < 1000 gives 999, the cube root gives 100, and 31 counts squares up to 10³.

More Coding Interview Problems questions

Exams that ask this topic