Maximize utility given an arbitrary number of goods and the condition that exactly X number of items must be bought
Utility maximization problem is 
\begin{eqnarray*} \max_{x_1, x_2, \ldots, x_n} &amp;&amp; u(x_1, x_2, \ldots, x_n) \\ \text{s.t.} &amp;&amp; \sum_{i=1}^n p_ix_i \leq M \\ &amp;&amp; \sum_{i=1}^n x_i = X \\ &amp;&amp; x_i\in\mathbb{Z}_+ \ \ \forall i\in\{1,2,\ldots, n\} \end{eqnarray*} 

If we ignore the budget constraint, the equation $\sum\limits_{i=1}^n x_i = X$ has ${X+n-1\choose n-1}$ solutions. List them, sort them from high to low by utility, and then identify the highest one in the sorted list that also satisfy the budget constraint. 

If $u$ is strictly increasing, differentiable and quasi-concave on $\mathbb{R}_+^n$, then one can solve the utility maximization problem in the usual way by ignoring the $\sum_{i=1}^n x_i = X$ constraint, and then inspect the integral solutions of $\sum_{i=1}^n x_i = X$ that surrounds the solution of the utility maximization problem, and choose the best amongst them to get the final solution.