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));
}
  1. A. 6
  2. B. 7
  3. C. 16
  4. 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

Exams that ask this topic