ProgrammingHardTCS NQT · Accenture

Count the integers n with 1 <= n <= 100 that are divisible by 3 or by 5, but NOT by both. The procedure below does this with a single loop. What is printed?

Count the integers n with 1 <= n <= 100 that are divisible by 3 or by 5, but NOT by both. The procedure below does this with a single loop. What is printed?
count = 0
for n = 1 to 100
    a = (n mod 3 == 0); b = (n mod 5 == 0)
    if a xor b then count = count + 1
end for
Print count
  1. A. 47
  2. B. 41
  3. C. 6
  4. D. 40

Correct answer: B. 41

Multiples of 3 up to 100 number 33 and multiples of 5 number 20, with 6 multiples of 15 in both, so exactly one holds for 27 + 14 = 41. Counting the union gives 47, counting both gives 6, and stopping the range at 99 gives 40.

More Pseudocode and Code Tracing questions

Exams that ask this topic