# Fastest way to compute the solution of this equation

I am looking for the solutions to the equation : $$a_1+...+a_n =x$$ with $$-3 \leq a_i\in \mathbb {Z} \leq 3 \ \ \ \ \ \forall i$$ $$x \in \mathbb Z$$

Mathematica will get you the solutions eventually with ( x == tot, and varNbr==n) :

Solutions[tot_, varNbr_] := Block[{ unknowns= Symbol["a" <> ToString[#]] & /@ Range[varNbr] }, Solve[Total[unknowns] == tot&& ( -4 < # < 4) & /@ unknowns, unknowns, Integers] ]

but it's very slow for big variable numbers. (try it with varNbr around 10 for example, not 1000).

Do you have faster solutions ?

• In view of that nothing simple is expected. – user64494 Feb 17 at 12:25
• Require the variables to be ordered to eliminate permutations of the same values. Solutions[tot_Integer, varNbr_Integer?Positive] := Module[{unknowns = Array[a, varNbr]}, Solve[Total[unknowns] == tot && (LessEqual @@ unknowns) && And @@ ((-4 < # < 4) & /@ unknowns), unknowns, Integers]] – Bob Hanlon Feb 17 at 15:51
• FrobeniusSolve solves the same equation with different bounds -- maybe it could be adapted or not. Probably it's easiest to loop through $a_n =x -(a_1+...+a_{n-1})$ and select the ones for which $3\le a_n\le3$. – Michael E2 Feb 17 at 16:17
• @BobHanlon: These are different solutions which form the same partition. The OP asks for solutions. – user64494 Feb 17 at 16:31
• @user64494 "FrobeniusSolve finds only non-negative integer solutions" -- so I said...again, you're focused on the wrong thing. – Michael E2 Feb 17 at 16:51

That's precisely what IntegerPartitions does. For example, for $$n=10$$ and $$x=12$$ we have 157 ordered solutions,

IntegerPartitions[12, {10}, Range[-3, 3]]
(*    {{3, 3, 3, 3, 3, 3, 3, -3, -3, -3},
{3, 3, 3, 3, 3, 3, 2, -2, -3, -3},
{3, 3, 3, 3, 3, 3, 1, -1, -3, -3},
...
{2, 2, 1, 1, 1, 1, 1, 1, 1, 1}}    *)


If you want all permutations of these (all unordered solutions), apply Permutations to each ordered solution. There are now $$3\,039\,400$$ solutions,

Join @@ Permutations /@ %
(*    {{3, 3, 3, 3, 3, 3, 3, -3, -3, -3},
{3, 3, 3, 3, 3, 3, -3, 3, -3, -3},
{3, 3, 3, 3, 3, 3, -3, -3, 3, -3},
...
{1, 1, 1, 1, 1, 1, 1, 1, 2, 2}    *)


All together in one function:

solutions[x_, n_] :=
Join @@ Permutations /@ IntegerPartitions[x, {n}, Range[-3, 3]]