[Math] Number of ways to express an integer N as sum of 4 integers

combinatoricselementary-number-theory

In reference to the question mentioned here :
Number of ways to express a number as the sum of different integers,

what would be the number of ways to express the number if there is an additional constraint on the ordering of the k integers? For example – if a,b,c,d are k positive integers which express the number and the required ordering constraint is:

a <= b <= c <= d.

There is also a programming solution to this example here: Number of ways to express an integer N as sum of 4 integers
which I can't seem to understand.

There is a same question here too In how many ways I can write a number N as sum of 4 numbers?
However, the method used in the above mentioned programming solution looks simple. It would be of great help if the method could be explained easily.

Best Answer

you can get a solution with complexity $\mathcal O (1)$

there are $5$ types of solutions:

  • All numbers are equal
  • three equal numbers and one distinct
  • two and two
  • one pair and the other two distinct
  • all different

let $A,B,C,D,E$ be the number of solutions of each type.

Clearly $A=1$ if $4|N$ and $0$ otherwise.

We have $B=\lfloor (N-1)/3 \rfloor-A$

we have $C=0$ if $C$ is odd and $C=(N/2-1-A)/2$ otherwise.

We have $D=[(\sum\limits_{i=1}^{2i<N}N-2i-1)-C]/2-B$.

Finally, using stars and bars we get $E=\frac{\binom{N-1}{3}-A-4B-6C-12D}{4!}$.

And clearly you want $A+B+C+D+E$