ProgrammingVery hardCAT · MBA placement

A pair (a, b) with 1 <= a < b <= 20 is called coprime if gcd(a, b) = 1. The procedure below counts coprime pairs. What is printed?

A pair (a, b) with 1 <= a < b <= 20 is called coprime if gcd(a, b) = 1. The procedure below counts coprime pairs. What is printed?
count = 0
for a = 1 to 20
    for b = a + 1 to 20
        if gcd(a, b) == 1 then count = count + 1
    end for
end for
Print count
  1. A. 128
  2. B. 63
  3. C. 190
  4. D. 127

Correct answer: D. 127

Counting every pair with a < b and gcd 1 gives 127. Including a = b adds the diagonal and gives 128, counting the non-coprime pairs gives 63, and counting all pairs ignores the test and gives 190.

More Pseudocode and Code Tracing questions

Exams that ask this topic