Data Structures & AlgorithmsModerateTCS NQT · number theory

Problem: What is the sum of gcd(i, j) over all pairs 1 <= i < j <= 4? Run the code.

Problem: What is the sum of gcd(i, j) over all pairs 1 <= i < j <= 4? Run the code.
from math import gcd
print(sum(gcd(i, j) for i in range(1, 5) for j in range(i + 1, 5)))
What is printed?
  1. A. 7
  2. B. 17
  3. C. 14
  4. D. 5

Correct answer: A. 7

The six pairs have gcds 1, 1, 1, 1, 2, 1 (only (2, 4) shares a factor), totalling 7. Starting j at i adds gcd(i, i) = 1 + 2 + 3 + 4 and gives 17, summing over ordered pairs doubles it to 14, and counting the coprime pairs instead of summing gcds gives 5.

More Coding Interview Problems questions

Exams that ask this topic