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));
}- A. 3
- B. 2
- C. 5
- 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
- How many bit positions are zero in both 0xAAAA and 0x5555 within 16 bits? Count them with this program. c #include <stdint.h> #include…
- What is printed? Assume unsigned int is 32 bits. c #include <stdio.h> int main(void) { unsigned x = 12; printf("%u", (x << 3) + (x << 1)); }
- How many adjacent pairs of 1 bits does 27 (binary 11011) have? The program counts the set bits of x & (x >> 1). c #include <stdio.h> int…
- What is printed? c #include <stdio.h> int main(void) { int b[] = {1, 1, 0, 1, 1, 1, 0, 1, 1, 1}, run = 0, best = 0; for (int i = 0; i <…
- What is printed? c #include <stdio.h> int main(void) { int a[] = {1, 2, 3, 4, 5}; for (int i = 0; i + 1 < 5; i += 2) { int t = a[i]; a[i]…
- What is printed? c #include <stdio.h> int f(int n) { return n <= 1 ? 0 : 1 + f(n / 2); } int main(void) { printf("%d", f(10)); }