Simple Algorithm
Algorithms & Data Structures · Optimal · 30 min

The Fast Fourier Transform

Multiplying polynomials in O(n log n) with roots of unity.

Multiplying two polynomials of degree nn coefficient by coefficient takes Θ(n2)\Theta(n^2) operations. The fast Fourier transform does it in O(nlog⁡n)O(n \log n) by a detour: evaluate both polynomials at the complex roots of unity, multiply the values, and interpolate back. Gauss knew the trick around 1805; Cooley and Tukey's rediscovery in 1965 made it one of the most used algorithms ever written.

What you’ll learn

  • Express polynomial multiplication as a convolution, and explain why the point-value representation makes multiplication cheap.
  • Derive the radix-2 FFT from the halving lemma for roots of unity, and the inverse transform from the DFT matrix.
  • Implement the FFT recursively and in place with the bit-reversal permutation, and judge its floating-point error.
  • Use the number-theoretic transform modulo 998244353=119⋅223+1998244353 = 119 \cdot 2^{23} + 1 for exact integer convolution.
  • Apply convolution to big-integer multiplication, wildcard string matching and counting pair sums.

Multiplying polynomials is convolution

Let A(x)=∑i<naixiA(x) = \sum_{i<n} a_i x^i and B(x)=∑j<nbjxjB(x) = \sum_{j<n} b_j x^j. Their product C=ABC = AB has coefficients

ck=∑i+j=kai bj(0≤k≤2n−2),c_k = \sum_{i + j = k} a_i\,b_j \qquad (0 \le k \le 2n - 2),

the convolution of the two coefficient sequences. Computed directly, that is Θ(n2)\Theta(n^2) multiplications.

A polynomial of degree less than mm is also determined by its values at any mm distinct points (the Vandermonde matrix of the points is invertible). In this point-value form, multiplication is pointwise: C(xk)=A(xk) B(xk)C(x_k) = A(x_k)\,B(x_k), only O(m)O(m) work, provided both polynomials are evaluated at the same m≥2n−1m \ge 2n - 1 points.

StageOperationCost
EvaluateAA and BB at mm chosen pointsΘ(m2)\Theta(m^2) by Horner at arbitrary points; O(mlog⁡m)O(m \log m) at roots of unity
MultiplyC(xk)=A(xk) B(xk)C(x_k) = A(x_k)\,B(x_k)O(m)O(m)
Interpolaterecover the coefficients of CCΘ(m2)\Theta(m^2) in general; O(mlog⁡m)O(m \log m) at roots of unity
The choice of points is the whole trick: at the complex roots of unity, both evaluation and interpolation become divide and conquer.

Roots of unity and the halving lemma

Let ωn=e2πi/n\omega_n = e^{2\pi i/n}, a principal nn-th root of unity; its powers ωn0,…,ωnn−1\omega_n^0, \dots, \omega_n^{n-1} are the nn points zz with zn=1z^n = 1. The discrete Fourier transform of (a0,…,an−1)(a_0, \dots, a_{n-1}) is the vector of values yk=A(ωnk)=∑jaj ωnjky_k = A(\omega_n^k) = \sum_j a_j\,\omega_n^{jk}. Take nn a power of 2, padding with zero coefficients.

DerivationThe radix-2 FFT
  1. A(x)=Aeven(x2)+x Aodd(x2),Aeven(u)=a0+a2u+a4u2+⋯ ,Aodd(u)=a1+a3u+⋯A(x) = A_{\text{even}}(x^2) + x\,A_{\text{odd}}(x^2),\qquad A_{\text{even}}(u) = a_0 + a_2 u + a_4 u^2 + \cdots,\quad A_{\text{odd}}(u) = a_1 + a_3 u + \cdots

    Split AA by even and odd coefficients:

  2. (ωnk)2=ωn/2k,ωnk+n/2=− ωnk\big(\omega_n^{k}\big)^2 = \omega_{n/2}^{k},\qquad \omega_n^{k + n/2} = -\,\omega_n^{k}

    Halving lemma. For even nn, squaring the nn-th roots of unity gives the (n/2)(n/2)-th roots of unity, each twice, and opposite roots differ by a sign:

  3. yk=Ek+ωnk Ok,yk+n/2=Ek−ωnk Ok(0≤k<n/2)y_k = E_k + \omega_n^k\,O_k,\qquad y_{k + n/2} = E_k - \omega_n^k\,O_k\qquad (0 \le k < n/2)

    So with EkE_k and OkO_k the DFTs of length n/2n/2 of the even and odd coefficients, the nn values come from the butterfly:

  4. T(n)=2 T(n/2)+O(n)⟹T(n)=O(nlog⁡n)T(n) = 2\,T(n/2) + O(n)\quad\Longrightarrow\quad T(n) = O(n \log n)

    Two half-size transforms and O(n)O(n) butterflies:

DerivationThe inverse transform
  1. ∑k=0n−1ωnkℓ=ωnnℓ−1ωnℓ−1=0\sum_{k=0}^{n-1} \omega_n^{k\ell} = \frac{\omega_n^{n\ell} - 1}{\omega_n^{\ell} - 1} = 0

    The DFT is multiplication by the Vandermonde matrix Vjk=ωnjkV_{jk} = \omega_n^{jk}. For ℓ≠0\ell \ne 0 (mod nn), ωnℓ≠1\omega_n^\ell \ne 1 is a root of zn−1z^n - 1, so the geometric sum vanishes:

  2. aj=1n∑k=0n−1yk ωn−jka_j = \frac{1}{n} \sum_{k=0}^{n-1} y_k\,\omega_n^{-jk}

    Hence the matrix with entries ωn−jk\omega_n^{-jk}, times VV, is nn times the identity, and the inverse DFT is the same transform with ωn−1\omega_n^{-1}, divided by nn:

python
import cmath

def fft(a, invert=False):               # len(a) must be a power of 2
    n = len(a)
    if n == 1:
        return a[:]
    even = fft(a[0::2], invert)          # A_even at the (n/2)-th roots of unity
    odd = fft(a[1::2], invert)           # A_odd at the same points
    sign = -1 if invert else 1
    out = [0] * n
    for k in range(n // 2):
        w = cmath.exp(sign * 2j * cmath.pi * k / n)   # omega_n^k (or its inverse)
        out[k] = even[k] + w * odd[k]                 # the butterfly
        out[k + n // 2] = even[k] - w * odd[k]
    return out

def multiply(p, q):                      # integer coefficients, lowest degree first
    n = 1
    while n < len(p) + len(q) - 1:
        n *= 2
    fp = fft(p + [0] * (n - len(p)))
    fq = fft(q + [0] * (n - len(q)))
    prod = fft([x * y for x, y in zip(fp, fq)], invert=True)
    return [round((c / n).real) for c in prod[:len(p) + len(q) - 1]]

multiply([1, 2, 3], [4, 5]) returns [4, 13, 22, 15]: (1+2x+3x2)(4+5x)=4+13x+22x2+15x3(1 + 2x + 3x^2)(4 + 5x) = 4 + 13x + 22x^2 + 15x^3. The transform length is the smallest power of 2 that holds all the product's coefficients.

In place, in floating point, and modulo a prime

Unroll the recursion and the leaves receive the coefficients in bit-reversed order: for n=8n = 8, the order is a0,a4,a2,a6,a1,a5,a3,a7a_0, a_4, a_2, a_6, a_1, a_5, a_3, a_7, because index 1=00121 = 001_2 lands in position 1002=4100_2 = 4, and so on. Production FFTs permute the array into that order once, then run log⁡2n\log_2 n rounds of butterflies in place: no recursion, no extra arrays, good locality. Libraries such as FFTW go further and time many decompositions to keep the fastest one for the given nn and machine.

text
ITERATIVE-FFT(a):                          # n = len(a), a power of 2
    permute a into bit-reversed index order
    for len = 2, 4, 8, ..., n:              # log2 n rounds
        w_len ← e^(2πi / len)
        for start = 0, len, 2·len, ..., n − len:
            w ← 1
            for k = 0, 1, ..., len/2 − 1:   # butterflies, in place
                u ← a[start + k]
                v ← w · a[start + k + len/2]
                a[start + k] ← u + v
                a[start + k + len/2] ← u − v
                w ← w · w_len

Precision. Complex doubles carry 53-bit mantissas, and the rounding error grows with nn and with the size of the coefficients. Rounding the inverse transform to the nearest integer is safe only while the error stays below 12\tfrac12. In our test of the iterative version on 1,024 random coefficients per polynomial (with twiddle factors updated by repeated multiplication, as above), coefficients up to 10310^3 gave errors below 10−610^{-6}, coefficients up to 10610^6 an error of about 0.75, enough to round wrongly, and coefficients up to 10710^7 errors of about 68. The remedies: split each coefficient into 15- or 16-bit halves and use more transforms, or compute exactly modulo primes.

The number-theoretic transform (NTT) replaces C\mathbb C by the integers modulo a prime pp. If nn divides p−1p - 1 and gg is a primitive root modulo pp, then wn=g(p−1)/nw_n = g^{(p-1)/n} has order exactly nn, so wnn/2=−1w_n^{n/2} = -1, the halving lemma holds verbatim, and every operation is exact. The favorite prime of competitive programmers is p=998244353=119⋅223+1p = 998244353 = 119 \cdot 2^{23} + 1, with primitive root 3.

python
MOD = 998244353                            # 119 * 2^23 + 1, prime; 3 is a primitive root

def ntt(a, invert=False):                  # len(a) a power of 2, at most 2^23
    n = len(a)
    if n == 1:
        return a[:]
    even, odd = ntt(a[0::2], invert), ntt(a[1::2], invert)
    w_n = pow(3, (MOD - 1) // n, MOD)      # an element of order exactly n
    if invert:
        w_n = pow(w_n, MOD - 2, MOD)       # its inverse, by Fermat's little theorem
    out, w = [0] * n, 1
    for k in range(n // 2):
        t = w * odd[k] % MOD
        out[k] = (even[k] + t) % MOD
        out[k + n // 2] = (even[k] - t) % MOD
        w = w * w_n % MOD
    return out

Multiply exactly as with fft, then scale the inverse transform by n−1 mod pn^{-1} \bmod p instead of dividing by nn. The results are the true coefficients modulo pp: exact when the true values are below pp; larger values can be recovered from transforms modulo two or three such primes with the Chinese remainder theorem.

Predict before you look

Modulo p=998244353p = 998244353, transforms of length 2k2^k need an element of order 2k2^k. What is the largest such kk?

Show the answer

23

An element of order nn exists exactly when nn divides p−1=119⋅223=7⋅17⋅223p - 1 = 119 \cdot 2^{23} = 7 \cdot 17 \cdot 2^{23}. The largest power of 2 dividing it is 223=8,388,6082^{23} = 8{,}388{,}608, enough for products with about 8 million coefficients.

Applications, history and limits

Wherever a problem hides a sum of the form ∑i+j=k\sum_{i+j=k}, convolution and the FFT apply:

  • Big integers. Write the digits as coefficients, multiply the polynomials, then propagate carries. Schönhage and Strassen refined this into O(nlog⁡nlog⁡log⁡n)O(n \log n \log \log n) bit operations (see Fast Multiplication: Karatsuba to Strassen).
  • All pairwise sums. For integers a1,…,ama_1, \dots, a_m in [0,M][0, M], square P(x)=∑ixaiP(x) = \sum_i x^{a_i}: the coefficient of xsx^s counts the ordered pairs with ai+aj=sa_i + a_j = s, for every ss at once, in O(Mlog⁡M)O(M \log M) time however large mm is.
  • Matching with wildcards (Clifford & Clifford, 2007). Encode letters as positive integers and the wildcard as 0. Position ii of the text matches the pattern iff ∑jpj ti+j (pj−ti+j)2=0\sum_j p_j\,t_{i+j}\,(p_j - t_{i+j})^2 = 0; expanding the square gives three convolutions, so all positions are tested in O(nlog⁡n)O(n \log n).
  • Signal processing. Filtering, spectral analysis and fast correlation; JPEG and MP3 rely on close relatives of the DFT, cosine transforms.
Check your understanding

Why does ∑jpj ti+j (pj−ti+j)2=0\sum_j p_j\,t_{i+j}\,(p_j - t_{i+j})^2 = 0 detect a match at position ii, with wildcards encoded as 0?

  1. Each term is non-negative, and it is zero exactly when one of the two characters is a wildcard or the two are equal, so the sum vanishes iff every position matches
  2. The terms cancel in pairs whenever the strings match
  3. It counts the mismatches, and a count of 0 means a match, but wildcards are not handled
  4. It equals the edit distance between the pattern and the window
Show the answer

A. Each term is non-negative, and it is zero exactly when one of the two characters is a wildcard or the two are equal, so the sum vanishes iff every position matches

With non-negative codes, pj ti+j≥0p_j\,t_{i+j} \ge 0 and the square is ≥0\ge 0, so no cancellation is possible: the sum is 0 iff every term is 0, that is, iff at each position one character is a wildcard (a factor 0) or the characters are equal (the square is 0).

Key takeaways

  • Polynomial multiplication is convolution, ck=∑i+j=kaibjc_k = \sum_{i+j=k} a_i b_j; in point-value form it is pointwise, so evaluate, multiply and interpolate.
  • At the nn-th roots of unity, A(x)=Aeven(x2)+xAodd(x2)A(x) = A_{\text{even}}(x^2) + x A_{\text{odd}}(x^2) and the halving lemma give T(n)=2T(n/2)+O(n)=O(nlog⁡n)T(n) = 2T(n/2) + O(n) = O(n \log n); the inverse is the same transform with ωn−1\omega_n^{-1}, divided by nn.
  • The in-place FFT permutes into bit-reversed order and then runs log⁡2n\log_2 n rounds of butterflies; double precision limits the size of exact integer results, and the NTT modulo 998244353998244353 (root 3) is exact.
  • Convolution gives big-integer multiplication, all pairwise sums of small integers, and wildcard string matching in O(nlog⁡n)O(n \log n); whether the DFT itself needs Ω(nlog⁡n)\Omega(n \log n) operations is open.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

Why can a DFT of length nn be computed from two DFTs of length n/2n/2?

  1. Because half of the nn-th roots of unity are real
  2. Because A(x)=Aeven(x2)+xAodd(x2)A(x) = A_{\text{even}}(x^2) + x A_{\text{odd}}(x^2), and the squares of the nn-th roots of unity are just the n/2n/2 different (n/2)(n/2)-th roots of unity
  3. Because a polynomial of degree nn has only n/2n/2 independent coefficients
  4. Because the DFT matrix is symmetric
Show the answer

B. Because A(x)=Aeven(x2)+xAodd(x2)A(x) = A_{\text{even}}(x^2) + x A_{\text{odd}}(x^2), and the squares of the nn-th roots of unity are just the n/2n/2 different (n/2)(n/2)-th roots of unity

AevenA_{\text{even}} and AoddA_{\text{odd}} are evaluated at the squares of the evaluation points, and squaring maps the nn roots onto only n/2n/2 points. So each half-size polynomial needs only a half-size DFT, and the butterfly combines them.

Question 2

How is the inverse DFT computed with the FFT?

  1. Apply the forward FFT a second time: the DFT is its own inverse
  2. Solve the Vandermonde system by Gaussian elimination
  3. Run the same FFT with ωn−1\omega_n^{-1} in place of ωn\omega_n, then divide every value by nn
  4. Run the FFT on the output in reverse order without any scaling
Show the answer

C. Run the same FFT with ωn−1\omega_n^{-1} in place of ωn\omega_n, then divide every value by nn

The matrix of ωn−jk\omega_n^{-jk} times the DFT matrix is nIn I, because the sums ∑kωnkℓ\sum_k \omega_n^{k\ell} vanish for ℓ≠0\ell \ne 0. So the inverse is an FFT with inverted roots and a final division by nn: still O(nlog⁡n)O(n \log n).

Question 3

You multiply a polynomial of degree 5 by one of degree 9 with a radix-2 FFT. What is the smallest transform length that works?

  1. 8
  2. 10
  3. 32
  4. 16
Show the answer

D. 16

The product has degree 14, so 15 coefficients, and the transform needs at least 15 points; the next power of 2 is 16. A shorter transform computes a cyclic convolution, in which high coefficients wrap around onto low ones.

Question 4

What makes the prime p=998244353p = 998244353 convenient for the number-theoretic transform?

  1. p−1=119⋅223p - 1 = 119 \cdot 2^{23}, so the integers modulo pp contain elements of order 2k2^k for every k≤23k \le 23, playing the role of ωn\omega_n
  2. It is the largest prime below 10910^9
  3. Every nonzero residue modulo pp is a root of unity of order 2232^{23}
  4. Arithmetic modulo pp needs no multiplications
Show the answer

A. p−1=119⋅223p - 1 = 119 \cdot 2^{23}, so the integers modulo pp contain elements of order 2k2^k for every k≤23k \le 23, playing the role of ωn\omega_n

Modulo a prime pp there is a primitive root gg (here g=3g = 3), and g(p−1)/ng^{(p-1)/n} has order exactly nn whenever nn divides p−1p - 1. With 2232^{23} dividing p−1p - 1, every power-of-2 length up to 2232^{23} has its root of unity, and the halving lemma holds exactly, with no rounding.

Further reading

  • J. W. Cooley & J. W. Tukey, "An algorithm for the machine calculation of complex Fourier series," Mathematics of Computation 19 (1965), 297–301.
  • T. H. Cormen, C. E. Leiserson, R. L. Rivest & C. Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), chapter 30; the iterative FFT is in §30.3 of the 3rd edition (2009).
  • M. T. Heideman, D. H. Johnson & C. S. Burrus, "Gauss and the history of the fast Fourier transform," IEEE ASSP Magazine 1(4) (1984), 14–21.
  • P. Clifford & R. Clifford, "Simple deterministic wildcard matching," Information Processing Letters 101(2) (2007), 53–54.
  • M. Frigo & S. G. Johnson, "The design and implementation of FFTW3," Proceedings of the IEEE 93(2) (2005), 216–231.