Question: Say you are given `A` oranges and `B` apples. You want to create a basket of total `N` fruits. What is the total number of combination of apples and oranges you can make?  

Assuming `A+B >= N`.

**Example:**  

I have 6 oranges and 6 apples and I want to create a basket with total 9 fruits.  

So I have 4 different combinations:

```
3 apples 6 oranges
4 apples 5 oranges
5 apples 4 oranges
6 apples 3 oranges

```

I want to create a simple (and efficient) algorithm to calculate this number.  

Is there any mathematical / combinatoric way to calculate this number in O(1)? I couldn't find a correct formula for this.

Answer: 
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](https://en.wikipedia.org/wiki/Stars_and_bars_(combinatorics)) and [Inclusion Exclusion](https://en.wikipedia.org/wiki/Inclusion%E2%80%93exclusion_principle), 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

```
Ok, sorry, I was (way) too fast.

You know there's always at least one solution.

You have to take at least enough fruit of A so that with B, it makes N. You take at max A fruit of A. If that's bigger than N, the limit is N. So the answer should be:

```
min(A, N) - max(0, N-B) + 1

```