The number of ways to choose N items out of R groups where each item in a group is identical is equal to the number of integral solutions to _x_1 + _x_2 + _x_3…x__R = N, where 0 ≤ x__i ≤ L__i, where L__i is the number of items in i__th group. Number of integral solutions are coefficient of x__N in [Product of (1 + x + x * x + …x__L__i) over all $i$].
You need to find coefficient of x__s in (1 + x + _x_2 + _x_3 + + .._x__f_1) * * * (1 + x + _x_2 + _x_3 + + ..x__f__n).
Using sum of Geometric progression we can say that(1 + x + _x_2 + _x_3 + + .._x__f_1) = (1 - x(_f_1 + 1)) / (1 - x).
Substituting in the expression, we get (1 - x(_f_1 + 1)) / (1 - x) * * * (1 - x(f__n + 1)) / (1 - x).
Now we can find x__s in (1 - x) - n easily. It is.
You can have a look at following link. to understand it better.
So now as s is large, we can not afford to iterate over s.
But n is small, we notice that (1 - x(f_1 + 1)) * .. * (1 - x(f__n + 1)) can have at most 2_n terms.
So we will simply find all those terms, they can be very easily computed by maintaining a vector<pair<int, int> > containing pairs of coefficients and their corresponding powers. You can write a recursive function for doing this.
How to find% p. As n + s - 1 is large and s is very small. You can use lucas’s theorem. If you understand lucas’s theorem, you can note that we simply have to compute.