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 . Factor out of everything except the constant, again and again:
Now read it from the inside out. Start with the leading coefficient and repeat "multiply by , add the next coefficient". At :
Check the slow way: . ✓
Note: Zero coefficients must be kept in the list. Dropping the would shift every later coefficient to the wrong power.
Counting operations
For a polynomial of degree :
| Method | Multiplications | Additions |
|---|---|---|
| Naive: compute each from scratch | ||
| Keep a running power | about | |
| Horner |
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.
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 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 is divided by , and the last number is the remainder (dividing polynomials):
That is the remainder theorem: the remainder of is . In particular, exactly when is a factor.
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 = 2quotient: [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: is a root of , and the quotient 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 , keeping only the remainder :
Horner computes it in one pass: h = (h * B + ord(ch)) % M. Java's String.hashCode is exactly this with and (the int overflows and wraps).
The Rabin–Karp search slides a window of length 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 , add the new character.
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] == patdoes. More on hashing in hash tables and modular arithmetic.
Exercises
Exercise 1: Horner by hand
Evaluate at with Horner's method. Show each step.
Answer
Solution
Check the slow way: . ✓
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 is a factor of , and give the quotient.
Answer
Yes: the remainder is 0, and .
Solution
Divide by , so :
The quotient coefficients are 1, 2, −3: .
Exercise 3: A tiny hash (code)
Compute the Java-style hash () of "cat" by hand, then check it in code.
Answer
98262
Solution
ord('c') = 99, ord('a') = 97, ord('t') = 116:
h = 99
h = 99·31 + 97 = 3166
h = 3166·31 + 116 = 98262h = 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 ?
Horner's method at gives the intermediate values 1, 5, 7 and final value 0. What does that tell you?
- is a root, and the quotient is
- The polynomial is 0 everywhere
- The polynomial has degree 4
Why does Rabin–Karp compare the text after a hash match?
- To speed up the search
- Because the rolling update is approximate
- Because two different strings can have the same hash
- Because Python strings are immutable