TExcelTAD
Home › Algebra › Evaluating Polynomials Fast

Evaluating Polynomials Fast

Evaluating a polynomial looks trivial, but the obvious way wastes multiplications. Horner's method rewrites the polynomial as nested brackets and needs only one multiplication and one addition per coefficient. The same nesting is synthetic division, and it is how hash functions like Java's String.hashCode and the Rabin–Karp rolling hash turn a string into a number.

The idea: nest the brackets

Take p(x)=2x4−3x3+0x2+5x−7p(x) = 2x^4 - 3x^3 + 0x^2 + 5x - 7. Factor xx out of everything except the constant, again and again:

p(x)=2x4−3x3+0x2+5x−7=(2x3−3x2+0x+5)⋅x−7=((2x2−3x+0)⋅x+5)⋅x−7=(((2x−3)⋅x+0)⋅x+5)⋅x−7=((((2)⋅x−3)⋅x+0)⋅x+5)⋅x−7\begin{aligned} p(x) &= 2x^4 - 3x^3 + 0x^2 + 5x - 7 \\ &= (2x^3 - 3x^2 + 0x + 5) \cdot x - 7 \\ &= ((2x^2 - 3x + 0) \cdot x + 5) \cdot x - 7 \\ &= (((2x - 3) \cdot x + 0) \cdot x + 5) \cdot x - 7 \\ &= ((((2) \cdot x - 3) \cdot x + 0) \cdot x + 5) \cdot x - 7 \end{aligned}

Now read it from the inside out. Start with the leading coefficient and repeat "multiply by xx, add the next coefficient". At x=3x = 3:

start=22⋅3−3=33⋅3+0=99⋅3+5=3232⋅3−7=89p(3)=89\begin{aligned} \text{start} &\phantom{{}={}} 2 \\ 2 \cdot 3 - 3 &= 3 \\ 3 \cdot 3 + 0 &= 9 \\ 9 \cdot 3 + 5 &= 32 \\ 32 \cdot 3 - 7 &= 89 && p(3) = 89 \end{aligned}

Check the slow way: 2⋅81−3⋅27+0+15−7=162−81+15−7=892 \cdot 81 - 3 \cdot 27 + 0 + 15 - 7 = 162 - 81 + 15 - 7 = 89. ✓

Note: Zero coefficients must be kept in the list. Dropping the 0x20x^2 would shift every later coefficient to the wrong power.

Counting operations

For a polynomial of degree nn:

Method Multiplications Additions
Naive: compute each xkx^k from scratch (n+1)(n+2)/2=O(n2)(n + 1)(n + 2)/2 = O(n^2) nn
Keep a running power xkx^k about 2n2n nn
Horner nn nn

The code below counts multiplications for a degree-10 polynomial with all three methods and checks they agree with NumPy's np.polyval, which uses Horner's method internally.

python · try it yourself
import numpy as np

def naive(coeffs, x):                  # coeffs from the highest power down
    n, total, mults = len(coeffs) - 1, 0, 0
    for i, a in enumerate(coeffs):
        k, power = n - i, 1
        for _ in range(k):
            power *= x; mults += 1
        total += a * power; mults += 1
    return total, mults

def running(coeffs, x):
    total, power, mults = 0, 1, 0
    for a in reversed(coeffs):         # lowest power first
        total += a * power; mults += 1
        power *= x; mults += 1
    return total, mults - 1            # the last power update is not needed

def horner(coeffs, x):
    total, mults = 0, 0
    for a in coeffs:
        total = total * x + a; mults += 1
    return total, mults - 1            # the first step multiplies 0 by x

p = [1, -2, 0, 3, 1, -1, 4, 0, 2, -5, 7]  # degree 10
for f in (naive, running, horner):
    value, m = f(p, 2)
    print(f"{f.__name__:8}: p(2) = {value}, multiplications = {m}")
print("np.polyval:", int(np.polyval(p, 2)))
print("Horner on [2,-3,0,5,-7] at 3:", horner([2, -3, 0, 5, -7], 3)[0])
naive   : p(2) = 485, multiplications = 66
running : p(2) = 485, multiplications = 21
horner  : p(2) = 485, multiplications = 10
np.polyval: 485
Horner on [2,-3,0,5,-7] at 3: 89

For degree 10 that is 66 multiplications against 10. On a GPU evaluating a polynomial per pixel, or a math library computing sin⁡(x)\sin(x) from a polynomial approximation, that difference is the whole point. Horner is also usually more accurate in floating point, because it never forms large powers.

Horner is synthetic division

The intermediate numbers 2, 3, 9, 32 are not just scratch work. They are the coefficients of the quotient when p(x)p(x) is divided by (x−3)(x - 3), and the last number is the remainder (dividing polynomials):

p(x)=(x−3)(2x3+3x2+9x+32)+89p(x) = (x - 3)(2x^3 + 3x^2 + 9x + 32) + 89

That is the remainder theorem: the remainder of p(x)÷(x−c)p(x) \div (x - c) is p(c)p(c). In particular, p(c)=0p(c) = 0 exactly when (x−c)(x - c) is a factor.

python · try it yourself
import sympy as sp

def horner_divide(coeffs, c):
    row = [coeffs[0]]
    for a in coeffs[1:]:
        row.append(row[-1] * c + a)
    return row[:-1], row[-1]           # quotient coefficients, remainder

q, r = horner_divide([2, -3, 0, 5, -7], 3)
print("quotient:", q, "remainder:", r)

x = sp.symbols("x")
print(sp.div(2*x**4 - 3*x**3 + 5*x - 7, x - 3))
print(horner_divide([1, -6, 11, -6], 2))   # x³ − 6x² + 11x − 6 at x = 2
quotient: [2, 3, 9, 32] remainder: 89
(2*x**3 + 3*x**2 + 9*x + 32, 89)
([1, -4, 3], 0)

The last line shows remainder 0: x=2x = 2 is a root of x3−6x2+11x−6x^3 - 6x^2 + 11x - 6, and the quotient x2−4x+3=(x−1)(x−3)x^2 - 4x + 3 = (x - 1)(x - 3) gives the other two roots.

Strings as polynomials: rolling hashes

Treat the characters of a string as coefficients and evaluate the polynomial at a base BB, keeping only the remainder  mod M\bmod M:

hash⁡(c0c1…cm−1)=c0⋅Bm−1+c1⋅Bm−2+⋯+cm−1(modM)\operatorname{hash}(c_0 c_1 \ldots c_{m-1}) = c_0 \cdot B^{m-1} + c_1 \cdot B^{m-2} + \cdots + c_{m-1} \pmod{M}

Horner computes it in one pass: h = (h * B + ord(ch)) % M. Java's String.hashCode is exactly this with B=31B = 31 and M=232M = 2^{32} (the int overflows and wraps).

The Rabin–Karp search slides a window of length mm along a text. Moving the window one step is a cheap update instead of a full rehash: remove the leading character's term, shift by BB, add the new character.

hnew=((hold−cout⋅Bm−1)⋅B+cin) mod Mh_\text{new} = ((h_\text{old} - c_\text{out} \cdot B^{m-1}) \cdot B + c_\text{in}) \bmod M
python · try it yourself
def java_hash(s):
    h = 0
    for ch in s:
        h = (h * 31 + ord(ch)) % 2**32
    return h - 2**32 if h >= 2**31 else h          # as a signed 32-bit int

print("hashCode('hello') =", java_hash("hello"))
print("hashCode('polynomial') =", java_hash("polynomial"))

def rabin_karp(text, pat, B=256, M=1_000_003):
    m = len(pat)
    hp = ht = 0
    for i in range(m):
        hp = (hp * B + ord(pat[i])) % M
        ht = (ht * B + ord(text[i])) % M
    top = pow(B, m - 1, M)
    found = []
    for i in range(len(text) - m + 1):
        if ht == hp and text[i:i + m] == pat:      # confirm: hashes can collide
            found.append(i)
        if i + m < len(text):
            ht = ((ht - ord(text[i]) * top) * B + ord(text[i + m])) % M
    return found

print(rabin_karp("abracadabra", "abra"), rabin_karp("abracadabra", "cad"))
hashCode('hello') = 99162322
hashCode('polynomial') = -1079839020
[0, 7] [4]

Tip: Different strings can share a hash (a collision), so a hash match must always be confirmed by comparing the actual text. That is what text[i:i + m] == pat does. More on hashing in hash tables and modular arithmetic.

Exercises

Exercise 1: Horner by hand

Evaluate p(x)=3x3−5x2+2x−8p(x) = 3x^3 - 5x^2 + 2x - 8 at x=4x = 4 with Horner's method. Show each step.

Answer

p(4)=112p(4) = 112

Solution
start=33⋅4−5=77⋅4+2=3030⋅4−8=112\begin{aligned} \text{start} &\phantom{{}={}} 3 \\ 3 \cdot 4 - 5 &= 7 \\ 7 \cdot 4 + 2 &= 30 \\ 30 \cdot 4 - 8 &= 112 \end{aligned}

Check the slow way: 3⋅64−5⋅16+2⋅4−8=192−80+8−8=1123 \cdot 64 - 5 \cdot 16 + 2 \cdot 4 - 8 = 192 - 80 + 8 - 8 = 112. ✓

python · try it yourself
p = [3, -5, 2, -8]
h = 0
for a in p:
    h = h * 4 + a
print(h)
112

Exercise 2: Is it a factor?

Use synthetic division to decide whether (x+2)(x + 2) is a factor of x3+4x2+x−6x^3 + 4x^2 + x - 6, and give the quotient.

Answer

Yes: the remainder is 0, and x3+4x2+x−6=(x+2)(x2+2x−3)=(x+2)(x+3)(x−1)x^3 + 4x^2 + x - 6 = (x + 2)(x^2 + 2x - 3) = (x + 2)(x + 3)(x - 1).

Solution

Divide by x−(−2)x - (-2), so c=−2c = -2:

start=11⋅(−2)+4=22⋅(−2)+1=−3−3⋅(−2)−6=0remainder 0\begin{aligned} \text{start} &\phantom{{}={}} 1 \\ 1 \cdot (-2) + 4 &= 2 \\ 2 \cdot (-2) + 1 &= -3 \\ -3 \cdot (-2) - 6 &= 0 && \text{remainder } 0 \end{aligned}

The quotient coefficients are 1, 2, −3: x2+2x−3=(x+3)(x−1)x^2 + 2x - 3 = (x + 3)(x - 1).

Exercise 3: A tiny hash (code)

Compute the Java-style hash (B=31B = 31) of "cat" by hand, then check it in code.

Answer

98262

Solution

ord('c') = 99, ord('a') = 97, ord('t') = 116:

text
h = 99
h = 99·31 + 97   = 3166
h = 3166·31 + 116 = 98262
python · try it yourself
h = 0
for ch in "cat":
    h = h * 31 + ord(ch)
print(h)
98262

Test yourself

How many multiplications does Horner's method need for a polynomial of degree nn?

  1. n2n^2
  2. nn
  3. 2n2^n
  4. n(n+1)/2n(n + 1)/2

Horner's method at x=cx = c gives the intermediate values 1, 5, 7 and final value 0. What does that tell you?

  1. cc is a root, and the quotient is x2+5x+7x^2 + 5x + 7
  2. The polynomial is 0 everywhere
  3. The polynomial has degree 4
  4. c=0c = 0

Why does Rabin–Karp compare the text after a hash match?

  1. To speed up the search
  2. Because the rolling update is approximate
  3. Because two different strings can have the same hash
  4. Because Python strings are immutable