Sums of squares
Which numbers are sums of two squares, of three, of four? Fermat, Legendre and Lagrange answered each, and Jacobi counted the ways. Every representation of n as a sum of two squares comes out of the factorisation of n in the Gaussian integers.
Two squares
Fermat: an odd prime is a sum of two squares exactly when . To find them, take with and run Euclid's algorithm on and ; the first remainder below is , and is a square (Cornacchia, Brillhart).
A number is a sum of two squares exactly when every prime divides it to an even power.
import { primeAsTwoSquares, twoSquaresAll, twoSquaresReason, r2, threeSquares, fourSquares, r4, pythagoreanTriples } from "@ratmath/numtheory";
primeAsTwoSquares(13); // [3n, 2n]
primeAsTwoSquares(1000000009n); // [31400n, 3747n]
twoSquaresAll(325); // [[18n, 1n], [17n, 6n], [15n, 10n]]
twoSquaresReason(21); // { possible: false, reason: "3 ≡ 3 (mod 4) divides 21 to the odd power 1" }
r2(325); // 24n: with signs and order
Why: in the Gaussian integers , . A prime splits as , a prime stays prime, and . So the elements of norm are found by choosing, for each with , how many of the factors are and how many . Counting the choices gives Jacobi's formula
(when no prime appears to an odd power), with the number of divisors . gives .
Three squares and four
Legendre and Gauss: is a sum of three squares unless . Lagrange: every is a sum of four. Jacobi again counts:
threeSquares(30); // [5n, 2n, 1n]
threeSquares(28); // null: 28 = 4·7
fourSquares(112); // [8n, 4n, 4n, 4n]: 112 = 16·7 needs four
r4(12); // 96n
rk(10, 8); // 14112n: r₈(10), by multiplying out the theta series
rk counts directly as the coefficient of in , , which is also how the tests check the formulas.
Pythagorean triples
Every primitive triple with odd is , , for coprime of opposite parity (Euclid). Read in : . So the triples with hypotenuse are the representations of as a sum of two squares, and those with leg come from factoring .
pythagoreanTriples(30); // [[3n, 4n, 5n], [5n, 12n, 13n], [15n, 8n, 17n], [7n, 24n, 25n], [21n, 20n, 29n]]
triplesWithHypotenuse(65); // [[16n, 63n, 65n], [25n, 60n, 65n], [33n, 56n, 65n], [39n, 52n, 65n]]
triplesWithLeg(12); // [[12n, 5n, 13n], [12n, 9n, 15n], [12n, 16n, 20n], [12n, 35n, 37n]]
@ratmath/numtheory and Core's Rational in scope. The last line's value is shown; PRINT(…) adds lines, TEX(…) typesets math.