ProgrammingHardCompetitive coding (CP)

How many subsets of {1, 2, 3} (the empty set included) have a sum divisible by 3? The recursion below counts them. What is printed?

How many subsets of {1, 2, 3} (the empty set included) have a sum divisible by 3? The recursion below counts them. What is printed?
#include <stdio.h>
int v[3] = {1, 2, 3};
int cnt(int i, int s) {
    if (i == 3) return s % 3 == 0;
    return cnt(i + 1, s) + cnt(i + 1, s + v[i]);
}
int main(void) {
    printf("%d", cnt(0, 0));
}
  1. A. 3
  2. B. 2
  3. C. 5
  4. D. 4

Correct answer: D. 4

The subsets with sum 0, 3, 3 and 6 are the empty set, {3}, {1, 2} and {1, 2, 3}, which makes 4.

More C Programming questions

Exams that ask this topic