Data Structures & AlgorithmsHardTCS NQT · number theory

Problem: How many unordered pairs (i < j) of 1..10 have a sum divisible by 5? Run the code.

Problem: How many unordered pairs (i < j) of 1..10 have a sum divisible by 5? Run the code.
a = list(range(1, 11))
print(sum(1 for i in range(len(a)) for j in range(i + 1, len(a)) if (a[i] + a[j]) % 5 == 0))
What is printed?
  1. A. 10
  2. B. 11
  3. C. 9
  4. D. 12

Correct answer: C. 9

Residues mod 5 pair up as (0,0), (1,4) and (2,3). They give 1 + 4 + 4 = 9 pairs, for example (5,10) and (1,9).

More Coding Interview Problems questions

Exams that ask this topic