Data Structures & AlgorithmsHardProduct Company SDE · CP practice

Problem: How many pairs (i < j) of [2, 4, 6, 9, 12, 15] have gcd(ai, aj) = 3? Run the code.

Problem: How many pairs (i < j) of [2, 4, 6, 9, 12, 15] have gcd(a_i, a_j) = 3? Run the code.
from math import gcd
a = [2, 4, 6, 9, 12, 15]
print(sum(1 for i in range(len(a)) for j in range(i + 1, len(a)) if gcd(a[i], a[j]) == 3))
What is printed?
  1. A. 6
  2. B. 4
  3. C. 5
  4. D. 7

Correct answer: C. 5

Only pairs whose elements are both multiples of 3 with no common factor of 2 have gcd exactly 3.

More Coding Interview Problems questions

Exams that ask this topic