ProgrammingHardTCS NQT · Accenture

The number of ways to write 20 as p + q with p and q prime and p <= q is counted by the procedure below, which tries p = 2 to 10 and sets q = 20 - p. What is printed?

The number of ways to write 20 as p + q with p and q prime and p <= q is counted by the procedure below, which tries p = 2 to 10 and sets q = 20 - p. What is printed?
count = 0
for p = 2 to 10
    q = 20 - p
    if p and q are both prime and p <= q then count = count + 1
end for
Print count
  1. A. 4
  2. B. 8
  3. C. 5
  4. D. 2

Correct answer: D. 2

The pairs with p <= q summing to 20 are 3 + 17 and 7 + 13 (since 1 is not prime), so the count is 2. Letting p run to 20 counts the reversed pairs as well, counting all primes up to 20 gives 8, and using or instead of and counts many more pairs.

More Pseudocode and Code Tracing questions

Exams that ask this topic