Fast Multiplication with the FFT
Multiplying two polynomials, or two huge integers, is a convolution of their coefficient or digit lists. Schoolbook multiplication takes steps; the FFT does it in . This is how computer algebra systems multiply polynomials with millions of terms, how is computed to trillions of digits, and how post-quantum cryptography multiplies polynomials quickly.
Polynomials
has coefficients : a convolution. With the FFT: pad both coefficient lists to length at least of the product, transform, multiply pointwise, transform back. Evaluating the FFT is evaluating the polynomial at the roots of unity, and the inverse FFT is interpolation.
import numpy as np
a = np.array([3, 0, 2, 5]) # 3 + 2z^2 + 5z^3
b = np.array([1, 4, 0, 0, 7]) # 1 + 4z + 7z^4
n = len(a) + len(b) - 1
N = 1 << (n - 1).bit_length()
c_fft = np.fft.irfft(np.fft.rfft(a, N) * np.fft.rfft(b, N), N)[:n]
print("FFT product: ", np.round(c_fft).astype(int).tolist())
print("schoolbook product:", np.convolve(a, b).tolist())FFT product: [3, 12, 2, 13, 41, 0, 14, 35]
schoolbook product: [3, 12, 2, 13, 41, 0, 14, 35]
Big integers
An integer in base 10 is a polynomial evaluated at . Multiply the digit polynomials with the FFT, then propagate carries:
import numpy as np
def fft_multiply(x: int, y: int) -> int:
a = [int(d) for d in str(x)[::-1]] # least significant digit first
b = [int(d) for d in str(y)[::-1]]
n = len(a) + len(b) - 1
N = 1 << (n - 1).bit_length()
c = np.rint(np.fft.irfft(np.fft.rfft(a, N) * np.fft.rfft(b, N), N)[:n]).astype(np.int64)
result, carry = [], 0
for v in c.tolist():
carry += v
result.append(carry % 10)
carry //= 10
while carry:
result.append(carry % 10)
carry //= 10
return int("".join(map(str, result[::-1])))
x = int("31415926535897932384626433832795028841971693993751")
y = int("27182818284590452353602874713526624977572470936999")
print(fft_multiply(x, y) == x * y)
print(str(fft_multiply(x, y))[:30] + "...")True
853973422267356706546355086954...
Floating-point FFTs work as long as rounding errors stay below 0.5 in every coefficient; for very long numbers libraries use larger bases with care, or exact number-theoretic transforms (FFTs modulo a prime).
How much faster?
import math
for digits in (10**3, 10**5, 10**7, 10**9):
school = digits ** 2
N = 1 << (2 * digits - 1).bit_length()
fft = 3 * N * math.log2(N)
print(f"{digits:>12,d} digits: schoolbook {school:.1e} ops, FFT about {fft:.1e} ops, ratio {school / fft:.0e}") 1,000 digits: schoolbook 1.0e+06 ops, FFT about 6.8e+04 ops, ratio 1e+01
100,000 digits: schoolbook 1.0e+10 ops, FFT about 1.4e+07 ops, ratio 7e+02
10,000,000 digits: schoolbook 1.0e+14 ops, FFT about 2.5e+09 ops, ratio 4e+04
1,000,000,000 digits: schoolbook 1.0e+18 ops, FFT about 2.0e+11 ops, ratio 5e+06
The FFT's overhead makes it lose on small numbers. GMP uses schoolbook multiplication up to a few hundred digits, then Karatsuba () and Toom-Cook variants, and switches to its FFT only at roughly 3000 to 10000 64-bit words (about 60,000 to 200,000 decimal digits), depending on the CPU.
In software
- Python's own
intuses Karatsuba multiplication for large operands; GMP andgmpy2use Schönhage-Strassen-style FFTs;numpy.polynomialmultiplies with direct convolution. - The number-theoretic transform is used in ML-KEM (Learning With Errors) to multiply polynomials modulo 3329.
Exercises
Exercise 1: Size of the FFT
You multiply two polynomials of degree 1000. What is the smallest power-of-two FFT length that avoids wrap-around?
Answer
Solution
The product has degree 2000, so 2001 coefficients; the next power of two is 2048.
Exercise 2: Evaluation and interpolation
Explain the FFT multiplication algorithm as "evaluate, multiply, interpolate".
Answer
FFT evaluates both polynomials at the -th roots of unity, the values are multiplied pointwise, and the inverse FFT interpolates the product polynomial from its values.
Solution
A polynomial of degree below is determined by its values at points. Choosing the roots of unity as points makes both evaluation and interpolation cost via the FFT, instead of for arbitrary points.
Exercise 3: Square a number (code)
Use the FFT method to compute and compare with Python.
Answer
15241578750190521, matching Python.
Solution
import numpy as np
x = 123456789
a = [int(d) for d in str(x)[::-1]]
N = 32
c = np.rint(np.fft.irfft(np.fft.rfft(a, N) ** 2, N)).astype(np.int64)
value = sum(int(v) * 10 ** i for i, v in enumerate(c.tolist()))
print(value, value == x * x)15241578750190521 True
Summing performs the carries implicitly with Python's big integers.
Test yourself
Multiplying polynomials is a…
- sum of coefficients
- convolution of coefficient lists
- pointwise product of coefficients
- sorting problem
FFT multiplication of two -digit numbers takes about…
- (times a slowly growing factor)
Why do exact big-number libraries often use number-theoretic transforms?
- they are easier to type
- they avoid floating-point rounding errors entirely
- they need no multiplication
- they work only for primes