Computing Legendre Symbols in Practice
Is a perfect square modulo the prime ? Answering this by brute force means checking many residues. We would need to square each of the nonzero residues. We check whether any hits . This is a slow and unenlightening search. The Legendre symbol packages this yes/no question into a single number. This number is . The Law of Quadratic Reciprocity, together with its supplementary laws, changes this. It turns the computation into something closer to the Euclidean algorithm than to trial and error. This matters because quadratic residues sit at a crossroads of number theory. They control which primes appear as sums of two squares. They govern the splitting of primes in quadratic fields. They are also the computational backbone of primality tests. This includes cryptographic protocols such as the Solovay–Strassen test. It also includes the design of quadratic residue codes. Knowing the theory of reciprocity is one thing. Knowing how to wield it is a distinct and essential skill. This means flipping symbols, peeling off powers of two, and reducing arguments modulo the base. This skill is the subject of this article. The big picture is an algorithm, not just a theorem. Reciprocity converts the question "is a square mod ?" into a question about smaller numbers. It does this recursively, in a way that mirrors the Euclidean algorithm's descent by remainders. Every step is justified by The Law of Quadratic Reciprocity and The Supplementary Laws. The recursion terminates because the numerator strictly shrinks (in absolute value) at each reduction. What emerges is an algorithm requiring reciprocity/reduction steps. It is genuinely fast, and hand-computable for primes with a few dozen digits. This article delivers a complete algorithm for evaluating . It includes a rigorous proof that it always terminates and returns the correct value. It also includes two fully worked numerical examples with realistic (non-round) numbers. There is a discussion of exactly where the hypothesis " prime" is used. This discussion also covers what fails without it. Finally, it offers a bridge toward the Jacobi Symbol. This symbol removes the primality restriction on the denominator. It also makes the algorithm even faster in practice.
- The Legendre symbol records whether is a nonzero square mod the odd prime (), a nonresidue (), or ().
- Reciprocity lets you flip and for odd primes , up to a sign determined by .
- The supplementary laws evaluate and directly from and .
- The algorithm: reduce mod , strip out factors of using the second supplement, flip via reciprocity, and recurse — exactly like the Euclidean algorithm.
- Multiplicativity lets you factor the numerator instead of reducing it whole.
- Key idea: turn a search over residues into a handful of reciprocity flips and remainder reductions, just as Euclid turns GCDs into remainder chains.
Where this lives today
The reciprocity algorithm described here is not a historical curiosity — it is the standard method by which computer algebra systems and cryptographic libraries evaluate Legendre and Jacobi symbols, because it avoids integer factorization entirely (via the Jacobi symbol's factorization-free reciprocity) and runs in time comparable to the Euclidean algorithm. It underlies the Solovay–Strassen primality test, a randomized algorithm that checks whether for random , using exactly this fast symbol evaluation. It appears in the construction of quadratic residue codes in coding theory, in the theory of Gauss sums and their role in evaluating certain exponential sums in analytic number theory, and in the arithmetic of quadratic fields , where determines whether a prime splits, is inert, or ramifies. It also shows up in cryptographic schemes based on the quadratic residuosity problem, such as the Goldwasser–Micali encryption scheme, whose security rests on the presumed difficulty of deciding quadratic residuosity modulo a composite without knowing its factorization — precisely the composite-modulus case that the counterexample above shows lies genuinely beyond the reach of the prime-modulus Legendre-symbol algorithm, and which motivates the Jacobi Symbol as a computational tool distinct from a residue-detector.
Ask the tutor: Can you walk me through evaluating step by step using this algorithm?
Let be an odd prime and let . The Legendre symbol is defined by
where is a quadratic residue mod if there exists with . The computational task addressed here is: given an odd prime and an integer with (WLOG, after reducing mod ), compute using only: 1. Reduction: depends only on . 2. Multiplicativity: . 3. The first supplement: . 4. The second supplement: . 5. Quadratic reciprocity: for distinct odd primes ,
The goal is an algorithm avoiding both factorization of large numbers and exhaustive search over residues.
Intuition — descent by remainders
The single most important idea is an analogy with the Euclidean algorithm for . There, one repeatedly replaces by , and the numbers shrink until one hits . Here, one repeatedly replaces the problem "evaluate " by a strictly smaller problem, using three moves in rotation:
- Reduce: replace by (free — the symbol only depends on the residue class).
- Split off 2's: write with odd, and evaluate directly from the second supplement — no recursion needed here, this is a closed form.
- Flip: once the top of the symbol is an odd number , use reciprocity to relate to , which has a smaller modulus .
Because the new modulus satisfies , this process strictly decreases the larger of the two numbers at each flip, exactly as in Euclid's algorithm, guaranteeing termination in flips. The diagram below visualizes one full descent for (worked in full below): each node is a symbol, arrows are labeled by the move used, and the modulus (bottom number) strictly shrinks left to right until we reach a symbol we can read off immediately.
Intuition — squares thin out predictably
It also helps to see, geometrically, that quadratic residues are exactly half of the nonzero residues mod an odd prime , and that this 50/50 split is what makes a single bit of information (the sign) worth tracking multiplicatively. The picture below marks residues mod on a line, with squares (residues of ) highlighted.
Let be an odd prime and an integer. Define the following recursive procedure : 1. If , return . 2. Replace by , with . 3. Write with odd, . 4. If , return . 5. Otherwise, let and recursively compute ; return
Then terminates after at most recursive calls, and
We prove correctness and termination separately, using strong induction on for correctness (the proof technique) and a descent argument for termination.
Setup and well-definedness of each step. Since is prime and after step 2, is coprime to , so ; hence by the reduction property of the Legendre symbol (immediate from the definition: the symbol depends only on modulo , since has the same solution set as when ). Writing with odd is possible and unique for every positive integer . If then , and by multiplicativity,
using the second supplementary law directly (this is a base case, requiring no recursion, valid for any odd prime ). This matches step 4 of the algorithm exactly.
Case . Since is odd, . We do not assume is prime. Instead we use multiplicativity to reduce to a claim about times prime factors — but in fact reciprocity for the Legendre symbol as usually stated requires both entries to be odd primes. We resolve this by first establishing the needed generalization for arbitrary odd coprime to , via multiplicativity over the prime factorization of ; this is standard and we spell it out. Claim (reciprocity for composite odd numerator). For any odd with ,
where denotes the Jacobi symbol (the multiplicative extension of the Legendre symbol to odd moduli , defined as the product of Legendre symbols over the prime factorization , with multiplicity). This claim is precisely the reciprocity law for Jacobi symbols; here we only need the special case needed to drive the recursion, and we verify it reduces correctly to Legendre-symbol reciprocity when is itself prime, which is the only case invoked at each individual step of the algorithm as written (step 5 recurses with , and this recursive call, if is composite, is interpreted as a Jacobi symbol internally — the algorithm remains correct because a Jacobi symbol equal to still certifies is a nonresidue, while if it is used purely as a computational device the final composed product still equals , by the multiplicativity of the Jacobi symbol over the prime factorization of and ordinary Legendre reciprocity applied prime-by-prime). To keep the induction airtight without presupposing Jacobi-symbol machinery (which is introduced only as a forward pointer in this article, not as a prerequisite), we instead prove the theorem by strong induction on for prime at each step, and observe that the algorithm as stated, applied to a general odd numerator , is equivalent to first factoring into odd primes (with multiplicity) and applying multiplicativity:
and then applying genuine Legendre reciprocity to each factor individually. Concretely, for each prime factor of ,
and since (as ), reduction gives , a strictly smaller instance of the same problem because (in fact since after reduction in step 2). Multiplying over :
One checks by direct computation with fixed that whenever is a product of odd numbers — this is the standard "additivity of mod 2 under odd multiplication" lemma, proved by induction on using for odd (itself checked directly: writing , , so ). Hence
matching step 5's sign exactly. This justifies collapsing the product into the single recursive value : by the same multiplicativity and Chinese-Remainder-independent reasoning (each depends only on mod , hence only on reduced further mod , consistent with computing recursively on the pair and having the recursive call itself perform the same factor-and-multiply reduction on ). This is precisely an inductive unfolding: strong induction on , with the inductive hypothesis being " correctly computes for all primes ", applied here with for every prime factor of .
Base case of the induction. The smallest odd prime is . For , the only possible reduced residues are . If : , so , and the algorithm returns by step 4; indeed is a square. If : , , algorithm returns (second supplement with : ); indeed is not a square mod since . Base case verified directly, no recursion needed.
Termination. At each recursive call, the algorithm passes from modulus to modulus where is an odd number satisfying (since divides , in fact , with being the terminating case handled without recursion). Thus the modulus in the recursive chain strictly decreases at every step: , a strictly decreasing sequence of positive integers, hence finite. Explicitly, since and further is odd while the next remainder is again reduced, the sequence of moduli decreases at least as fast as in the Euclidean algorithm for , giving recursive calls by the standard analysis of the Euclidean algorithm's run time (each two steps at least halve the modulus, a classical fact: if then or the next reduction achieves this bound within two steps). Hence terminates after steps, each step doing arithmetic (mod reduction, parity checks, extracting powers of 2), so the total bit-complexity is polynomial in (with schoolbook arithmetic, ; the exact complexity constant is not needed here).
Conclusion. By strong induction on (base case verified; inductive step reduces the problem at modulus to problems at strictly smaller odd primes , correctly assembled via multiplicativity and reciprocity as shown), for every odd prime and every integer .
∎Worked examples
Example 1: Compute . Here is prime (check: not divisible by ; , so trial division up to suffices, and none divide , confirming primality). Step 1: already, and is odd, so . Factor . Step 2 (multiplicativity):
Step 3, evaluate by reciprocity. Both and are odd primes. We have and , so the reciprocity sign is . Thus
Reduce: , so , giving . By the second supplement with : , so . Hence , and
Step 4, evaluate by reciprocity. (even), so the sign regardless of the other factor (even exponent). Thus
Reduce: , so , giving . Factor , so by multiplicativity , since any nonzero Legendre symbol squared is . Second supplement with : (since ), and the rule iff gives . So .
Assemble:
So is a quadratic residue mod . (Sanity check via direct search would require testing up to squares — the algorithm above used only three reciprocity flips and a handful of reductions.)
Example 2: Compute . Here is a well-known prime (it is the largest prime below ; check by trial division up to since — none of divide ). Factor the numerator: . By multiplicativity:
Evaluate . , (even), so sign (exponent even). So
Reduce : , remainder . So . Now flip again: , , sign , so . Reduce , and trivially (1 is always a square). So , hence , hence .
Evaluate . , , sign . Since is even, the product is even, so sign . Thus
Reduce : , remainder . So . Factor , so (odd power, same sign). Second supplement: , i.e. , so . Hence .
Assemble:
So is a quadratic nonresidue mod .
The theorem requires (and, at each recursive step, the modulus) to be an odd prime. Suppose we try to apply the same reciprocity formula naively with a composite modulus, say we attempt to compute "" for by pretending the Legendre symbol and reciprocity apply verbatim with . First, the very definition breaks down: for composite , one can still ask whether has a solution, but the resulting function is not simply -valued in the way that makes multiplicativity and reciprocity work cleanly. Concretely, take and : check all residues mod :
The set of squares mod is ; is not among them, so " is a nonresidue mod " in the naive sense. But now apply the (Jacobi-style) formula one might be tempted to use, treating as if reciprocity's prime hypothesis were unnecessary: pair with the odd prime and attempt
If one further (incorrectly, since is not prime) tried to read as an ordinary Legendre symbol meaning "is a square mod ", direct check of the square list shows is in the list (since and ), so the naive symbol would be . Meanwhile (since ), and by the second supplement with the genuine prime : , so . The product happens to match the predicted sign here — but this apparent agreement is fragile and not a proof of anything, because the object "" as computed here is not the Legendre symbol of the theorem at all (it fails multiplicativity in general: one can find coprime to with the naive residue-indicator not multiplicative, e.g. and are both nonresidues mod — squares are nonzero — yet , which is a residue, so nonresidue nonresidue residue accidentally matches the sign rule only because is a special near-degenerate case). The genuine failure shows up sharply at : squares mod are (from ), so nonzero nonresidues include minus the residues — checking, and are both nonresidues mod (neither appears in ), and , which is a residue — again "accidentally" consistent — but , and is a nonresidue, is also a nonresidue (checking the list, ), while nonresidue times nonresidue should be a residue if a naive sign-multiplicative rule held with only two values ; this failure of the naive indicator to be -multiplicative is the real breakdown, ultimately because for composite with more than 2 prime factors or repeated prime factors, the group is not cyclic (or its squaring map has a kernel of size ), so "is a square" is not captured by a single multiplicative character. This is exactly why the Legendre symbol's clean multiplicative behavior — and hence the entire reciprocity-based algorithm — depends essentially on being prime (so that is cyclic of even order , and squaring has kernel exactly , making the residue/nonresidue split into a genuine index-2 subgroup with a well-defined multiplicative sign character). The Jacobi Symbol fixes this by defining a multiplicative -valued extension via prime factorization of the modulus — but it explicitly is not an indicator of being a square when the modulus is composite, which is precisely the subtlety this counterexample exposes.
Scope, edge cases & common traps
| Situation | What to do | Why |
|---|---|---|
| Return immediately | Legendre symbol convention; not a residue or nonresidue | |
| negative | Reduce mod first, or use via first supplement | Symbol depends only on residue class |
| even | Strip all factors of , apply second supplement once per factor | Avoids reciprocity machinery (which needs odd numerator) |
| Numerator composite and odd | Factor and use multiplicativity, or treat as a Jacobi symbol shortcut | Reciprocity as stated is for two odd primes |
| Modulus composite | Stop — this is the Jacobi symbol's job, not the Legendre symbol's | See counterexample above |
| Large numerator, no known factorization | Use the Jacobi-symbol version of reciprocity (forward pointer) to skip factoring | Jacobi reciprocity holds for any two coprime odd numbers, prime or not |
The mathematician behind it
Origins · 1 minAdrien-Marie Legendre and how this was discovered
Legendre worked across number theory, elliptic integrals, celestial mechanics, and statistics (he is a co-discoverer of the method of least squares). His 1798 treatise Essai sur la théorie des nombres introduced the symbol that bears his name and stated the law of quadratic reciprocity, though his proof had gaps that were only fully closed by Gauss, who gave the first complete proof in 1801 and went on to publish eight distinct proofs over his lifetime, regarding reciprocity as the "golden theorem" (aureum theorema) of arithmetic.
Why do we require to be prime in the Legendre symbol, rather than any odd modulus?
The Legendre symbol's key algebraic property — being a ±1-valued multiplicative character, satisfying and correctly detecting squares — relies on being a cyclic group of even order . In a cyclic group of even order, the squaring map has kernel exactly , so squares form a subgroup of index exactly , giving a clean quadratic-residue/nonresidue dichotomy. For composite moduli, need not be cyclic, and the kernel of squaring can have more than two elements, so "is a square mod " is no longer captured by a single sign character. The Jacobi Symbol is a genuinely different, purely computational, multiplicative extension.
Is the reciprocity algorithm actually faster than checking all residues by brute force?
Yes, dramatically. Brute force checks up to candidate square roots, which takes time exponential in (linear in itself). The reciprocity algorithm needs only flips and reductions, each a cheap arithmetic operation, giving total time polynomial in — comparable to the Euclidean algorithm's efficiency for computing . For a -digit prime, brute force is utterly infeasible, while the reciprocity algorithm finishes in well under a second.
What happens if I need to compute a Legendre symbol where the numerator is hard to factor?
This is exactly the situation the Jacobi Symbol is designed for. Jacobi symbol reciprocity holds for any two coprime odd positive integers, not just primes, so you can flip (treated formally as a Jacobi symbol during the computation) without ever factoring . You only need to know that the final denominator, at the very last step, is prime, to correctly interpret the final as a genuine residue/nonresidue statement.
Does guarantee is a residue, or could it be a false positive?
For prime , if and only if is a genuine nonzero quadratic residue mod — there are no false positives, because the Legendre symbol is defined directly from that dichotomy and the algorithm is proved to compute it exactly. This certainty is special to prime moduli; for the Jacobi symbol with composite modulus, does not guarantee is a square mod — it only guarantees a is a square modulo an even number of the prime factors (in a suitable multiplicative sense), which is a weaker statement.
How does the first supplementary law fit into the algorithm if is negative?
If , first reduce modulo to land in , or equivalently write and use multiplicativity: , evaluating via the first supplement ( if , if ) and continuing the algorithm on . Both routes give the same answer since they differ only in bookkeeping.
Can this algorithm be extended to prime powers or general composite moduli directly?
Not directly with the Legendre symbol, which is only defined for prime moduli by the standard convention. For odd prime powers , residuosity is governed by Hensel's lemma: coprime to is a square mod iff it is a square mod (for odd), so the Legendre symbol computation at the base prime already answers the question. For general composite , one must check residuosity modulo each prime power factor separately via the Chinese Remainder Theorem; the single-symbol shortcut of the Legendre/Jacobi framework does not by itself decide residuosity mod composite without that extra factorization step.
Why does the algorithm's runtime resemble the Euclidean algorithm so closely?
Because the core recursive step — replace by where is the odd part of — literally is a variant of the Euclidean remainder sequence, with the extra bookkeeping of tracking sign flips at each step. Both algorithms terminate because the pair of numbers involved forms a strictly decreasing sequence of positive integers bounded below by , and both enjoy the same logarithmic bound on the number of steps, provable by the same "modulus roughly halves every two steps" argument.