4

I would like to list all ways of writing $n$ as the sum of 3 squares. This is slightly different from finding just one:

My current implementation is the naive one which runs in $O(n^{3/2})$ time: Write all numbers $n = x^2 + y^2 + z^2$ with

  • $x < \sqrt{n}$
  • $y < \sqrt{n - x^2}$
  • $z < \sqrt{n - x^2 - y^2}$

Perhaps there is a more efficient way using Quaternions or matrices or something?

Finding All Representations

The linked questions efficiently compute one representation $n = x^2 + y^2 + z^2$. However, I am hoping to find a complete list of all representations and I would like to know if we can do any better than the naïve algorithm.

john mangual
  • 22,599

1 Answers1

7

The number of representation can be as big as $\sqrt{n},$ so this is a lower bound on the complexity of any algorithm. Now, the algorithm is to iterate through all $k\leq \sqrt{n},$ and try to represent $n-k^2$ as a sum of squares (in all possible ways). This is equivalent to factoring, so the complexity will be not that bad above optimal (factoring is "hard", but not so hard compared to $\sqrt{n},$ indeed, this algorithm runs in time $O(n^{1/2 + \epsilon})$ for any $\epsilon > 0.$)

Igor Rivin
  • 95,560