Data Structures & AlgorithmsVery hardICPC regional · number theory

Problem: How many ordered pairs (a, b) with 1 <= a <= b <= 20 have gcd(a, b) = 1? Run the code.

Problem: How many ordered pairs (a, b) with 1 <= a <= b <= 20 have gcd(a, b) = 1? Run the code.
from math import gcd
print(sum(1 for a in range(1, 21) for b in range(a, 21) if gcd(a, b) == 1))
What is printed?
  1. A. 127
  2. B. 120
  3. C. 128
  4. D. 255

Correct answer: C. 128

Each b contributes φ(b) coprime partners a ≤ b, so the count is Σφ(b) for b = 1..20 = 128; the pair (1, 1) is included. Starting b at a + 1 drops (1, 1) and gives 127, stopping at 19 drops φ(20) = 8 (120), and counting ordered pairs gives 2 × 128 − 1 = 255.

More Coding Interview Problems questions

Exams that ask this topic