ProgrammingVery hardCompetitive coding (CP)
How many partitions of 5 are there? The program counts partitions of n into parts of size at most m. Compute with it.
How many partitions of 5 are there? The program counts partitions of n into parts of size at most m. Compute with it.
#include <stdio.h>
int part(int n, int m) {
if (n == 0) return 1;
if (n < 0 || m == 0) return 0;
return part(n - m, m) + part(n, m - 1);
}
int main(void) {
printf("%d", part(5, 5));
}- A. 6
- B. 7
- C. 16
- D. 3
Correct answer: B. 7
part(n, m) either uses a part of size m or forbids it, so each partition is counted once: 5, 4+1, 3+2, 3+1+1, 2+2+1, 2+1+1+1, 1+1+1+1+1 = 7. 6 forgets the single part 5, 16 = 2^4 counts ordered compositions, and 3 counts only partitions into distinct parts.
More C Programming questions
- What is printed? c #include <stdio.h> int main(void) { char c = 'A'; c += 32; printf("%c %d", c, c); }
- What is printed? c #include <stdio.h> int main(void) { int x = 2, r = 0; switch (x) { case 1: r += 1; case 2: r += 10; case 3: r += 100…
- How many loop iterations run? Compute with the program. c #include <stdio.h> int main(void) { unsigned x = 0xF00D; int c = 0; while (x) {…
- What is printed? c #include <stdio.h> int main(void) { int i = 5; do { i++; } while (i < 3); printf("%d", i); }
- What is printed? Assume int is 4 bytes. c #include <stdio.h> int main(void) { printf("%d %zu", 1 ? 'A' : 0, sizeof(1 ? 'A' : 0)); }
- What is printed? Assume unsigned long long is 64 bits. c #include <stdio.h> int main(void) { unsigned long long x = (1ULL << 40) - 1; int…