Quadratic reciprocity
Which numbers are squares modulo p? Euler's criterion answers it with one power, and Gauss's law of quadratic reciprocity answers it faster, by turning the question upside down until it is trivial. The steps can be shown, line by line.
Residues and the Legendre symbol
For an odd prime and , is a quadratic residue when has a solution. Exactly half of the nonzero residues are. The Legendre symbol is for a residue, for a non-residue and when , and Euler's criterion computes it:
import { legendre, jacobi, jacobiSteps, eulerCriterion, gaussLemma, quadraticResidues, sqrtsMod } from "@ratmath/numtheory";
quadraticResidues(11); // [0n, 1n, 3n, 4n, 5n, 9n]
legendre(2, 7); // 1: 3² = 9 ≡ 2
eulerCriterion(3, 7); // { power: 6n, value: -1 }: 3³ = 27 ≡ −1 (mod 7)
gaussLemma(3, 11); // { value: 1, mu: 2, large: [6n, 9n] }
Gauss's lemma counts instead: among reduced into , let be how many exceed . Then . For , the residues are 3, 6, 9, 1, 4, and two of them are large.
The law of quadratic reciprocity
For distinct odd primes :
so the two symbols agree unless both primes are . With the two supplements and exactly when , any symbol can be computed like a gcd: reduce the top, pull out factors of 2, flip. The Jacobi symbol for odd obeys the same rules, so the flips never need a factorisation. (A Jacobi symbol of 1 does not mean is a square mod ; a value of −1 does mean it is not.)
jacobiSteps(1001, 9907).steps;
// (1001/9907)
// = (9907/1001) reciprocity: one of them is 1 mod 4, so the sign stays
// = (898/1001) reduce the top mod 1001
// = (449/1001) take out 2: (2/1001) = 1 since 1001 ≡ 1 (mod 8)
// …
// = −(1/29) take out 2^3: (2/29) = −1 since 29 ≡ 5 (mod 8)
// = −1
The Kronecker symbol extends the Jacobi symbol to every bottom: is 0 for even , 1 for , −1 for , and is the sign of . It is the character attached to a quadratic field, which is how it appears in class number formulas.
Square roots modulo n
Modulo a prime, Tonelli–Shanks finds a root in a few powers (from algebraic's sqrtMod). Modulo a composite, find the roots modulo each prime power by Hensel lifting and combine them: so there can be many.
sqrtsMod(1, 15); // [1n, 4n, 11n, 14n]
sqrtsMod(4, 32); // [2n, 6n, 10n, 14n, 18n, 22n, 26n, 30n]
sqrtsMod(-1, 65); // [8n, 18n, 47n, 57n]
@ratmath/numtheory and Core's Rational in scope. The last line's value is shown; PRINT(…) adds lines, TEX(…) typesets math.