Find all combinations that sum up to a specific number

3.5k Views Asked by At

How to find all the combinations that adds up to a certain number, given the number of elements?

For example if target $T$ is $ 100 $ and number of elements is $2$. Then the result is $101$. ($100+ 0$, $99 + 1$, $98 + 2$,… $1 + 99$, $0+ 100$.)

What would the formula be, if the given number of elements is $ 3, 4$, etc?

2

There are 2 best solutions below

3
On BEST ANSWER

The more general way to do this is to use generating functions. The number of ways to write $100$ as the sum of two non-negative integers is the coefficient of $x^{100}$ in the product $$ (1 + x + x^2 + \cdots + x^{100})(1 + x + x^2 + \cdots + x^{100}) $$ and the number of ways to write $100$ as the sum of $5$ non-negative integers is the coefficient of $x^{100}$ in $$ (1 + x + x^2 + \cdots + x^{100})^{5}. $$

This method is more flexible because you can control which terms appear in the sum. For example, if you want the first term to be even, the second term to be a multiple of $4$, and the third term to be a multiple of $6$, you want the coefficient of $x^{100}$ in $$ (1 + x^2 + x^4 + \cdots + x^{100})(1 + x^4 + x^8 + \cdots + x^{100})(1 + x^6 + x^{12} + \cdots + x^{96}). $$

2
On

The method you're looking for is called Stars and bars method.

The formula is $$N=\binom{n+k-1}{n}$$ where $n$ is the number you want to split and $k$ is the number of parts.