Data Structures & AlgorithmsModerateTCS NQT · counting

Problem: How many ordered pairs (i < j) of [1, 2, 3, 4, 6] have a[j] divisible by a[i]? Run the code.

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

Correct answer: B. 7

The qualifying pairs are (1,2), (1,3), (1,4), (1,6), (2,4), (2,6) and (3,6), giving 7; (2,3) and (3,4) fail. Starting j at i adds the 5 self-pairs (12), forgetting that 1 divides everything leaves only 3, and 10 counts all C(5,2) pairs as if divisibility always held.

More Coding Interview Problems questions

Exams that ask this topic