Number

The two squares actually produced

Three proofs say a prime one more than a multiple of four is a sum of two squares, and not one of them hands over the squares. Running the Euclidean algorithm half-way does — and where to stop is the whole of the correctness argument.

Worth reading first: Two squares, and a lattice.

The circle on the lattice gives three proofs that a prime one more than a multiple of four is a sum of two squares, and it is worth noticing what each of them leaves on the table.

Euler’s descent shrinks a multiple of pp until the multiplier is one, which does terminate and does produce the squares — slowly, and only after an arbitrary starting multiple has been found. Minkowski’s lattice argument says a disc of the right area must contain a non-zero lattice point, which is a statement about area and names no point. Zagier’s involution counts a set’s parity and deduces that a second involution has a fixed point, which exhibits nothing at all.

1000710007 is not a sum of two squares; 1000910009 is. Which two?

The two squares of 97, produced by division. A table of the division chain on 97 and a square root of minus one modulo it, with each row's quotient and remainder, the point at which the remainder falls below the square root marked, and the two squares that add to 97.
Fig. 1 The computation for 9797. A square root of 1-1 modulo 9797 is 7575; dividing 9797 by it and continuing gives remainders 2222, 99; the ruled line is 97\sqrt{97}; and the first remainder below it is 99, whose partner is 44. Eighty-one and sixteen.

Two divisions. The algorithm is Cornacchia’s, from 1908, and the surprising part is not that it is short but where it stops — the rule take the first remainder below the square root is not an optimisation, it is the entire correctness proof compressed into a comparison.

What has to be found first

The chain needs a number ss with s21(modp)s^2 \equiv -1 \pmod p, and finding one is the only step with any cost in it.

Such an ss exists exactly when p1(mod4)p \equiv 1 \pmod 4, which is the fact the two-square theorem rests on: the numbers modulo a prime form a cyclic group of order p1p-1, and an element of order four exists precisely when four divides p1p-1, which is the cyclic structure a generator’s powers run through used for the one thing it is most often used for. Its square has order two, and the only element of order two is 1-1.

Producing one is a different matter. The standard route takes any aa that is not a square modulo pp and computes a(p1)/4a^{(p-1)/4}, which squares to a(p1)/2=1a^{(p-1)/2} = -1 by Euler’s criterion. Testing whether a given aa is a non-residue is fast; half of all aa work; so a handful of tries suffice, and the figures here do exactly that.

That is the only randomised step in the whole computation, and it is worth flagging because it is where the practical difficulty of the problem actually sits. Everything after it is division.

Why stopping there is the proof

The chain is run on pp and ss, and the claim is that the first remainder below p\sqrt p is one of the two squares’ roots. Here is why.

Write xx for that remainder and yy for the value of the remainder above it reduced against xx — equivalently, y=px2y = \sqrt{p - x^2}, which the algorithm’s correctness is the claim about. The relation that carries down the chain is the one the congruence started from: every term is congruent to ±s\pm s times the next, modulo pp, because each is obtained from the two before by subtracting a multiple. So

x±sy(modp),hencex2+y2s2y2+y2=(s2+1)y20(modp).x \equiv \pm\, s\,y \pmod p, \qquad \text{hence} \qquad x^2 + y^2 \equiv s^2y^2 + y^2 = (s^2+1)y^2 \equiv 0 \pmod p.

So x2+y2x^2 + y^2 is a multiple of pp at every stage. The only question is which multiple, and that is where the size condition comes in: once both xx and yy are below p\sqrt p, the sum x2+y2x^2 + y^2 is below 2p2p and positive, so the only multiple of pp it can be is pp itself.

That is the whole argument, and the figures check both halves of it: the answer is required to satisfy the congruence, and the row above the stopping line is required not to work — pp minus its square is not a square, so stopping one step early would produce nothing.

The two squares of 1009, produced by division. A table of the division chain on 1009 and a square root of minus one modulo it, with each row's quotient and remainder, the point at which the remainder falls below the square root marked, and the two squares that add to 1009.
Fig. 2 A longer chain, for 10091009. Four divisions before the remainder falls past 100931.8\sqrt{1009} \approx 31.8, and the answer is 152+28215^2 + 28^2. The number of steps is the number of steps the Euclidean algorithm takes on a pair of that size — logarithmic, and in practice about one step per digit and a half.
The two squares of 3001, produced by division. A table of the division chain on 3001 and a square root of minus one modulo it, with each row's quotient and remainder, the point at which the remainder falls below the square root marked, and the two squares that add to 3001.
Fig. 3 And for 30013001, where the chain runs one step longer and ends at 2424 and 3535. Nothing about the length of the chain depends on the answer; it depends on the continued-fraction expansion of s/ps/p, which is a fact about the square root of 1-1 that was found rather than about the prime.

The same thing as a lattice

Minkowski’s proof draws a lattice and says a short vector must exist. This algorithm produces it, and seeing the two as one object is the reason both belong in this family.

The lattice of 29, shortened until its shortest vector appears. A patch of the sublattice whose points satisfy a congruence modulo 29, with the circle of radius the square root of 29 drawn and the shortest non-zero lattice point marked on it.
Fig. 4 The lattice of points (a,b)(a, b) with bsa(mod29)b \equiv s a \pmod{29}, drawn over the ordinary grid. One point in every 2929, so its cell has area exactly 2929; the circle has radius 29\sqrt{29}; and the marked vector is the shortest non-zero point, at squared length 2929. A lattice point at squared distance 2929 from the origin is a pair of squares adding to 2929.

Take the sublattice generated by (1,s)(1, s) and (0,p)(0, p). Its points are exactly those with bsab \equiv sa, its fundamental cell has area pp, and every one of its points has a2+b20(modp)a^2 + b^2 \equiv 0 \pmod p by the computation of the last section. So a non-zero point at squared distance below 2p2p is a representation of pp, and Minkowski’s theorem says one exists.

Gauss reduction finds it. Start with the two generators; repeatedly subtract from the longer the nearest multiple of the shorter; stop when neither shortens the other. What remains is a shortest vector, and in two dimensions the procedure is exact rather than approximate — a fact that fails in three dimensions and fails badly in high ones, which is the whole difficulty of lattice-based cryptography.

The lattice of 97, shortened until its shortest vector appears. A patch of the sublattice whose points satisfy a congruence modulo 97, with the circle of radius the square root of 97 drawn and the shortest non-zero lattice point marked on it.
Fig. 5 The same construction for 9797, where the lattice is sparser and the shortest vector lands at (9,4)(9, 4) — the pair the division chain produced at the top of this essay. The two computations have nothing in common to look at and are the same arithmetic.

The two are the same because a step of Gauss reduction is a step of the Euclidean algorithm. Subtracting qq copies of the shorter vector from the longer changes its first coordinate from aa to aqba - qb, which is the division step, and the rounding that chooses qq is the floor. So the chain of remainders in the table and the chain of shortening vectors in the lattice are one sequence, written in two notations, and the stopping rules match: the division chain stops when the remainder is below p\sqrt p, and the reduction stops when the vector is short enough that nothing shortens it.

The figures check that the area is pp at every intermediate basis, which is the invariant a reduction preserves — and is the quantity Minkowski’s theorem is about.

The other square root, and the same answer

There are two square roots of 1-1 modulo pp, namely ss and psp - s, and the chain behaves quite differently on them — which is worth knowing, because it is the one place the algorithm as usually stated has a convention that looks arbitrary and is not.

For 9797 the two are 2222 and 7575. Run the chain on 7575 and the remainders are 2222, then 99, and the answer is 92+429^2 + 4^2. Run it on 2222 and the first remainder is already below 97\sqrt{97} before any division has happened, so the rule stop at the first remainder below the square root fires immediately and returns 2222 itself, which is above 97\sqrt{97} and not a solution.

The convention is therefore to take the larger root, and the reason is the size argument rather than taste: the proof needs both xx and the term before it to be handled, and starting below p\sqrt p means the chain has not yet done the work the bound is about. A version that starts anywhere and stops at the first small remainder is wrong on about half its inputs, and wrong in a way that produces a number rather than an error.

That is a small instance of the recurring hazard in this collection: a stopping rule read as an optimisation rather than as the argument. The rule here is the argument, and moving it one step in either direction breaks it — one step later and both terms are small enough that the multiple could be zero, one step earlier and the sum is above 2p2p and the multiple could be two.

Set against descent, run rather than quoted

Euler’s descent is the oldest of the three proofs, and it is worth putting the two computations beside each other, because the comparison says what the algorithm bought.

Descent starts from any multiple mp=a2+b2m p = a^2 + b^2 with mm below pp — one is available from s2+1=mps^2 + 1 = m p directly — and manufactures a smaller multiplier from it by reducing aa and bb modulo mm into the range ±m/2\pm m/2 and dividing. Each step at least halves the multiplier, so it terminates in about logp\log p steps, which is the same order as the division chain.

So descent is not slow. What it is, is fiddly: each step needs a symmetric reduction, a division that must come out whole, and a check that the multiplier really fell. The division chain does the same work with a single while loop and a comparison, and the reason is that it never carries the multiplier at all — the congruence does the bookkeeping that descent does by hand.

The kinship is not superficial. Descent’s reduction step is a subtraction of the nearest multiple, which is what the Euclidean algorithm does to a rectangle and what Gauss reduction does to a basis. Three descriptions, one operation, and the one that is easiest to run is the one that keeps the least state.

What it costs, and what that is good for

The whole computation is one square root modulo pp followed by a Euclidean chain, so it is fast in the sense that matters: the number of divisions is proportional to the number of digits, and each division is on numbers no larger than pp.

That has a consequence worth stating, because it is easy to assume the opposite. Representing a prime as a sum of two squares is easy, and factoring a number is hard. Those two facts sit uncomfortably close together, since a number with two essentially different representations is composite and gives its factors — so if representations were easy to find for composites, factoring would be easy.

The resolution is that the algorithm above needs ss, and finding a square root of 1-1 modulo a composite nn is exactly as hard as factoring nn. Given such an ss, gcd(s2+1,n)\gcd(s^2+1, n) splits nn immediately. So the easy step and the hard step are cleanly separated: the arithmetic of the chain is cheap, and the ingredient it needs is the whole difficulty.

That pattern recurs through computational number theory, and this is its smallest instance. The same square root modulo pp is what the Tonelli–Shanks algorithm computes for general residues; it is the reason a ring can factor uniquely and still be hard to factor in; and it is the step that makes primality testing and factoring such different problems despite being about the same objects.

Where the answer is used

Modular square roots, everywhere. The one expensive ingredient here — a square root modulo a prime — is the same subroutine that decompresses an elliptic-curve point from its x-coordinate, that decides whether a quadratic congruence has a solution, and that sits underneath half the constructive results in this field. Its cost is a modular exponentiation, which is to say it is cheap and is still the dominant term.

Elliptic-curve point counting. The number of points on a curve over a field of pp elements, for curves with extra structure, is given by p+1ap + 1 - a where aa is read off a representation 4p=a2+b2d4p = a^2 + b^2 d — the two-square computation with a coefficient. Producing those representations is what Cornacchia’s algorithm is usually running for in a modern library.

Gaussian integer factorisation. Factoring an ordinary integer in Z[i]\mathbb{Z}[i] means splitting each prime 1(mod4)\equiv 1 \pmod 4 into (a+bi)(abi)(a+bi)(a-bi), which needs the same aa and bb. Nothing else is required, since primes 3\equiv 3 stay prime and 22 ramifies.

And sums of four squares. Lagrange’s theorem says every number is a sum of four squares, and the standard constructive proof runs a descent whose base case is the two-square computation. Rabin and Shallit’s randomised algorithm for it, from 1986, is built on exactly this chain.

Why two dimensions is where this works

The lattice reading raises a question it is worth answering, because the answer explains why the two-square theorem has a clean algorithm and its natural generalisations do not.

Gauss reduction finds a genuinely shortest vector, and in two dimensions that is exact: the procedure terminates with a basis whose first vector is shortest in the whole lattice, and the proof is a page. In three dimensions there is a similar procedure and it is already harder. In high dimensions finding a shortest lattice vector is NP-hard, and the best general algorithms take exponential time; the workhorse approximations, of which LLL from 1982 is the first, return a vector within an exponential factor of shortest and are enormously useful precisely because nothing better is available.

So the picture in the two lattice figures is the last dimension in which it is easy. That is not a curiosity about this essay’s subject; it is the reason the hardness of lattice problems is now the standard foundation for cryptography meant to survive quantum computers, and the two-dimensional case is the toy that shows what the hard problem is a version of.

It also explains the shape of the generalisations. Representing pp by x2+ny2x^2 + n y^2 for other nn is the same lattice question with a different quadratic form, and Cornacchia’s algorithm handles it by the same chain with the stopping bound changed — because the lattice is still two-dimensional. Representing a number by a form in four variables, as Lagrange’s theorem does, is a four-dimensional lattice question and has no comparably clean method; the constructive proofs there descend instead, one square at a time.

Six instances, and a claim about every prime

Every figure is one prime. The algorithm’s correctness is a statement about all p1(mod4)p \equiv 1 \pmod 4, and the four tables and two lattices here are six instances. What each figure does check is that this instance’s answer satisfies the congruence and that stopping one step early would fail — which is the shape of the argument tested at a point, not the argument.

The square root of 1-1 arrives without explanation. Both views take ss as given and neither shows how it was found. The search for a non-residue is a loop with no geometry in it, and drawing it would be drawing a list of failed tests.

The lattice pictures are drawn at small primes for a reason that undermines them. At 2929 the lattice is visibly sparse and the shortest vector is visibly short. At 1000910009 the same picture has one lattice point in every ten thousand grid points and cannot be drawn at all at a scale where the circle is visible — so the figures show the mechanism exactly where the mechanism is unnecessary, and are silent at the sizes anybody would run it.

And neither view shows the second representation. The circle of radius p\sqrt p passes through eight points, being the four sign choices on two coordinates and the swap; the algorithm returns one and the others are relabellings. For a composite with two genuinely different representations — the case that factors it — this chain returns only the one its ss leads to.

Still open here: producing what the counting formula counts

Jacobi’s formula says exactly how many lattice points sit on the circle of radius n\sqrt n, for every nn, by counting divisors. That is a count and not a list, and this essay has produced one point of the list for a prime.

The general problem — list every representation of an arbitrary nn — reduces to factoring nn and then multiplying the prime representations together in the Gaussian integers, where the sign choices at each prime give the whole list. So it is exactly as hard as factoring, and the counting formula computes without any of that work how many answers there are. A formula that says how many and cannot say which is the standing shape here, and it is the same gap Frobenius’s count of coverings has in a completely different subject.

An existence proof, and the thing it does not contain

The habit is worth stating because it is easy to be satisfied too early.

Three proofs of the two-square theorem are on record and all three are complete. Not one of them can be run. Descent needs a starting multiple and shrinks slowly; Minkowski’s argument is about area and names nothing; Zagier’s is a parity count that proves a fixed point exists without locating it.

An existence proof and a construction are different objects, and the gap between them is sometimes the whole subject. Here it is one line of division, and the line is short enough that the difference looks unimportant. In the design theory that settled existence asymptotically the gap is still open, and in factoring it is the gap that cryptography is built on.

The question to ask of any existence theorem is what would have to be added to make it run — and then whether that addition is a detail or is the problem.

Reads more easily once this is understood

Essays that name this one as worth reading first.

Shares its objects with

Essays that name at least two of the same things, and that neither author linked.

Named objects

A dashed tag is an object no other essay names yet.

DescentEuclidean algorithmGaussian integersLatticeModular arithmeticNormSums of two squares