Multiplying two polynomials term by term takes n squared products. The FFT takes about n log n. For two polynomials of 1,024 terms, that is 35,840 products instead of 1,048,576.
Pick a route, then drag the size. Watch the grid of products explode while the butterfly network stays thin. Then we build, piece by piece, the point values, the roots of unity, the butterfly and the way back.
You need Python, polynomials (like 3 + 2x + x²) and a little recursion. We build the rest, complex numbers included, from zero.
Follows Chapter 30 of Introduction to Algorithms by Cormen, Leiserson, Rivest and Stein (CLRS). It uses the CLRS sign convention. The devices and toy inputs are our own.
Both polynomials have n terms. The FFT route pads to 2n points and runs three transforms of (2n/2) lg 2n products each, plus 2n pointwise products. Each complex product counts as one. Additions are not counted.
Chapter 0
Multiply two short polynomials by hand and count every product
Take A(x) = 3 + 2x + x² and B(x) = 1 + 4x. To multiply them, you multiply every term of A by every term of B. That is 3 × 2 = 6 products. Then you collect the terms with the same power of x.
We store a polynomial as its list of coefficients, the numbers in front of each power: A is [3, 2, 1]. Two lists of n coefficients need n × n products. For n = 1,000,000 that is 1012 products.
Each cell is one product. Press Step to collect the cells whose powers add up to k. Pick the larger pair and count the cells.
Illustrative. The 8 by 8 coefficients are fixed digits chosen for the demo.
Each output coefficient is a sum along one diagonal of the grid. Call the coefficients of A aj, those of B bj, and those of the product C ck.
c-k equals the sum over j of a-j times b of k minus j.
To get c-k, pair each a-j with the b whose power adds to k. Multiply each pair and add. This sum has a name: the convolution of the two lists.
With A = [3, 2, 1] and B = [1, 4]: c1 = a0b1 + a1b0 = 3 × 4 + 2 × 1 = 14. That is the 14x in the product.
The FFT avoids the grid. It changes how we describe the polynomials, multiplies in that description with n products, and changes back. Each change costs about n lg n, where lg n is the logarithm base 2.
Symptom: the product list is one entry short, and the top power is missing.
Measure: lists of length m and n give a product of length m + n − 1. Check len(c).
Fix: allocate m + n − 1 slots, not max(m, n).
Chapter 1
Describe the same polynomial by where it passes, and multiply in n steps
A polynomial is also a curve. Evaluate A(x) = 3 + 2x + x² at x = 0, 1 and 2: you get 3, 6 and 11. Only one curve of degree 2 passes through those three points. So the three pairs (0, 3), (1, 6), (2, 11) describe A as well as [3, 2, 1] does.
This is the point-value form: a polynomial described by its values at chosen points. The rule behind it: n points with different x values fix exactly one polynomial with n coefficients. Going from values back to coefficients is called interpolation.
Why bother? Because C(x) = A(x) · B(x) at every x. If you know A and B at the same points, the values of C are the products of the values. That is one product per point, n in total.
The table multiplies A and B point by point. The blue curve is the true product C. Switch to three points and see a second cubic fit them too.
A = 3 + 2x + x², B = 1 + 4x, C = 3 + 14x + 9x² + 4x³. The impostor is C + 2x(x − 1)(x − 2), which is zero at x = 0, 1, 2.
The product has degree 3, so it needs 4 points. Evaluate A and B at 4 points, multiply, and you hold C.
| x | A(x) | B(x) | C(x) = A · B |
|---|---|---|---|
| 0 | 3 | 1 | 3 |
| 1 | 6 | 5 | 30 |
| 2 | 11 | 9 | 99 |
| 3 | 18 | 13 | 234 |
Check one: C(3) = 3 + 42 + 81 + 108 = 234. The catch is the cost of the conversions. Horner's rule evaluates one point in n steps: start from the top coefficient, multiply by x, add the next. But n points cost n × n again. Chapter 2 picks points that are cheap to evaluate all together.
pythondef horner(coeffs, x): # coeffs = [a0, a1, ..., a(n-1)] y = 0 for a in reversed(coeffs): y = y * x + a # one multiply, one add per coefficient return y [horner([3, 2, 1], x) for x in range(4)] # [3, 6, 11, 18]
Symptom: after interpolation the product is a different polynomial.
Measure: count the points. C needs deg A + deg B + 1 of them.
Fix: evaluate both inputs at that many points before you multiply. Three points for a cubic leave it unfixed.
Chapter 2
Space n points around a circle, square them, and watch n become n/2
The fast points are not on the number line. They are on a circle in the complex plane. A complex number a + bi is a point with x coordinate a and y coordinate b, where i × i = −1. Multiplying two points on the circle of radius 1 adds their angles.
Put n points evenly around that circle, starting at 1. Each one, raised to the power n, goes around to 1 again. These are the n-th roots of unity. Call the first one past 1 ωn, the principal root. The others are its powers.
omega-n to the k equals e to the two pi i k over n, which is cos of two pi k over n, plus i times sin of two pi k over n.
Cut a full turn into n equal slices. Walk k slices from 1. The point you reach is omega-n to the k. Its x is the cosine of the angle, its y the sine.
n = 8, k = 1: the angle is 45 degrees, so ω8 = 0.707 + 0.707i. k = 2 gives 90 degrees, the point i. k = 4 gives −1.
Squaring a point doubles its angle. Press Square with n = 8 and count where the points land. Then try an odd n.
Exact geometry, no toy numbers.
That folding is the property the FFT runs on.
omega-n to the k, squared, equals omega of n over two, to the k.
Square all n roots, with n even. You get the n/2 roots of the half-size circle, each one twice. This is the halving lemma.
(ω8)2 = (0.707 + 0.707i)2 = 0.5 − 0.5 + 2 × 0.5i = i, which is ω4. ω85 squared also lands on i. Eight points become four.
One more fact, used in Chapter 7: the n roots add to zero. They pull equally in every direction. For n = 4: 1 + i + (−1) + (−i) = 0. This is the summation lemma.
Symptom: your FFT returns wrong values for n = 6 or n = 12.
Measure: after a few halvings an odd size appears: 6 becomes 3, and the squares of 3 roots do not fold.
Fix: pad the list with zeros up to a power of 2.
Chapter 3
Add the coefficients as arrows, each turned by a root, and land on the value
Evaluate a polynomial with n coefficients at all n roots of unity. The n results form the discrete Fourier transform, or DFT, of the coefficient list. Call the coefficients aj and the results yk.
y-k equals the sum over j from zero to n minus one of a-j times omega-n to the j k.
For value y-k, turn each coefficient a-j by j times k slices of the circle. Lay the turned arrows head to tail. Where the chain ends is y-k.
a = (1, 2, 3, 4), n = 4, so ω4 = i. y1 = 1 + 2i + 3(−1) + 4(−i) = −2 − 2i.
Blue arrows are the coefficients after their turn. The warm dot is yk. Drag k and watch the arrows turn faster.
Computed exactly with the CLRS convention, ωn = e+2πi/n.
The full result is DFT(1, 2, 3, 4) = (10, −2 − 2i, −2, −2 + 2i). y0 is the plain sum, because every arrow points along 1. Computed this way, each yk costs n products, so the DFT costs n2. No saving yet.
Look at y3: it mirrors y1 across the x axis. For real coefficients yn−k is always the mirror image of yk.
Symptom: numpy.fft.fft([1, 2, 3, 4]) gives −2 + 2i where you expect −2 − 2i.
Measure: compare with 4 × numpy.fft.ifft([1, 2, 3, 4]).
Fix: NumPy and most signal processing texts use e−2πi/n. CLRS uses e+2πi/n. Pick one sign and keep it.
Chapter 4
Turn one evaluation of size n into two evaluations of size n/2
Here is the divide step. Put the coefficients with even index in one list and those with odd index in another. Each list is a polynomial with n/2 coefficients. Call them Aeven and Aodd.
A of x equals A-even of x squared, plus x times A-odd of x squared.
Evaluate A-even and A-odd at x squared. Multiply the A-odd value by x. Add. The result is A of x.
A = 1 + 2x + 3x2 + 4x3, so Aeven(y) = 1 + 3y and Aodd(y) = 2 + 4y. At x = 2: Aeven(4) = 13, Aodd(4) = 18, and 13 + 2 × 18 = 49 = A(2).
Now join this with Chapter 2. We need A at the n roots. The formula asks for Aeven and Aodd at the squares of those roots. The halving lemma says the squares are only the n/2 half-size roots. So we need two DFTs of size n/2, plus a little work to join them.
Teal boxes go to the even list, pink boxes to the odd list. Press Split three times. Then show the indexes in binary and read the bottom row.
Each box shows its index, a0 to a7. Only the order matters here.
Each level halves the size, so the recursion is lg n levels deep. For n = 8 that is 3 levels, and the leaves come out in the order 0, 4, 2, 6, 1, 5, 3, 7. Chapter 6 uses that order.
Symptom: you split into the first half and the second half, and the answers are wrong.
Measure: check the identity at one point, say x = 2. The halves give A(x) = L(x) + xn/2 R(x), with x not squared.
Fix: split by index parity: a[0::2] and a[1::2] in Python.
Chapter 5
Join the two half-size DFTs with a plus and a minus
The recursion returns two lists of n/2 values. ek is the DFT of the even coefficients and ok the DFT of the odd ones. How do we build the n values of A?
y-k equals e-k plus omega-n to the k times o-k. y of k plus n over two equals e-k minus omega-n to the k times o-k.
Turn o-k by the twiddle factor. Call the result t. Then y-k is e-k plus t, and y of k plus n over two is e-k minus t. The minus sign appears because the root half a turn on is minus the first one.
For a = (1, 2, 3, 4): e = (4, −2), o = (6, −2), ω4 = i. k = 0: t = 6, y0 = 10, y2 = −2. k = 1: t = i × (−2) = −2i, y1 = −2 − 2i, y3 = −2 + 2i.
This plus and minus pair is the butterfly. One product, ωnk ok, serves two outputs. The answer matches Chapter 3 exactly.
This is the top stage of an 8-point FFT of (1, 2, 3, 4, 0, 0, 0, 0). Pick k. The pink arrow turns by the twiddle; the two warm dots sit at e + t and e − t.
e and o are the 4-point DFTs of (1, 3, 0, 0) and (2, 4, 0, 0). All numbers are exact to two decimals.
Count the work. The join does n/2 products and n additions. Two half-size calls plus linear work give T(n) = 2T(n/2) + n, the merge sort recurrence. The master theorem from Chapter 4 solves it: n lg n. Each of the lg n levels does n/2 products, so (n/2) lg n in all. For n = 8 that is 12 products instead of 64.
pythonimport cmath def fft(a): # len(a) must be a power of 2 n = len(a) if n == 1: return list(a) # one coefficient: its own value e, o = fft(a[0::2]), fft(a[1::2]) # two half-size DFTs w_n = cmath.exp(2j * cmath.pi / n) # principal root, CLRS sign y, w = [0] * n, 1 for k in range(n // 2): t = w * o[k] # the one product y[k], y[k + n // 2] = e[k] + t, e[k] - t # the butterfly w *= w_n return y fft([1, 2, 3, 4]) # [10, -2-2j, -2, -2+2j]
Symptom: the first half of the output is right and the second half is wrong.
Measure: compare y[n//2:] with a direct DFT on a random list.
Fix: the second half takes e − t with the same twiddle, not e + t with a new one.
Chapter 6
Unroll the recursion into stages that work in place on one array
The recursive FFT makes new lists at every call. Fast libraries avoid this. They run the recursion backwards: first all the size 2 butterflies, then size 4, then size 8. Each stage writes its results into the same array.
For that, the input must start in the order of the recursion's leaves. Chapter 4 found it: 0, 4, 2, 6, 1, 5, 3, 7. Write each index in binary and reverse the bits: 1 = 001 becomes 100 = 4. This shuffle is the bit-reversal permutation.
The left column is the input in bit-reversed order. Press Stage. Each butterfly joins two lanes: teal adds the turned value, pink subtracts it.
Values rounded to one decimal on the canvas. The read-out gives two.
Stage s joins lanes that are 2s−1 apart. Each stage does 4 products for n = 8, so 3 stages do 12. The last column is the DFT in natural order: the same 10 at the top as the Chapter 3 sum.
| Index | Binary | Reversed | Goes to |
|---|---|---|---|
| 1 | 001 | 100 | 4 |
| 3 | 011 | 110 | 6 |
| 6 | 110 | 011 | 3 |
pythondef fft_inplace(a, sign=1): # a: list of complex, length 2^m n, m = len(a), len(a).bit_length() - 1 for i in range(n): # bit-reversal shuffle r = int(format(i, f"0{m}b")[::-1], 2) if i < r: a[i], a[r] = a[r], a[i] size = 2 while size <= n: # stages: 2, 4, 8, ... w_s = cmath.exp(sign * 2j * cmath.pi / size) for start in range(0, n, size): w = 1 for j in range(size // 2): u, t = a[start + j], w * a[start + j + size // 2] a[start + j], a[start + j + size // 2] = u + t, u - t w *= w_s size *= 2 return a
Symptom: the in-place FFT returns the right numbers in a scrambled order.
Measure: run it on (0, 1, 0, 0, 0, 0, 0, 0). The output must be the 8 roots in order, 1, ω, ω2, …
Fix: do the bit-reversal shuffle before the stages, and swap only when i < r, or each pair swaps back.
Chapter 7
Turn the other way around the circle, divide by n, and recover the coefficients
After multiplying values we hold the product as values. We need its coefficients. That is interpolation at the roots of unity, the inverse DFT. It looks almost like the forward DFT.
a-j equals one over n, times the sum over k from zero to n minus one of y-k times omega-n to the minus j k.
Run the DFT on the values y-k, but turn each one clockwise instead of counterclockwise. Divide every result by n. You get back the coefficients a-j.
y = (10, −2 − 2i, −2, −2 + 2i), n = 4. a0 = (10 − 2 − 2i − 2 − 2 + 2i)/4 = 4/4 = 1. a1 = (10 + (−2 + 2i) + 2 + (−2 − 2i))/4 = 8/4 = 2.
Why does it work? Do forward then backward. Each coefficient comes back with weight n: every turn cancels its reverse turn. Every other coefficient lands on the sum of a full set of roots, which is 0 by the summation lemma. Dividing by n leaves the original list.
Top: coefficients. Middle: their DFT values. Bottom: what the inverse returns. Switch off one fix at a time and read the bottom row.
n = 4. The values are exact.
So the inverse needs no new code. Call the same FFT with the sign of the angle flipped, then divide by n. The cost is again n lg n.
Symptom: every recovered coefficient is exactly n times too big.
Measure: run forward then inverse on [1, 0, 0, 0]. You must get [1, 0, 0, 0] back.
Fix: divide by n once at the end, or by 2 at each of the lg n levels.
Chapter 8
Pad, transform, multiply values, transform back, and watch the product wrap if you skip the padding
Now put the pieces together. To multiply A and B:
Take A = 1 + 2x + 3x2 and B = 2 + x. The product has 4 terms, so N = 4.
Check: (1 + 2x + 3x2)(2 + x) = 2 + x + 4x + 2x2 + 6x2 + 3x3 = 2 + 5x + 8x2 + 3x3. Each step matches.
The two bottom rows should match. Switch the size to the longer input only and see which terms land in the wrong place.
The FFT here runs in your browser in floating point, then rounds. The first coefficients are A = [1, 2, 3] and B = [1, 1, 2]; New draws digits from 0 to 9.
What went wrong without padding? The DFT treats the list as a loop. A term that falls past the end wraps around to the start. With A = [1, 2, 3] and B = [1, 1, 2], the true product is [1, 3, 7, 7, 6]. With N = 4, the 6 wraps onto the first slot: [1 + 6, 3, 7, 7] = [7, 3, 7, 7]. This loop product is the circular convolution.
The pipeline proves the convolution theorem: the DFT of a convolution is the slot-by-slot product of the DFTs. Many sums have this shape. Two dice are one example. Convolve [1, 1, 1, 1, 1, 1] with itself and you get the ways to roll each total from 2 to 12: [1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1], out of 36.
Symptom: the first few coefficients of the product are too big and the last ones are missing.
Measure: compare with numpy.convolve on the same lists.
Fix: choose N as a power of 2 with N ≥ len(a) + len(b) − 1.
Chapter 9
Run the same FFT on whole numbers modulo a prime, with no rounding at all
Floating point FFTs round. For long lists of large integers, the rounding error can grow past 0.5 and flip a digit. The fix is to find roots of unity among whole numbers.
Work modulo a prime p: keep only the remainder after division by p, like hours on a clock. A number g is a primitive root mod p if its powers g, g2, … hit every nonzero remainder. Its powers then go round in a cycle of length p − 1, the way ω goes round the circle.
omega equals g to the power p minus one over n, mod p.
The powers of g cycle through p minus one remainders. Take every ((p − 1)/n)-th one. You get n remainders that cycle like the n roots of unity. The first of them is omega.
p = 17, g = 3, n = 4: ω = 34 = 81 = 4 × 17 + 13, so ω = 13. Then 132 = 169 = 16 mod 17, which is −1, just as i2 = −1.
Each dot is a remainder mod 17, placed at its step in the cycle of 3. Pick n and see the roots form the same even spacing as on the complex circle.
Exact arithmetic mod 17. Dot k holds 3k mod 17.
Run Chapter 8 mod 17 with ω = 13. FFT([1, 2, 3, 0]) = [6, 7, 2, 6] and FFT([2, 1, 0, 0]) = [3, 15, 1, 6]. The products mod 17 are [1, 3, 2, 2]. The inverse uses ω−1 = 4 and 1/4 = 13, both mod 17. It returns [2, 5, 8, 3], exact. This is the number theoretic transform, or NTT.
| Prime p | p − 1 | Longest list | g |
|---|---|---|---|
| 17 | 24 | 16 | 3 |
| 998,244,353 | 119 × 223 | 223 = 8,388,608 | 3 |
| 985,661,441 | 235 × 222 | 222 = 4,194,304 | 3 |
| 469,762,049 | 7 × 226 | 226 = 67,108,864 | 3 |
Symptom: the NTT product has a small coefficient where you expect a large one.
Measure: bound the true coefficients: at most min(len a, len b) × max a × max b.
Fix: the NTT returns each coefficient mod p. If a true one can reach p, use a larger prime, or two primes joined by the Chinese remainder theorem.
Chapter 10
Keep the numbers, the checks and the code in one place
Coefficients multiply slowly and values multiply fast. The FFT moves between the two in n lg n, because the roots of unity fold in half when squared. The inverse is the same algorithm turned the other way and divided by n.
| Term | What it is | Number to remember |
|---|---|---|
| Schoolbook product | every term times every term | n × n products |
| ωn | e2πi/n, the principal root | ω8 = 0.707 + 0.707i |
| Halving lemma | squares of n roots are the n/2 roots | 8 points become 4 |
| DFT | A at all n roots | DFT(1,2,3,4) = (10, −2−2i, −2, −2+2i) |
| Butterfly | e + t and e − t with t = ωko | (n/2) lg n products: 12 for n = 8 |
| Bit reversal | input order of the in-place FFT | 0, 4, 2, 6, 1, 5, 3, 7 |
| Inverse DFT | same FFT with ω−1, then divide by n | [18, −6+2i, 2, −6−2i] → [2, 5, 8, 3] |
| Padding | N ≥ len a + len b − 1 | [1,2,3] × [1,1,2] at N = 4 wraps to [7,3,7,7] |
| NTT | FFT mod a prime | 998,244,353 = 119 × 223 + 1 |
pythonimport numpy as np def poly_multiply(a, b): m = len(a) + len(b) - 1 # terms in the product N = 1 while N < m: N *= 2 # pad to a power of 2 fa, fb = np.fft.fft(a, N), np.fft.fft(b, N) # evaluate at N roots c = np.fft.ifft(fa * fb).real[:m] # multiply values, go back return np.rint(c).astype(int) poly_multiply([3, 2, 1], [1, 4]) # [ 3 14 9 4] poly_multiply([1, 2, 3], [2, 1]) # [2 5 8 3] poly_multiply([1]*6, [1]*6) # two dice: [1 2 3 4 5 6 5 4 3 2 1]
| Use | The two lists |
|---|---|
| Big integers | digit lists, then carries. Schönhage and Strassen (1971) reach n log n log log n; Harvey and van der Hoeven (2019) reach n log n. |
| Filters on a signal | samples and a filter's weights; long filters gain most. |
| Image blur | pixels and a kernel, with the FFT run on rows, then columns. |
| Wildcard matching | text and the reversed pattern, scored at every shift. |
| Lattice cryptography | polynomials mod a prime, with the NTT. ML-KEM (FIPS 203) uses q = 3329. |
Now press Present or Teach and explain from memory: the two descriptions, the halving lemma, the even and odd split, the butterfly and the way back. Then go back to the hero, set 1,024 terms, and say where the 35,840 comes from.