x1+...+xk = n#11550

x1+...+xk = n (Editorial)

Let's use the "stars and bars" method. Write down ones in a row: . There are n - 1 gaps between adjacent ones. Choose any k - 1 of these gaps and put a '' sign into each chosen gap. The ones are then split into consecutive groups; let x_i denote the number of ones in the -th group. For example, for n = 6 the string 11+111+1 corresponds to the solution (2, 3, 1) of the equation x_1 + x_2 + x_3 = 6.

Each such arrangement defines a solution of the equation in positive integers. Indeed, the sizes of all groups add up to , and every group is non-empty: a '' sign is never placed before the first one or after the last one, and no gap can contain two signs. Therefore, all x_i \ge 1.

There is a one-to-one correspondence between the solutions of the equation and the ways to choose k - 1 gaps out of n - 1. Hence, the required number of solutions equals C_{n-1}^{k-1}.

For example, for n = 5, k = 3 there are n - 1 = 4 gaps, of which k - 1 = 2 must be chosen. This can be done in C_4^2 = 6 ways, and each choice corresponds to exactly one solution of the equation x_1 + x_2 + x_3 = 5:

Example

Consider the equation x_1 + x_2 + x_3 = 4. It has positive integer solutions: (1, 1, 2), (1, 2, 1), (2, 1, 1).

For example, n = 4 ones can be divided into k = 3 terms in C_2^3 = 3 ways:

Note

Let’s consider a few variations of this problem:

Algorithm implementation

The Cnk function computes the value of the binomial coefficient C_n^k.

long long Cnk(long long k, long long n)
{
  long long res = 1;
  if (k > n - k) k = n - k;
  for (long long i = 1; i <= k; i++)
    res = res * (n - i + 1) / i;
  return res;
}

The main part of the program. Read the input data.

scanf("%lld %lld", &k, &n);

Compute and print the answer – the value of C_{n-1}^{k-1}.

res = Cnk(k - 1, n - 1);
printf("%lld\n", res);

Python implementation

import math

Read the input data.

k, n = map(int,input().split())

Compute and print the answer – the value of C_{n-1}^{k-1}.

res = math.comb(n - 1, k - 1)
print(res)