ProgrammingHardTCS NQT · Infosys SP

What will be the output of the following pseudocode?

What will be the output of the following pseudocode?
Integer c = 0
for (each a from 1 to 20)
    for (each b from a to 20)
        for (each h from b to 20)
            if (a * a + b * b == h * h)
                c = c + 1
            end if
        end for
    end for
end for
Print c
  1. A. 6
  2. B. 12
  3. C. 3
  4. D. 5

Correct answer: A. 6

With a ≤ b ≤ h ≤ 20 each right triangle is counted once: (3, 4, 5), (6, 8, 10), (5, 12, 13), (9, 12, 15), (8, 15, 17), (12, 16, 20). 12 ignores b starting from a and counts each triangle twice, 3 keeps only the primitive triples, and 5 misses (12, 16, 20) by treating 20 as excluded.

More Pseudocode and Code Tracing questions

Exams that ask this topic