Data Structures & AlgorithmsModerateTCS NQT · number theory

Problem: How many pairs (i < j) of [2, 4, 6, 8] have gcd exactly 2? Run the code.

Problem: How many pairs (i < j) of [2, 4, 6, 8] have gcd exactly 2? Run the code.
from itertools import combinations
from math import gcd
print(sum(1 for i, j in combinations([2, 4, 6, 8], 2) if gcd(i, j) == 2))
What is printed?
  1. A. 4
  2. B. 5
  3. C. 6
  4. D. 3

Correct answer: B. 5

The qualifying pairs are (2,4), (2,6), (2,8), (4,6) and (6,8). Only (4,8) has gcd 4.

More Coding Interview Problems questions

Exams that ask this topic