n = 6561;
Using PowersRepresentations
and filtering:
(powersreps = Select[DuplicateFreeQ] @ PowersRepresentations[n, 3, 2];
sPR = Sort[Join @@@ Join @@ (Permutations /@
Select[SubsetQ[powersreps, Sort /@ Transpose[#]] &] @
Select[DuplicateFreeQ @* Flatten] @
Subsets[Join @@ (Permutations /@ powersreps), {3}])];) // AbsoluteTiming // First
2.21796
Note: We could also use IntegerPartitions
instead of PowersRepresentations
:
Sort[Sort /@ Select[DuplicateFreeQ] @ Sqrt @
IntegerPartitions[n, {3}, Range[Sqrt @ n]^2]] == powersreps
True
Compare with using Solve
and filtering:
vars = {a, b, c, d, e, f, g, h, i};
eqns1 = {n == a^2 + b^2 + c^2, n == d^2 + e^2 + f^2, n == g^2 + h^2 + i^2};
eqns2 = {n == a^2 + d^2 + g^2, n == b^2 + e^2 + h^2, n == c^2 + f^2 + i^2};
rangeconstraints = {And @@ Thread[1 <= vars < n]};
sOP = Select[DuplicateFreeQ] @ Values @
Solve[Join[eqns1, eqns2, rangeconstraints], vars, Integers]; //
AbsoluteTiming // First
28.9619
sPR == sOP
True
Update: A much faster method using FindInstance
to find a single instance and processing it to generate the desired solution:
constraints = {And @@ Join[Thread[1 <= vars < n], {a < b < c, a != h}]};
(singleinstance = Partition[First @ Values @
FindInstance[Join[eqns1, eqns2, constraints], vars, Integers], 3];
sFI = Sort[Join @@@ Join @@ Transpose @* Map[Permutations] /@
(Join @@ (Permutations /@ {#, Transpose @ #} & @ singleinstance))];) //
AbsoluteTiming // First
0.183416
sFI == sOP
True