ProgrammingHardTCS NQT Advanced · Goldman Sachs OA

What will be the output of the following pseudocode?

What will be the output of the following pseudocode?
Function gcd(Integer a, Integer b)
    if (b == 0) return a
    return gcd(b, a mod b)
End Function
Integer c = 0
for (each i from 1 to 10)
    for (each j from i + 1 to 10)
        if (gcd(i, j) == 1) c = c + 1
    end for
end for
Print c
  1. A. 45
  2. B. 32
  3. C. 27
  4. D. 31

Correct answer: D. 31

c counts pairs i < j up to 10 with no common factor. For each j, the number of smaller coprime i is φ(j): 1 + 2 + 2 + 4 + 2 + 6 + 4 + 6 + 4 = 31 (j = 2 to 10).

More Pseudocode and Code Tracing questions

Exams that ask this topic