TITLE: Enumerating ways to decompose an integer into the sum of two squares
QUESTION [29 upvotes]: The well known "Sum of Squares Function" tells you the number of ways you can represent an integer as the sum of two squares.  See the link for details, but it is based on counting the factors of the number N into powers of 2, powers of primes = 1 mod 4 and powers of primes = 3 mod 4.
Given such a factorization, it's easy to find the number of ways to decompose N into two squares. But how do you efficiently enumerate the decompositions?
So for example, given N=2*5*5*13*13=8450 , I'd like to generate the four pairs:
13*13+91*91=8450
23*23+89*89=8450
35*35+85*85=8450
47*47+79*79=8450
The obvious algorithm (I used for the above example) is to simply take i=1,2,3,...,$\sqrt{N/2}$ and test if (N-i*i) is a square. But that can be expensive for large N. Is there a way to generate the pairs more efficiently?   I already have the factorization of N, which may be useful.
(You can instead iterate between $i=\sqrt{N/2}$ and $\sqrt{N}$ but that's just a constant savings, it's still $O(\sqrt N)$.

REPLY [2 votes]: Another point of view, which might be easier from an algorithmic point of view (in my opinion), is to look at the decomposition $n = a^2+b^2$ using complex numbers $n = (a+bi)(a-bi)$. Suppose you know how to find the solutions $a,b$ when $n$ is prime. Then note that the identity $(a^2+b^2)(c^2+d^2)=(ac+bd)^2+(ad-bc)^2$ can be seen as the equality of the product of modules of two complex numbers. 
In order to find all possible decompositions of a number $n$ into a sum of squares just write the factorization of $n$ in $\Bbb{Z}[i]$: $n = \prod (a_j+ib_j)$ and note that in this product every factor comes with its conjugate. First, ignore the powers of $2$ and the primes of the form $4k+3$. Now, in order to find all factorizations, just split all factors into two columns with conjugate pairs being on different columns. Doing this, when taking the product on each column we'll get a pair of conjugate numbers whose product equals to $n$, so we find a solution of the representation $n=a^2+b^2$. The number of ways to split the factors in the two columns with conjugate pairs on different sides will be equal the number of divisors of $n$ in $\Bbb{Z}[i]$ (divided by 4, since you can multiply factors by $1,-1,i,-i$) so all factors will be generated. 
If $n$ contains primes of the forms $4k+3$ or powers of $2$ look at Will Jagy's answer. Note that if you reduce all powers of $4$ and you still have a $2$ left in $n$ you can write $2 = (1+i)(1-i)$ and split this on different sides of the two columns.