Data Structures & AlgorithmsModerateProduct Company SDE · CP practice

Problem: How many distinct pairs (i < j) of [6, 10, 15, 21] have gcd(ai, aj) = 1? Run the code.

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

Correct answer: B. 1

gcd is 1 exactly when the two numbers share no prime factor, which the pairwise check verifies.

More Coding Interview Problems questions

Exams that ask this topic