Data Structures & AlgorithmsModerateTCS NQT · number theory

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

Problem: How many pairs (i < j) of [2, 3, 4, 5, 6] have gcd(a[i], a[j]) = 1? Run the code.
from math import gcd
a = [2, 3, 4, 5, 6]
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. 4
  2. B. 12
  3. C. 7
  4. D. 6

Correct answer: D. 6

The coprime pairs are (2,3), (2,5), (3,4), (3,5), (4,5) and (5,6), giving 6 of the 10 pairs. Counting the pairs that share a factor gives 4, counting ordered pairs doubles it to 12, and testing 'neither divides the other' instead of gcd = 1 gives 7 because it wrongly admits (4,6).

More Coding Interview Problems questions

Exams that ask this topic