1
$\begingroup$

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 ?

$\endgroup$
6
  • $\begingroup$ In view of that nothing simple is expected. $\endgroup$
    – user64494
    Feb 17, 2021 at 12:25
  • 4
    $\begingroup$ 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]] $\endgroup$
    – Bob Hanlon
    Feb 17, 2021 at 15:51
  • $\begingroup$ 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$. $\endgroup$
    – Michael E2
    Feb 17, 2021 at 16:17
  • $\begingroup$ @BobHanlon: These are different solutions which form the same partition. The OP asks for solutions. $\endgroup$
    – user64494
    Feb 17, 2021 at 16:31
  • 4
    $\begingroup$ @user64494 "FrobeniusSolve finds only non-negative integer solutions" -- so I said...again, you're focused on the wrong thing. $\endgroup$
    – Michael E2
    Feb 17, 2021 at 16:51

1 Answer 1

7
$\begingroup$

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]]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.