ProgrammingHardGATE CS · Competitive coding (CP)

How many subsets of {1, 2, 3, 4, 5, 6} (the empty set included) have a sum divisible by 3? Compute with this program.

How many subsets of {1, 2, 3, 4, 5, 6} (the empty set included) have a sum divisible by 3? Compute with this program.
#include <stdio.h>
int main(void) {
    int count = 0;
    for (unsigned m = 0; m < 64; m++) {
        unsigned s = 0;
        for (int i = 0; i < 6; i++)
            if (m >> i & 1u) s += (unsigned)i + 1;
        if (s % 3 == 0) count++;
    }
    printf("%d", count);
}
  1. A. 24
  2. B. 20
  3. C. 18
  4. D. 32

Correct answer: A. 24

Each bit of m selects one element of {1..6}, so the loop checks all 64 subsets. Of these, 24 have a sum divisible by 3, including the empty set.

More C Programming questions

Exams that ask this topic