Listing all compositions of an integer into k parts

### 7.1.27 Listing all compositions of an integer into k parts

A composition of a positive integer n is an ordered set of non-negative integers which sum to n. For example, three compositions of 4 are

4 | =1+3, |  |  |  |  |  |  |  |  |
4 | =3+1, |  |  |  |  |  |  |  |  |
4 | =1+1+2. |  |  |  |  |  |  |  |  |

These compositions have two, two and three elements, respectively. The icomp command finds all compositions of an integer with a given number of elements.

- icomp accepts two mandatory arguments and one optional argument:
  - n, a positive integer.
  - k, a positive integer not larger than n.
  - Optionally, either zeros=true (which is the default) or zeros=false.
- icomp(n,k ⟨,zeros=bool ⟩) returns the list of all compositions of n into k parts, where a part can be 0 if bool=true (the default), or where each part is greater than 0 if bool=false.

##### Remark.

Using icomp with too large values of n can easily clutter your working memory because the number of compositions rises exponentially.

#### Examples

icomp(4,2)

⎡ ⎢ ⎢ ⎢ ⎢ ⎢ ⎣ |
4 | 0
3 | 1
2 | 2
1 | 3
0 | 4
| ⎤ ⎥ ⎥ ⎥ ⎥ ⎥ ⎦

icomp(5,3,zeros=false)

⎡ ⎢ ⎢ ⎢ ⎢ ⎢ ⎢ ⎣ |
3 | 1 | 1
2 | 2 | 1
1 | 3 | 1
2 | 1 | 2
1 | 2 | 2
1 | 1 | 3
| ⎤ ⎥ ⎥ ⎥ ⎥ ⎥ ⎥ ⎦