TExcelTAD
Home › Randomized Algorithms & Probabilistic Analysis › Polynomial Identity Testing and the Schwartz-Zippel Lemma

Polynomial Identity Testing and the Schwartz-Zippel Lemma

Is det⁡(1xixi2⋯)i\det\begin{pmatrix} 1 & x_i & x_i^2 & \cdots \end{pmatrix}_{i} equal to ∏i<j(xj−xi)\prod_{i<j}(x_j - x_i)? Is a huge arithmetic formula identically zero? Expanding a polynomial in nn variables can produce exponentially many monomials, so polynomial identity testing (PIT) by expansion is hopeless. Evaluating is cheap, though, and a nonzero polynomial is rarely zero at a random point. The Schwartz-Zippel lemma makes "rarely" precise, and it gives the simplest and most widely used randomized algorithm for a problem with no known deterministic polynomial-time algorithm. Freivalds' check (Freivalds' Matrix-Product Verification) is its degree-1 special case.

The lemma

Lemma (Schwartz 1980, Zippel 1979; DeMillo and Lipton 1978). Let Q∈F[x1,…,xn]Q \in F[x_1, \ldots, x_n] be a nonzero polynomial of total degree dd over a field FF, and let S⊆FS \subseteq F be finite. If r1,…,rnr_1, \ldots, r_n are chosen independently and uniformly from SS, then

Pr⁡[Q(r1,…,rn)=0]≤d∣S∣.\Pr\bigl[Q(r_1, \ldots, r_n) = 0\bigr] \le \frac{d}{\lvert S \rvert} .

Proof. Induction on nn. For n=1n = 1, a nonzero polynomial of degree dd has at most dd roots, and r1r_1 hits one of them with probability at most d/∣S∣d/\lvert S \rvert. For n>1n > 1, collect powers of x1x_1:

Q(x1,…,xn)=∑i=0kx1i Qi(x2,…,xn),Qk≠0,Q(x_1, \ldots, x_n) = \sum_{i=0}^{k} x_1^i \, Q_i(x_2, \ldots, x_n), \qquad Q_k \ne 0 ,

where kk is the largest power of x1x_1 that occurs, so QkQ_k has total degree at most d−kd - k. Let EE be the event Qk(r2,…,rn)=0Q_k(r_2, \ldots, r_n) = 0. By induction Pr⁡[E]≤d−k∣S∣\Pr[E] \le \frac{d - k}{\lvert S \rvert}. If EE does not happen, then Q(x1,r2,…,rn)Q(x_1, r_2, \ldots, r_n) is a nonzero univariate polynomial of degree kk in x1x_1, and r1r_1 is still uniform and independent of r2,…,rnr_2, \ldots, r_n, so it is a root with probability at most k∣S∣\frac{k}{\lvert S \rvert}. Hence

Pr⁡[Q(r)=0]≤Pr⁡[E]+Pr⁡[Q(r)=0∣E‾]≤d−k∣S∣+k∣S∣=d∣S∣.□\Pr[Q(r) = 0] \le \Pr[E] + \Pr[Q(r) = 0 \mid \overline{E}] \le \frac{d - k}{\lvert S \rvert} + \frac{k}{\lvert S \rvert} = \frac{d}{\lvert S \rvert}. \qquad \square

The bound is tight: Q=∏i=1d(x1−i)Q = \prod_{i=1}^{d}(x_1 - i) vanishes on exactly dd points of S={1,…,s}S = \{1, \ldots, s\}.

The algorithm

To test whether Q≡0Q \equiv 0, given any way to evaluate QQ (a formula, a circuit, a determinant, a black box), work over Zp\mathbb{Z}_p for a prime pp much larger than dd:

text
PIT(Q, d, k)                       // Q: evaluable polynomial of degree at most d
0  choose a prime p >= 2d          // larger p: smaller error
1  for round = 0 to k - 1
2      choose r_1 .. r_n uniformly from Z_p
3      if Q(r_1, .., r_n) mod p != 0
4          return "Q is not zero"  // certain
5  return "Q is zero"              // wrong with probability at most (d/p)^k

Over the integers one more step is needed, because QQ may be nonzero but divisible by pp: choose pp at random from a large range of primes, or work over a large enough field. The deterministic complexity of PIT is a famous open problem: Kabanets and Impagliazzo (2004) showed that a deterministic polynomial-time algorithm would imply circuit lower bounds that are out of reach of current techniques.

Testing identities

The program tests three claimed identities by random evaluation modulo p=261−1p = 2^{61} - 1: the Vandermonde determinant formula (true), the same formula with one factor reversed (false: off by a sign), and the expansion of (x1+⋯+xn)2(x_1 + \cdots + x_n)^2 with a coefficient wrong. The determinant is computed by Gaussian elimination modulo pp in O(n3)O(n^3) operations; expanding it symbolically would produce n!n! terms.

python · try it yourself
import random

P = 2 ** 61 - 1

def det_mod(M, p=P):
    M = [row[:] for row in M]
    n, det = len(M), 1
    for c in range(n):
        piv = next((r for r in range(c, n) if M[r][c] % p), None)
        if piv is None:
            return 0
        if piv != c:
            M[c], M[piv] = M[piv], M[c]
            det = -det
        det = det * M[c][c] % p
        inv = pow(M[c][c], p - 2, p)
        for r in range(c + 1, n):
            f = M[r][c] * inv % p
            M[r] = [(a - f * b) % p for a, b in zip(M[r], M[c])]
    return det % p

def vandermonde_identity(x):
    lhs = det_mod([[pow(xi, j, P) for j in range(len(x))] for xi in x])
    rhs = 1
    for i in range(len(x)):
        for j in range(i + 1, len(x)):
            rhs = rhs * (x[j] - x[i]) % P
    return lhs, rhs

def wrong_vandermonde(x):
    lhs, rhs = vandermonde_identity(x)
    return lhs, rhs * (x[0] - x[1]) * pow(x[1] - x[0], P - 2, P) % P   # one factor reversed

def square_expansion(x, wrong=False):
    lhs = sum(x) ** 2 % P
    rhs = sum(v * v for v in x) + (3 if wrong else 2) * sum(x[i] * x[j] for i in range(len(x)) for j in range(i + 1, len(x)))
    return lhs, rhs % P

rng = random.Random(70)
n = 12
tests = [("Vandermonde det = prod (x_j - x_i)", vandermonde_identity),
         ("same with one factor reversed", wrong_vandermonde),
         ("(sum x)^2 = sum x^2 + 2 sum x_i x_j", square_expansion),
         ("(sum x)^2 = sum x^2 + 3 sum x_i x_j", lambda x: square_expansion(x, True))]
for name, test in tests:
    verdicts = []
    for _ in range(5):
        lhs, rhs = test([rng.randrange(P) for _ in range(n)])
        verdicts.append(lhs == rhs)
    print(f"{name:38}: equal at {sum(verdicts)} of 5 random points")
print(f"error bound per point for the degree-{n * (n - 1) // 2} Vandermonde test: d/p = {n * (n - 1) / 2 / P:.1e}")
Vandermonde det = prod (x_j - x_i)    : equal at 5 of 5 random points
same with one factor reversed         : equal at 0 of 5 random points
(sum x)^2 = sum x^2 + 2 sum x_i x_j   : equal at 5 of 5 random points
(sum x)^2 = sum x^2 + 3 sum x_i x_j   : equal at 0 of 5 random points
error bound per point for the degree-66 Vandermonde test: d/p = 2.9e-17

A single random point already separates the true identities from the false ones, with error at most 66/p≈3⋅10−1766/p \approx 3 \cdot 10^{-17} for the determinant.

The lemma is tight

To see that d/∣S∣d/\lvert S \rvert is the right bound, take polynomials in xx and yy over the rationals, let S={1,…,50}S = \{1, \ldots, 50\}, and count exactly how many of the 2500 points of S2S^2 are roots.

python · try it yourself
s = 50
S = range(1, s + 1)
cases = {
    "prod_{i=1}^{10} (x - i)   d = 10": (lambda x, y: all(x != i for i in range(1, 11)), 10),
    "(x - y)(x - 2)             d = 2":  (lambda x, y: x != y and x != 2, 2),
    "x y - 6                    d = 2":  (lambda x, y: x * y != 6, 2),
}
for name, (nonzero, d) in cases.items():
    zeros = sum(not nonzero(x, y) for x in S for y in S)
    print(f"{name}: {zeros:3} roots in S^2, Pr[zero] = {zeros / s ** 2:.4f}, bound d/|S| = {d / s:.4f}")
prod_{i=1}^{10} (x - i)   d = 10: 500 roots in S^2, Pr[zero] = 0.2000, bound d/|S| = 0.2000
(x - y)(x - 2)             d = 2:  99 roots in S^2, Pr[zero] = 0.0396, bound d/|S| = 0.0400
x y - 6                    d = 2:   4 roots in S^2, Pr[zero] = 0.0016, bound d/|S| = 0.0400

The first polynomial attains the bound. The second comes close (Pr⁡=150+150−12500\Pr = \frac{1}{50} + \frac{1}{50} - \frac{1}{2500}), and the third is far below it: a polynomial can be zero much less often than the lemma allows, never more often.

Fingerprints

The lemma also explains why hashing by polynomial evaluation works. To check whether two nn-bit strings aa and bb held by different machines are equal, view them as polynomials A(x)=∑iaixiA(x) = \sum_i a_i x^i and B(x)=∑ibixiB(x) = \sum_i b_i x^i over Zp\mathbb{Z}_p with p≥n2p \ge n^2, pick a random r∈Zpr \in \mathbb{Z}_p and compare A(r)A(r) with B(r)B(r): only O(log⁡n)O(\log n) bits need to be sent, and if a≠ba \ne b the values collide with probability at most np≤1n\frac{n}{p} \le \frac1n, since A−BA - B is nonzero of degree less than nn. Deterministic protocols need nn bits. The rolling hash of Rabin-Karp uses the same principle with a fixed base and a random-looking modulus.

In C++

Verifying a claimed polynomial product R=P⋅QR = P \cdot Q (for instance the output of an FFT) takes O(n)O(n) time: evaluate all three at a random point modulo p=261−1p = 2^{61} - 1 and compare, which errs with probability at most deg⁡R/p\deg R / p. Products modulo pp use the compiler's 128-bit integers. The program builds a correct product of two degree-999 polynomials by schoolbook multiplication, then corrupts one coefficient.

cpp · try it yourself
#include <cstdint>
#include <cstdio>
#include <random>
#include <vector>

using u64 = std::uint64_t;
const u64 P = (1ULL << 61) - 1;

u64 mul(u64 a, u64 b) { return (unsigned __int128)a * b % P; }

u64 eval(const std::vector<u64>& c, u64 x) {            // Horner's rule, n multiplications
    u64 v = 0;
    for (size_t i = c.size(); i-- > 0;) v = (mul(v, x) + c[i]) % P;
    return v;
}

bool check_product(const std::vector<u64>& p, const std::vector<u64>& q, const std::vector<u64>& r, std::mt19937_64& rng) {
    u64 x = rng() % P;
    return mul(eval(p, x), eval(q, x)) == eval(r, x);
}

int main() {
    std::mt19937_64 rng(70);
    const int n = 1000;
    std::vector<u64> p(n), q(n), r(2 * n - 1, 0);
    for (auto& c : p) c = rng() % 1000;
    for (auto& c : q) c = rng() % 1000;
    for (int i = 0; i < n; ++i)
        for (int j = 0; j < n; ++j) r[i + j] = (r[i + j] + p[i] * q[j]) % P;
    std::printf("correct product passes 3 checks: %s\n",
                check_product(p, q, r, rng) && check_product(p, q, r, rng) && check_product(p, q, r, rng) ? "yes" : "no");
    r[777] += 1;
    std::printf("corrupted product passes a check: %s\n", check_product(p, q, r, rng) ? "yes" : "no");
    std::printf("error bound per check: %.2e\n", (2.0 * n - 2) / double(P));
}
correct product passes 3 checks: yes
corrupted product passes a check: no
error bound per check: 8.66e-16

Test yourself

A nonzero polynomial of total degree 10 in 5 variables is evaluated at a point drawn uniformly from S5S^5 with ∣S∣=1000\lvert S \rvert = 1000. What is the Schwartz-Zippel bound on the probability of getting 0?

  1. 10/100010/1000
  2. 50/100050/1000
  3. (10/1000)5(10/1000)^5
  4. 5/10005/1000

In the inductive proof, why is QkQ_k (the coefficient of the highest power x1kx_1^k) of degree at most d−kd - k?

  1. Because QQ is homogeneous
  2. Because every monomial of x1kQkx_1^k Q_k has total degree at most dd
  3. Because k≤nk \le n
  4. Because of the field size

Which of these is the degree-1 case of the Schwartz-Zippel lemma?

  1. Karger's contraction
  2. Freivalds' test ABr=CrABr = Cr
  3. Miller-Rabin
  4. Quicksort

Is a deterministic polynomial-time algorithm for polynomial identity testing of arithmetic circuits known?

  1. Yes, Gaussian elimination
  2. No; finding one would imply circuit lower bounds that are currently out of reach
  3. Yes, but only over finite fields
  4. No, the problem is NP-hard