ProgrammingHardCompetitive coding (CP)

What is printed?

What is printed?
#include <stdio.h>
int main(void) {
    int c = 0;
    for (unsigned n = 1; n <= 20; n++) {
        unsigned x = n;
        int p = 0;
        while (x) { p ^= 1; x &= x - 1; }
        if (p == 0) c++;
    }
    printf("%d", c);
}
  1. A. 10
  2. B. 9
  3. C. 0
  4. D. 15

Correct answer: A. 10

p flips once per set bit (x &= x - 1 clears the lowest one), so p == 0 means an even popcount: 3, 5, 6, 9, 10, 12, 15, 17, 18, 20, i.e. 10 values. 9 forgets 15 (four bits), 0 reads p as the bit count itself, and 15 counts every non-power of two.

More C Programming questions

Exams that ask this topic