The witness method — randomly hunt an element proving a property: primality (Fermat → Miller–Rabin → Solovay–Strassen), plus witnesses for Boolean matrix products rebuilding all-pairs shortest paths.
Last updated 27 June 2026
Lecture 4 (part 3) — Witnesses (svedkovia)
Course 2-INF-135/15 Pravdepodobnostné algoritmy, LS 2025/26.
Source slides: 04_metody456.pdf, slides 20–45 (the witness method).
Part 1 was eliminating the adversary; part 2 was fingerprints. This is the
fourth method — witnesses, and its two big customers: primality testing
and all-pairs shortest paths via fast matrix multiplication.
Where we are: the fourth method
The catalogue from part 1 listed six design methods. We have done eliminating the
adversary (online problems) and fingerprints (Freivalds, hashing, matching). Now:
Witnesses (svedkovia). To decide whether an object has a property, randomly
hunt for a witness — a small certificate that, if found, proves the property,
and whose validity is easy to check.
The whole method lives or dies on one number: how dense are the witnesses? If a
constant fraction of candidates are witnesses, random sampling finds one fast. The
mathematical work in this lecture is almost entirely proving that witnesses are dense
— and the recurring tool for that is Lagrange’s theorem (a proper subgroup has at
most half the elements).
1. The witness method, abstractly
We have a universe of candidates and want to test object O for a property P.
A witness is a candidate a such that the pair (O,a) carries an efficiently
checkable proof that O has property P.
Three requirements turn this into an algorithm (slides 21, 24):
Easy to verify a candidate: given a, deciding “is a a witness for O?” is
efficient.
Witnesses are dense: the ratio (candidates : witnesses) is a constant — so a
random candidate is a witness with constant probability.
Efficient access to candidates: we can sample one uniformly at random.
The algorithm is then trivial:
Pick a candidate a at random. Check if it is a witness.
Witness found → report “O has property P” — this is certain.
No witness → report “O probably does not have P.”
Punchline — this is exactly the co-RP / one-sided-error shape from Lecture 3.
A found witness is gospel (no false positives). The only error is failing to find
a witness that exists — a false negative. Repeat with r fresh candidates: if
witnesses have density ≥21, the chance of missing one r times is
≤2−r. Amplification is free.
For primality the property will be “n is composite”, and a witness for n being
composite is what the next sections build, step by step, fixing each failed attempt.
2. The number-theory toolbox (slide 22)
Everything below runs on four classical facts. Keep them on a card.
Little Fermat (malá Fermátová veta). If p is prime and $a \in \mathbb{Z}_p^* =
{d : \gcd(d,p)=1}$, then
ap−1≡1(modp).
Chinese Remainder Theorem, version I. If m=m1⋯mk with the mi
pairwise coprime, then any tuple of residues (r1,…,rk) corresponds to a
uniquer∈Zm with r≡ri(modmi).
Chinese Remainder Theorem, version II (the one we actually use). If n=p⋅q
with gcd(p,q)=1, then the ring Zn is isomorphic to
Zp×Zq:
a⟷(amodp,amodq),
and addition/multiplication act coordinatewise. Reading a number by its two
“coordinates” mod p and mod q is how we will construct witnesses by hand.
Lagrange’s theorem. For a subgroup H of a finite group A,
∣A∣=IndexH(A)⋅∣H∣,
so ∣H∣divides∣A∣. In particular a proper subgroup has index ≥2, hence
∣H∣≤∣A∣/2.
Why Lagrange is the hero of this lecture. Almost every “witnesses are dense”
theorem has the same skeleton: the non-witnesses form a proper subgroup of
Zn∗. By Lagrange that subgroup has ≤∣Zn∗∣/2 elements,
so at least half the group are witnesses. Density ≥21 falls out of
group theory, not of any delicate counting.
3. Attempt 0 — the divisor witness (and why it fails)
The naive definition: n is prime iff its only divisors are 1 and n. So a
divisora∣n with 1<a<n is a perfectly valid witness that n is
composite — and trivially checkable.
The problem is requirement 2 (density). Take the hardest composites, n=p⋅q
with p,q≈n (RSA-shaped numbers). Among the n−1 candidates there are
only a handful of divisors. The witness density is ≈1/n, astronomically
far from constant. Random sampling would never hit one.
Lesson. Divisors prove compositeness but are far too rare. We need a different,
denser notion of witness for the same property. The rest of §4–§9 is the search for
one.
4. Attempt 1 — the Fermat witness (and the Carmichael catastrophe)
Little Fermat says: if n is prime, then an−1≡1(modn) for everya∈Zn∗. Contrapositive:
a is a Fermat witness for “n composite” if an−1modn=1.
If we ever see an−1≡1, then ncannot be prime — certain proof.
It is efficient to test (iterated squaring / opakované umocňovanie). We never form
an−1 as an integer; we reduce mod n after every squaring:
a2modn,a2kmodn=[(a2k−1modn)2]modn,
and for n−1=∑ibi2i−1 we multiply together the a2i−1 with bi=1.
That is O(logn) multiplications in Zn, i.e. O((logn)3)bit
operations. Cheap.
The catastrophe: Carmichael numbers (Carmichaelove čísla). There exist compositen for which
an−1≡1(modn)for all a coprime to n.
The smallest is 561=3⋅11⋅17. For such n the Fermat test has no
witnesses at all among coprime a — density 0, requirement 2 dead. (There are
infinitely many Carmichael numbers, so this is not a finite annoyance we can table.)
Punchline. Fermat’s test is fast and one-sided but not robust: Carmichael
numbers are composites that the test cannot distinguish from primes. We need a
witness that survives even them. Two routes do it: looking at square roots of 1
(Miller–Rabin, §6) and the Jacobi symbol (Solovay–Strassen, §7).
5. The fix’s foundation — an algebraic characterization of primes (slides 25–26)
The escape is to test not an−1 but its square roota(n−1)/2.
Theorem (alternative definition of a prime). For odd p>2,
p is prime⟺a(p−1)/2modp∈{1,p−1}∀a∈Zp∖{0}.
Proof sketch.
(⇒) Write p=2p′+1. By Fermat ap−1−1≡0, and over the
fieldZp we may factor
ap−1−1=(a(p−1)/2−1)(a(p−1)/2+1)≡0(modp).
A field has no zero divisors, so one factor vanishes: a(p−1)/2≡±1, i.e.
∈{1,p−1}.
(⇐) Suppose the property holds for all x=0 but p=ab were a proper
factorization. Then $0 \equiv p \equiv (ab)^{(p-1)/2} = a^{(p-1)/2}b^{(p-1)/2}
\in{1,-1}\pmod p$ — contradiction, since 0∈/{1,−1} mod p. □
The number a(n−1)/2 is a square root of an−1. For a prime it must be one of the
trivial roots of unity ±1. Composites can have other roots — and those other
roots are the new, denser witnesses.
6. The clean case n≡3(mod4) — and the density engine (slides 25, 27, 28)
For the special shape n≡3(mod4) the witness is simply: a(n−1)/2 landing
outside{1,n−1}.
Theorem. For n≡3(mod4):
if n is prime, then a(n−1)/2modn∈{1,n−1} for all a;
if n is composite, then a(n−1)/2modn∈/{1,n−1} for more than
half of a∈{1,…,n−1}.
So define the witness set and its complement (the “liars”):
Wit={a:a(n−1)/2modn∈/{1,n−1}},Euler={a:a(n−1)/2modn∈{1,n−1}}.
Why ∣Wit∣≥∣Euler∣ — the injection argument. This is the
heart, and it is beautiful. Suppose we have one witness b∈Wit (we
construct one below). Define
hb:Euler→Wit,hb(a)=a⋅bmodn.
It lands in Wit. Since a∈Euler, a(n−1)/2≡±1, so
(ab)(n−1)/2=a(n−1)/2b(n−1)/2=(±1)b(n−1)/2.
As b(n−1)/2∈/{1,−1}, multiplying by ±1 keeps it outside {1,−1}.
Hence hb(a)∈Wit. ✓
It is injective. If a1b≡a2b(modn), multiply by b−1 (exists
because b∈Zn∗): a1≡a2. ✓
An injection Euler↪Wit gives $|\mathrm{Euler}|\le
|\mathrm{Wit}|, so witnesses are **at least half** of $\mathrm{Euler}\cup\mathrm{Wit}.
This is the Lagrange idea in disguise. Multiplying by a fixed b is a “coset
shift”: it maps the liars injectively onto (part of) the witnesses, so the liars can
be at most half. One real witness ⇒ a flood of them.
Constructing one witness b (slide 28). Let n=p⋅q with gcd(p,q)=1. By
CRT II read every a as a pair (amodp,amodq). Members of Euler map
to (1,1) or (p−1,q−1)=(−1,−1). Now defineb by its coordinates
b⟷(1,q−1)=(1,−1).
Then b(n−1)/2↔(1(n−1)/2,(−1)(n−1)/2)=(1,−1), which is neither(1,1) nor (−1,−1) — so b∈/Euler, i.e. b∈Wit. (Bonus: b
is its own inverse, since (1,−1)⊙(1,−1)=(1,1).) The witness exists; the injection
fires; density ≥21. □
The catch: this only covers n≡3(mod4). The two real algorithms remove that
restriction.
7. Miller–Rabin — square roots of unity for alln (slide 23)
Miller–Rabin upgrades the Fermat test with one extra idea: a nontrivial square root
of 1 betrays a composite. In a field, the only solutions of x2≡1 are
x≡±1. So if we ever find x with x2≡1(modb) but x≡±1,
then b is not a field, hence not prime.
Write b−1=2t⋅(odd), i.e. 2t∣(b−1) and 2t+1∤(b−1). The chain
of repeated square roots is
a(b−1)/2,a(b−1)/4,…,a(b−1)/2t.
Miller–Rabin test. Input: odd b>2, rounds r.
Find t with 2t∥(b−1).
Repeat r times:
pick a∈{1,…,b−1} at random;
if some x∈{a(b−1)/2,…,a(b−1)/2t} has x2≡1 and
x≡±1(modb) → return “b is composite”(nontrivial root of 1);
if ab−1≡1(modb) → return “b is composite”(Fermat witness);
return “b is probably prime.”
It catches both failure modes — Fermat witnesses and nontrivial square roots — and the
second kind even nails Carmichael numbers, which the pure Fermat test missed.
Guarantee. If b is composite, then
aPr[a is a witness]≥21,
so r independent rounds give error ≤(1/2)r.
Cost.O(rm3) for an m-bit b. For m=340 (≈ 100 decimal digits) and r=50:
rm3≈2⋅109 operations, error 2−50≈10−15. This is the
primality test used in practice.
8. Solovay–Strassen — the Jacobi symbol for alln (slides 29–34)
A second route to a witness for all odd n, historically first, built on quadratic
residues.
Legendre symbol (for prime p, gcd(a,p)=1):
(pa)={+1−1a is a quadratic residue mod p,a is a non-residue.Euler:(pa)=a(p−1)/2modp.
Jacobi symbol (for odd n=p1k1⋯pℓkℓ, gcd(a,n)=1):
(na)=i=1∏ℓ(pia)ki=i=1∏ℓ(a(pi−1)/2modpi)ki.
The crucial efficiency fact. The Jacobi symbol can be computed without factoring
n — by reciprocity rules (slide 30) that look exactly like a Euclidean GCD: each
step at least halves a parameter, so depth O(logn) and total O((logn)3) bit
operations. The rules are
(nab)=(na)(nb),(na)=(nb) if a≡b,(n2)=(−1)(n2−1)/8,(an)(na)=(−1)2a−12n−1.
Solovay–Strassen witness.a is a witness for “n composite” if either
gcd(a,n)=1,orgcd(a,n)=1and(na)=a(n−1)/2modn.
Theorem. For odd n≥3:
if n is prime, then (na)=a(n−1)/2modn for everya (this is exactly Euler’s criterion);
if n is composite, then (na)=a(n−1)/2modn for at
least half the a with gcd(a,n)=1.
The density proof is the Lagrange/subgroup argument again. Let the non-witnesses be
Witn={a∈Zn∗:(na)=a(n−1)/2modn}.
This set is closed under multiplication (slide 32): if a,b each satisfy it then
(nab)=(na)(nb)=a(n−1)/2b(n−1)/2=(ab)(n−1)/2(modn),
so ab∈Witn — it is a subgroup of Zn∗. To finish
we must show it is a proper subgroup, i.e. exhibit some a∈Zn∗outside
it (slides 32–34). With n=p1i1m, two cases:
i1=1 (p1 appears to the first power). Let g generate the cyclic group
Zp1∗ and use CRT to set a≡g(modp1), $a\equiv 1
(\bmod\ m). A generator is a non-residue, so $\left(\tfrac{a}{n}\right)=-1, while
a(n−1)/2≡1 — they differ, so a is a witness.
i1≥2 (a square factor). If a∈Witn then
an−1≡1, forcing the order ∣Zq∗∣ (with q=p1i1) to divide
n−1. But p1∣∣Zq∗∣ and p1∣n, so p1∣gcd(n,n−1)=1 —
contradiction. A witness must exist.
By Lagrange the proper subgroup has ≤∣Zn∗∣/2 elements, so witnesses are
≥ half. □
Algorithm SSA (Solovay–Strassen), input odd n≥3: pick random
a∈{1,…,n−1}; if gcd(a,n)=1 return composite; else compute
J=(na) and A=a(n−1)/2modn; return prime if J=A, else
composite. Everything is O((logn)3).
9. From testing to generating primes (slides 35–37)
Cryptography needs random primes. PrimGen(ℓ, k): repeatedly draw a random odd ℓ-bit
number n=2ℓ−1+∑i=1ℓ−2ai2i+1 and run k rounds of
Solovay–Strassen; output the first n that passes. There are two error sources, and both
are crushed.
Error A — fails to output any prime. By the Prime Number Theorem a random ℓ-bit
number is prime with probability ≥lnn1>2ℓ1. Over 2ℓ2
attempts,
Pr[no prime found and certified]<(1−2ℓ1)2ℓ2⋅(test-miss factor)<e−ℓ.
For ℓ≥100: e−100≪10−40.
Error B — outputs a composite as “prime”. Each run lets a composite slip with
probability ≤2−ℓ (with k=ℓ rounds). Summed over the ≤2ℓ2 attempts,
Pr[output composite]≤2ℓ−1ℓ2.
For ℓ≥100: ≤1.58⋅10−26.
Punchline. A Monte-Carlo test (one-sided error on a single number) composes into
a generator whose two failure modes are both exponentially unlikely. You get a prime
with overwhelming confidence and no factorization in sight — the bedrock of RSA key
generation.
10. The second arena — witnesses for a Boolean matrix product (slides 38–45)
The witness method is not only number theory. Its second appearance is a gem of
algorithm design: all-pairs shortest paths (APSP) in an unweighted, undirected
graph, via fast matrix multiplication. Let MM(n)=nω be the cost of
multiplying two n×n matrices.
distances only
distances and paths
deterministic
BFS O(mn), Floyd–Warshall O(n3)
—
randomized
APD O(MM(n)logn)
+ BPWM →O(MM(n)log2n)
10a. APD — distances by halving (Seidel), slides 39–40
Build G′ by adding an edge between any two vertices at distance ≤2 in G
(computed from A and A2: Z=A2, then B[i,j]=A[i,j]∨Z[i,j]). Distances in G′
are halved:
D[i,j] even⇒D[i,j]=2D′[i,j],D[i,j] odd⇒D[i,j]=2D′[i,j]−1.
Recurse on G′ to get D′, then recover the parity of D[i,j] from a neighbour sum
(slide 39): D[i,j] is even ⟺∑k∈Γ(i)D′[k,j]≥deg(i)D′[i,j].
The recursion T(n,δ)=2MM(n)+T(n,⌈δ/2⌉)+O(n2) gives
APD computes the full distance matrix in O(MM(n)logn).
But distances are not paths. To walk a shortest i–j path we need, at i, some
neighbour k on a shortest path to j. Finding that k is a witness problem.
10b. APSP reduces to BPWM (slide 41–42)
Define the Boolean Product Witness Matrix problem:
BPWM. Given Boolean matrices A,B, output W where W[i,j]=k for somek with
A[i,k]=B[k,j]=1 (a witness for the Boolean product entry), or 0 if none exists.
A successor on a shortest path is exactly such a witness: S[i,j]=k iff A[i,k]=1 (k
is a neighbour of i) and D[k,j]=D[i,j]−1. We don’t want to solve this for all n−1
possible distance values — but neighbours satisfy D[i,j]−1≤D[k,j]≤D[i,j]+1, so it
suffices to match D[k,j]≡D[i,j]−1(mod3). Run BPWM on A against the three
“distance-class” matrices D(r) (r∈{0,1,2}). Three products replace n−1.
10c. Finding the witness — isolate it by subsampling (slides 43–45)
How do we extract an actual witness k from a Boolean product? Two ideas.
Idea 1: a unique witness reveals itself arithmetically. Compute the integer product
W=A⋅B. Then W[i,j]counts the witnesses k. Now weight column k of A
by the number k and multiply: the (i,j) entry becomes ∑kkA[i,k]B[k,j]=sum
of all witness indices. If there is exactly one witness k∗, this sum equals
k∗ — the witness drops out for free.
Idea 2: make “exactly one” happen, by random subsampling. When (i,j) has c
witnesses, randomly keep a subset of d columns k1,…,kd. If we pick the scaled so that n/2≤cd≤n, exactly one witness survives with good probability:
Balls lemma. Among n balls, w are white. Draw d independently with
replacement, with n/2≤wd≤n. Then
Pr[exactly one white]=dnw(1−nw)d−1≥21(1−d1)d−1>2e1.
Proof.d⋅nw≥21 from wd≥n/2; and nw≤d1 from
wd≤n, so (1−nw)d−1≥(1−d1)d−1>e−1. □
Since c is unknown, try every scale d=2ℓ for $\ell=0,\dots,\lceil\log
n\rceil-1$, each repeated 3.42⌈logn⌉ times. For the right scale a single
try isolates a witness with probability ≥2e1, so the chance of never
isolating one is
(1−2e1)3.42⌈logn⌉≤n1.
Hence only a ≤1/n fraction of entries fall through to a direct computation (step 3),
and the whole witness matrix costs O(MM(n)log2n).
Punchline. This is the same deep idea as the Isolation Lemma from part 2:
when many solutions confuse you, randomly thin them down until exactly one
survives — a unique witness is one you can read off arithmetically. Randomness
here is not for speed but for isolation.
Recurring themes from the witness method
Theme
Where it appeared
One found witness = certain proof (co-RP / one-sided error)
every primality test (§1)
Density of witnesses is everything
divisor fails (§3), Fermat fails on Carmichael (§4)
Non-witnesses form a (proper) subgroup → Lagrange → ≤ half
n≡3mod4 (§6), Solovay–Strassen (§8)
One witness floods into many (multiply by b: injective coset shift)
injection Euler↪Wit (§6)
Read a number by CRT coordinates (modp,modq)
building an explicit witness b (§6, §8)
A nontrivial square root of 1 betrays a composite
Miller–Rabin (§7)
Compute a hard invariant without the hard data
Jacobi symbol without factoring (§8)
Monte-Carlo test → reliable generator
random prime generation (§9)
Isolate a unique witness by random subsampling
BPWM for shortest paths (§10)
The one sentence tying it together:
A witness is a needle whose mere existence is a proof — so the only question is how
much hay surrounds it. Group theory (Lagrange) guarantees the needles are at least
half the haystack for primality; random subsampling manufactures a lone needle for
matrix products. Find one and you are certain; the randomness only governs how fast
you find it.