Sums of two squares, continued fractions

Suppose p\equiv1\pmod4 is prime. Fermat’s theorem tells us that we can write p=x^2+y^2 . But how do we find the two integers? For a small prime we can try a few squares. For a large prime we would like something more systematic. There is a particularly nice algorithm that starts with a square root of minus one modulo p and uses nothing more than the Euclidean algorithm. There are really two problems here. The first is to find a square root of minus one modulo the prime. The second is to turn that modular root into a representation of the prime itself. We shall concentrate on the second problem first. At the end we will return to the first. This separation is useful because a modular root can be found by modular arithmetic, whereas finding two small integers seems at first to be a problem of a different kind.

Suppose r^2\equiv-1\pmod p , with 0<r<p . Imagine that we have found r^2+1=kp . If k=1 , we are finished. Usually, however, k is quite large. Can we somehow replace the pair (r,1) by a smaller pair without losing the fact that the sum of its squares is divisible by the prime? It is worth keeping this question in mind as we work through the examples.

For instance, take p=29 . We can choose r=12 , since 12^2+1=145=5\cdot29 . We already have a sum of two squares divisible by 29 . What we would like to do is find two smaller integers whose squares add up to 29 itself. Let us apply the Euclidean algorithm to 29 and 12 . The complete calculation is

\displaystyle \begin{aligned}29&=2\cdot12+5,\\ 12&=2\cdot5+2,\\ 5&=2\cdot2+1,\\ 2&=2\cdot1+0.\end{aligned}

Normally, we carry out the Euclidean algorithm until the remainder becomes zero. The last nonzero remainder gives us the greatest common divisor. Here, however, we are interested in something different. Look at the sequence of successive remainders:

\displaystyle 29,\quad12,\quad5,\quad2,\quad1,\quad0.

Since \sqrt{29}\approx5.385 , the first remainder that falls below \sqrt{29} is 5 . Let us stop at this point and ask whether 5 could be one of the two integers we are looking for. If it is, then the difference 29-5^2 must be a perfect square. Indeed,

\displaystyle 29-5^2=4=2^2.

We have obtained the desired representation: \displaystyle 29=5^2+2^2.

Why did we stop at \sqrt{29} ? And why should the difference be a perfect square? At the moment, there is no obvious reason for this to work. Before trying to explain it, let us experiment with a few more primes. In each case, we shall start with a square root of -1 modulo the prime, perform the Euclidean algorithm, and examine what happens when the remainder first falls below \sqrt p .

\displaystyle \begin{array}{c|c|l|l}p&r&\text{Remainders}&\text{Representation}\\\hline 73&27&19,8&73=8^2+3^2\\97&22&9&97=9^2+4^2\\109&33&10&109=10^2+3^2\\1009&469&71,43,28&1009=28^2+15^2\end{array}

Let us do the divisions explicitly in two of these examples. For seventy-three, the first division leaves a remainder of nineteen, which is still too large. The second leaves eight, which is small enough:

\displaystyle 73=2\cdot27+19,\qquad27=19+8.

The square root of seventy-three lies between eight and nine. Subtracting sixty-four from seventy-three leaves nine. For ninety-seven, only one division is needed:

\displaystyle 97=4\cdot22+9,\qquad97-9^2=4^2.

For the larger example of 1009, we need three divisions:

\displaystyle \begin{aligned}1009&=2\cdot469+71,\\469&=6\cdot71+43,\\71&=43+28.\end{aligned}

Here the square root of 1009 is between thirty-one and thirty-two. The first two remainders are too large, but twenty-eight is small enough. The difference 1009-28^2=225 is the square of fifteen. The rule works even when the first modular root is larger than the prime divided by two. For instance, we could have chosen 17 instead of twelve for the prime twenty-nine. The divisions would be

\displaystyle 29=17+12,\qquad17=12+5.

We obtain the same five. Choosing the smaller of the two modular roots is convenient, but is not necessary. Why should this work? The interesting point is that a remainder carries more information than its size. In our first example, 5=29-2\cdot12 . Reducing modulo twenty-nine and squaring gives 5^2\equiv-2^2\pmod{29} . The second square comes from the coefficient of twelve. This suggests keeping track of that coefficient as we run the Euclidean algorithm.

Let us pause over the example of seventy-three. We have 19=73-2\cdot27 and 8=27-19=3\cdot27-73 . Thus eight is congruent to three times our original modular root. We immediately get

\displaystyle 8^2\equiv-3^2\pmod{73}.

The second integer in the representation is therefore not something that we need to find by taking a square root at the end. It is already present in the Euclidean calculation. For 1009, the corresponding calculations are

\displaystyle \begin{aligned}71&=1009-2\cdot469,\\43&=13\cdot469-6\cdot1009,\\28&=7\cdot1009-15\cdot469.\end{aligned}

The last line gives 28^2+15^2\equiv0\pmod{1009} . Both twenty-eight and fifteen are smaller than the square root of 1009. Their squared sum is therefore smaller than twice 1009. Since it is a positive multiple of 1009, it has to be 1009 itself. This suggests what we should try to prove in general: at the first small remainder, its accompanying coefficient is also small.

Why the algorithm works

To understand why this procedure works, let us look more carefully at what happens during the Euclidean algorithm. Recall that our starting point is an integer r satisfying r^2\equiv-1\pmod p . This means that whenever we find two integers x,y satisfying \displaystyle x\equiv ry\pmod p, we automatically have

\displaystyle x^2+y^2\equiv r^2y^2+y^2\equiv0\pmod p.

So there is an easy way to construct sums of two squares divisible by p . Choose an integer y , multiply it by r , and subtract some multiple of p to obtain x . The difficulty is to choose the integers in such a way that both x and y are small. Now return to the Euclidean algorithm. Take, for example, p=1009 and r=469 . The first division gives \displaystyle 1009=2\cdot469+71. We usually think of 71 simply as a remainder. But let us write the equality in a slightly different way:

\displaystyle 71=1009-2\cdot469.

This tells us that 71\equiv-2\cdot469\pmod{1009} . We have therefore found a pair of integers, 71 and -2 , whose squares add up to a multiple of 1009 . Indeed,

\displaystyle 71^2+(-2)^2  \equiv 71^2-(-2)^2(469)^2 \equiv 0 \pmod{1009}, \quad  71^2+(-2)^2  = 5\cdot1009.

This is already an improvement over our original sum 469^2+1^2 . Can we make it smaller still? The next step of the Euclidean algorithm gives \displaystyle 43=469-6\cdot71. Substituting the expression we obtained for 71 , we find

\displaystyle 43=469-6(1009-2\cdot469)=13\cdot469-6\cdot1009.

Thus 43\equiv13\cdot469\pmod{1009} , and we obtain another sum of two squares divisible by 1009 :

\displaystyle 43^2+13^2  \equiv 0 \pmod{1009}, \quad 43^2+13^2 =2\cdot1009.

We are getting closer. Let us perform one more division: \displaystyle 28=71-43=7\cdot1009-15\cdot469. This time we obtain

\displaystyle 28^2+15^2=1009.

What is interesting about these calculations is that the Euclidean algorithm is producing two useful integers at each step, even though we usually pay attention to only one of them. The first is the remainder itself. The second is the coefficient of r when we express that remainder in terms of our original two integers. Let us now describe this systematically. Write the successive remainders as r_0=p,\ r_1=r . Every subsequent remainder is obtained by subtracting a multiple of one remainder from the preceding one:

\displaystyle r_{i+1}=r_{i-1}-q_i r_i.

Since we begin with p and r , and perform only integer subtractions, every remainder must be an integer linear combination of these two numbers. We can therefore write

\displaystyle r_i=s_i p+t_i r.

We are particularly interested in the coefficient t_i . The reason is that the other term, s_i p , disappears when we reduce modulo p . Thus knowing t_i tells us that

\displaystyle r_i\equiv t_i r\pmod p.

How do we keep track of these coefficients without repeatedly substituting all the previous expressions? For the first two remainders, the coefficients are easy to determine. We have

\displaystyle r_0=1\cdot p+0\cdot r,\qquad r_1=0\cdot p+1\cdot r.

So we begin with t_0=0 and t_1=1 . Now suppose we already know the coefficients of two successive remainders. The next Euclidean division gives

\displaystyle \begin{aligned}r_{i+1}&=r_{i-1}-q_i r_i\\&=(s_{i-1}p+t_{i-1}r)-q_i(s_ip+t_ir)\\&=(s_{i-1}-q_i s_i)p+(t_{i-1}-q_i t_i)r.\end{aligned}

Reading off the coefficient of r , we obtain

\displaystyle t_{i+1}=t_{i-1}-q_i t_i.

This is convenient. We can calculate the coefficients by exactly the same recurrence that we use to calculate the remainders. There is no need to keep track of the coefficients s_i if all we want is the congruence modulo p . Since r_i\equiv rt_i\pmod p and r^2\equiv-1\pmod p , we have at every step

\displaystyle r_i^2+t_i^2\equiv0\pmod p.

In our example of p=1009 , we can now write the two sequences side by side, together with the sums of squares they produce:

\displaystyle \begin{array}{c|r|r|r} i&r_i&t_i&(r_i^2+t_i^2)/1009 \\ \hline 0&1009&0&1009\\ 1&469&1&218 \\ 2&71&-2&5\\ 3&43&13&2\\4&28&-15&1\\ 5&15&28&1\\ 6&13&-43&2\\ 7&2&71&5\\ 8&1&-469&218\end{array}

Notice what is happening. In the first column of remainders, the numbers become smaller and smaller. In the next column, the absolute values of the coefficients become larger and larger. The sum of their squares initially decreases, reaches 1009 , and then begins to increase again. This explains why it is not necessarily useful to run the Euclidean algorithm all the way to the remainder 1 . Although we have made one of the two integers very small, we have done so at the expense of making the other one large. What we really want is a stage at which both integers are small. In fact, we do not need a particularly sharp estimate. If we can arrange that both r_i and |t_i| are smaller than \sqrt p , then

\displaystyle 0<r_i^2+t_i^2<2p.

But we already know that this sum is divisible by p . The only possibility is therefore

\displaystyle r_i^2+t_i^2=p.

Our problem has now become much simpler. We no longer need to explain directly why subtracting the square of a remainder from p produces another perfect square. We only need to understand the relationship between the decreasing remainders and the increasing coefficients. In particular, what happens to |t_i| at the moment when r_i first falls below \sqrt p ? It turns out that a simple identity in the Euclidean algorithm guarantees that the coefficient is still smaller than \sqrt p at precisely this stage.

So at every step we have a sum of two squares divisible by the prime. We want both integers to be small. The remainders decrease, while the absolute values of the coefficients increase. Fortunately there is an exact relation between them. The recurrence gives

\displaystyle r_it_{i+1}-r_{i+1}t_i=-(r_{i-1}t_i-r_it_{i-1}).

To see why the displayed identity holds, substitute the two recurrences on its left. The terms involving the quotient cancel:

\displaystyle \begin{aligned}r_it_{i+1}-r_{i+1}t_i&=r_i(t_{i-1}-q_it_i)\\&\quad -(r_{i-1}-q_ir_i)t_i\\&=r_it_{i-1}-r_{i-1}t_i.\end{aligned}

The initial value of the determinant is p\cdot1-r\cdot0=p . The signs of the coefficients alternate because the first two nonzero ones are 1,-q_1 , and subtracting a positive multiple of a coefficient from one of the opposite sign preserves this pattern. The initial determinant is p , so its absolute value never changes. Moreover, the nonzero coefficients t_i alternate in sign. Hence, for positive remainders,

\displaystyle r_{i-1}|t_i|+r_i|t_{i-1}|=p.

Now let r_k be the first remainder smaller than \sqrt p . The previous remainder is larger than \sqrt p . The identity above gives |t_k|\leq p/r_{k-1}<\sqrt p . Thus both integers are smaller than the square root of the prime. Their squared sum is a positive multiple of p smaller than 2p . There is only one such multiple. We conclude that

\displaystyle  p=r_k^2+t_k^2.

This explains the stopping rule. We stop at precisely the point where the remainder and its accompanying coefficient are both small enough. This is the simplest case of Cornacchia’s algorithm. Notice that the proof never used the best approximation theorem for continued fractions. Nor did it require us to know in advance that a representation exists. The determinant identity is enough. It provides an upper bound on the coefficient of the modular root in terms of the previous remainder, rather than the current one. This is exactly why we stop at the first crossing of the threshold, not at an arbitrary remainder below it.

Continued fractions

There is another way to discover the same algorithm. We want small integers x,y satisfying x\equiv ry\pmod p . Write x=ry-mp . Dividing by py gives

\displaystyle \frac rp-\frac my=\frac{x}{py}.

Thus we are looking for a good rational approximation to r/p with a small denominator. Continued fractions do exactly this. For instance,

\displaystyle \frac{469}{1009}=[0;2,6,1,1,\ldots] .

Its convergents begin with 0/1,1/2,6/13,7/15 . The last of these gives 469\cdot15-1009\cdot7=-28 . Both fifteen and twenty-eight are smaller than \sqrt{1009} , giving 1009=28^2+15^2 . The continued fraction is not searching for squares directly. It is finding a small denominator and a small approximation error. Our congruence turns these two quantities into a sum of squares.

For a smaller example, the fraction 12/29 has continued fraction expansion [0;2,2,2,2] . Let us compute the approximation errors without using decimals. For a convergent m/y , the integer error is 12y-29m .

\displaystyle \begin{array}{c|r|r|r}m/y&y&12y-29m&(12y-29m)^2+y^2\\\hline0/1&1&12&145\\1/2&2&-5&29\\2/5&5&2&29\\5/12&12&-1&145\\12/29&29&0&841\end{array}

Notice that the approximation improves as we go down the table, but the sum of the two squares does not necessarily decrease. Eventually, the denominator becomes too large. What we want is a convergent for which both the denominator and the integer error are small. Let us see this directly from the continued fraction expansion in our earlier example:

\displaystyle \frac{469}{1009}=[0;2,6,1,1,1,6,2].

The successive convergents are

\displaystyle \frac01,\quad\frac12,\quad\frac6{13},\quad\frac7{15},\quad\frac{13}{28},\quad\frac{20}{43},\quad\frac{133}{286},\quad\frac{286}{615}.

However, we do not need to compute all the convergents. For each fraction m/n , we examine the integer error 469n-1009m . At the convergent 7/15 , we obtain

\displaystyle 469\cdot15-1009\cdot7=-28.

This is the first integer error whose absolute value is smaller than \sqrt{1009} . The denominator is 15 . These are precisely the two integers we are looking for:

\displaystyle 1009=28^2+15^2.

Thus we can obtain the representation directly from the continued fraction expansion of r/p . We compute successive convergents m/n and stop as soon as |rn-pm|<\sqrt p . The answer is then

\displaystyle p=(rn-pm)^2+n^2.

This is really the same calculation as before, written in a different language. The Euclidean remainders are the absolute values of the integer errors, and the coefficients we kept track of are, up to sign, the denominators of the convergents. Continued fractions simply provide a natural way of organizing these two quantities together.

A geometric way to see the same argument

Consider the lattice L=\{(x,y)\in\mathbb Z^2:x\equiv ry\pmod p\} . It is generated by (p,0) and (r,1) , so its fundamental parallelogram has area p . Every lattice point has squared length divisible by p . We only need to find a nonzero point with both coordinates smaller than \sqrt p in absolute value. Why should we expect a short vector in this lattice? The area of a fundamental parallelogram is p . Thus, on average, there is one lattice point for every region of area p . A square of side roughly \sqrt p has this area. This is only a heuristic at present: a fundamental parallelogram could be very thin and long. But we can turn the heuristic into an exact argument by looking at differences of points rather than trying to locate a lattice point directly.

There is a simple pigeonhole argument for this. Put m=\lfloor\sqrt p\rfloor and consider the (m+1)^2>p integer pairs (i,j) with both coordinates between zero and m . Assign to each pair the residue i-rj\pmod p . Two distinct pairs must receive the same residue. Their difference is a nonzero lattice point (x,y) with |x|,|y|\leq m . Its squared length is positive, divisible by p , and smaller than 2p . Hence it equals p . For example, when p=29 and r=12 , consider the thirty-six points with coordinates between zero and five. The points (5,0) and (0,2) both give the residue five, since -24\equiv5\pmod{29} . Their difference is (5,-2) . This is exactly the vector that our Euclidean calculation found.

The argument proves that some collision must occur, but searching for a collision among roughly p pairs is not especially efficient. The Euclidean algorithm avoids that search. The Euclidean algorithm gives a much faster way of finding such a point. At each step we replace a lattice basis by another basis of the same lattice, subtracting an integer multiple of one vector from the other. In the example of twenty-nine, the successive vectors are (29,0),(12,1),(5,-2),(2,5) . The last two are perpendicular and have squared length twenty-nine. We started with long, nearly parallel vectors and ended with a square basis. There is a useful way to connect this geometric calculation with the determinant identity in the proof. At every stage the consecutive vectors (r_{i-1},t_{i-1}) and (r_i,t_i) are a basis of the same lattice. Subtracting a multiple of one from the other is reversible by addition. Their determinant therefore remains equal to p up to sign. What appeared earlier as a cancellation of algebraic terms is simply preservation of area. When the second vector has first coordinate below the threshold, the first vector still has first coordinate above it. Since the second coordinates have opposite signs, the area is the sum of two nonnegative products. In particular, it bounds the product of the larger first coordinate and the new second coordinate. This forces the new second coordinate to be small.

Why a square? The relation r^2\equiv-1\pmod p implies that whenever (x,y) belongs to the lattice, so does (-y,x) . The lattice is invariant under rotation through ninety degrees. Once we find a vector of squared length p , that vector and its rotation enclose a square of area p . This is the area of the original fundamental parallelogram, so the two vectors generate the entire lattice. In the language of Gaussian integers, this is precisely the assertion that the lattice is generated by the single Gaussian integer x+iy . In fact, if v=(x,y) is a vector of squared length p and w=(-y,x) , every lattice vector is uniquely of the form mv+nw with integers m,n . To justify the basis assertion directly, express the two vectors in the original basis. The resulting integer matrix has determinant one up to sign, because both parallelograms have the same area. Its inverse therefore has integer entries. Since the two vectors are perpendicular, we obtain

\displaystyle \|mv+nw\|^2=p(m^2+n^2).

This explains not just the existence of the short vector but also the shape of the entire lattice. The vectors of squared length p correspond precisely to the four choices (m,n)=(\pm1,0),(0,\pm1) . The other root of minus one gives the reflected lattice. Every representation of the prime belongs to one of these two lattices, because neither coordinate can vanish modulo the prime and the ratio of the coordinates is a root of minus one. This proves uniqueness up to signs and interchange.

For completeness, the required modular root always exists: Wilson’s theorem gives (p-1)!\equiv-1\pmod p . Pairing the factors on either side of (p-1)/2 shows that (((p-1)/2)!)^2\equiv-1\pmod p when p\equiv1\pmod4 . Thus the argument also proves Fermat’s theorem. For large primes one can find the modular root by faster modular arithmetic; the Euclidean algorithm then extracts the representation in a logarithmic number of divisions. There is also a more practical way to find the modular root. Choose a nonzero residue g that is a quadratic nonresidue modulo p . Euler’s criterion gives g^{(p-1)/2}\equiv-1\pmod p . Therefore we can take r\equiv g^{(p-1)/4}\pmod p . Half the nonzero residues are nonsquares, so random trials find one quickly on average, and repeated squaring computes the powers efficiently. For example, two is a nonresidue modulo twenty-nine, and 2^7\equiv12\pmod{29} . This recovers the root used in our first example.

It is natural to try the same idea for p=x^2+dy^2 . A square root of -d modulo p again gives a lattice on which the quadratic expression is divisible by p . But now the region x^2+dy^2<2p is an ellipse rather than a circle, and the ninety-degree symmetry is lost when d>1 . There need not be a point representing p itself. For example, minus five is a square modulo three, but three is not represented by x^2+5y^2 . This is where the distinction between different classes of quadratic forms begins to matter. The corresponding generalization of Cornacchia’s procedure is to stop at the first remainder x<\sqrt p and test whether (p-x^2)/d is a nonnegative integer square. For example, for p=29,d=5 , the root 13 satisfies 13^2+5=6\cdot29 . The division 29=2\cdot13+3 gives x=3 , and (29-9)/5=4 gives 29=3^2+5\cdot2^2 . But for p=7,d=5 , the root three gives the remainder one, and (7-1)/5 is not even an integer. There is no representation: if the second coordinate is nonzero, it must have absolute value one, leaving two for the first square. The modular congruence alone is insufficient. This is the point at which the study of different classes of quadratic forms becomes necessary.

Leave a Reply