Data Structures & AlgorithmsHardProduct Company SDE · CP practice

Problem: How many ways can you pick 2 different integers from [1, 20] whose sum is divisible by 4? Run the code.

Problem: How many ways can you pick 2 different integers from [1, 20] whose sum is divisible by 4? Run the code.
print(sum(1 for i in range(1, 21) for j in range(i + 1, 21) if (i + j) % 4 == 0))
What is printed?
  1. A. 90
  2. B. 45
  3. C. 55
  4. D. 47

Correct answer: B. 45

Residues 0 and 2 pair with themselves (C(5,2) = 10 each), and 1 pairs with 3 (5 · 5 = 25): 45. Ordered pairs give 90, allowing i = j gives 55, and 190/4 gives about 47.

More Coding Interview Problems questions

Exams that ask this topic