Data Structures & AlgorithmsHardProduct Company SDE · CP practice

Problem: How many numbers in [1, 1000] are divisible by 3 and whose digit sum is also divisible by 3? Run the code.

Problem: How many numbers in [1, 1000] are divisible by 3 and whose digit sum is also divisible by 3? Run the code.
print(sum(1 for x in range(1, 1001) if x % 3 == 0 and sum(map(int, str(x))) % 3 == 0))
What is printed?
  1. A. 111
  2. B. 333
  3. C. 667
  4. D. 37

Correct answer: B. 333

Divisibility by 3 already implies the digit-sum condition, so the answer is 1000 // 3 = 333. Treating the conditions as independent or as divisibility by 9 gives 111, 667 counts the complement, and 37 counts multiples of 27.

More Coding Interview Problems questions

Exams that ask this topic