This answer will show a generic way how to get to the correct closed formula, rather than give "here, it works" formula.
To get to a close formula, using the Stars and Bars formula and Inclusion Exclusion, you want to find the number of solutions to the equation:
x1 + x2 = n
s.t.
(1) 0 <= x1 <= A
(2) 0 <= x2 <= B
Denote:
W(0) = #solutions to the problem regardless of restrictions
W(1) = #solutions to the problem with (1) is NOT correct (x1 > A)
W(2) = #solutions to the problem with (2) is NOT correct (x2 > B)
W(1,2) = #solutions to the problem with both (1,2) NOT correct (x1 > A and X2 > B)
From inclusion exclusion principle, the answer to the problem we formalized above is:
E = W(0) - (W(1) + W(2)) + W(1,2)
All is left is to give formulas to W(...)
, and for this we will use the Stars and Bars.
Using the equations without constraits and Theorem 2 of bars and stars:
W(0) = Choose(N + 2 - 1, 2 - 1) = Choose(N + 1, 1) = N + 1
To calculate W(1) and W(2), we force x1/x2
to be A+1
or B+1
, and then go as usual, and get the equations:
x1 + x2 = N - A - 1
x1 + x2 = N - B - 1
and the number of solutions are (again using theorem 2):
W(1) = Choose(N - A - 1 + 2 - 1, 1) = Chose(N-A,1) = max{N-A,0}
W(2) = (similarly) = max{N-B,0}
For W(1,2) we set both and go on and get:
W(1,2) = Choose(N - A - 1 - B -1 + 2 - 1) = Choose(N-A-B-1,1) = max{N-A-B-1,0}
Summing it all together to the final formula:
E = W(0) - (W(1) + W(2)) + W(1,2) =
= N + 1 - max{N-A,0} - max{N-B,0} + max{N-A-B-1,0}
Which in your example is:
E = 9 + 1 - 3 - 3 + 0 = 4