TITLE: Is there an algorithm for writing a number as a sum of three squares?
QUESTION [11 upvotes]: By Gauss's Theorem, every positive integer $n$ is a sum of three triangular numbers; 
these are numbers of the form $\frac{m(m+1)}2$. Clearly
$$ n = \frac{m_1^2+m_1}2 + \frac{m_2^2+m_2}2 + \frac{m_3^2+m_3}2, $$
so multiplying through by $4$ and completing the squares gives
$$ 8n+3 = (2m_1+1)^2 + (2m_2+1)^2 + (2m_3+1)^2. $$
Thus writing $n$ as a sum of three triangular numbers is equivalent to writing $8n+3$ as a sum of three (necessarily odd) squares. 
My question is;
 Is there an algorithm for writing a positive integer as a sum of three squares?

REPLY [11 votes]: This problem is discussed in my paper with Rabin, Randomized algorithms in number theory,
Commun. Pure Appl. Math. 39, 1985, S239 - S256.  We give an algorithm that, assuming a couple of reasonable conjectures, will produce a representation as a sum of three squares in random polynomial time.