The Inverse FFT and Fast Polynomial Multiplication
The FFT turns coefficients into values at the roots of unity in time. To finish the plan of Coefficient and Point-Value Representations, we need the way back: interpolation at the roots of unity. It turns out to be the same algorithm with replaced by its inverse and a division by . With both directions fast, two polynomials of degree-bound can be multiplied in time, and so can two -digit integers, up to the care needed with floating-point rounding.
Inverting the DFT
The DFT is with . Its inverse is almost the same matrix.
Theorem. For , the entry of is .
Proof
Let have entries and compute the entry of :
If , every term is 1 and the result is 1. Otherwise is not a multiple of , and the summation lemma (Roots of Unity and the DFT) makes the sum 0. So .
Therefore
This is a DFT of the vector with in place of , followed by a division by . The recursive FFT of the previous lesson works unchanged with (its roots satisfy the same lemmas), so the inverse FFT also takes time: change the sign of the angle in the twiddle factor, then divide every result by .
Multiplying polynomials
FFT-MULTIPLY(a, b) // coefficient vectors of degree-bound n
1 N = the smallest power of 2 with N >= len(a) + len(b) - 1
2 pad a and b with zeros to length N
3 ya = FFT(a); yb = FFT(b) // Theta(N lg N)
4 yc[k] = ya[k] * yb[k] for k = 0 .. N - 1 // Theta(N)
5 c = INVERSE-FFT(yc) // Theta(N lg N)
6 return c, rounded to the nearest integers if a and b were integersSince , the total time is . Line 6 matters: floating-point arithmetic returns values like and , and for integer inputs the true coefficients are integers, so rounding recovers them exactly as long as every error stays below .
import cmath, random
def fft(a, invert=False):
n = len(a)
if n == 1:
return list(a)
y0, y1 = fft(a[0::2], invert), fft(a[1::2], invert)
sign = -1 if invert else 1
y = [0] * n
for k in range(n // 2):
t = cmath.exp(sign * 2j * cmath.pi * k / n) * y1[k]
y[k], y[k + n // 2] = y0[k] + t, y0[k] - t
return y
def fft_multiply(a, b):
N = 1
while N < len(a) + len(b) - 1:
N *= 2
ya = fft(a + [0] * (N - len(a)))
yb = fft(b + [0] * (N - len(b)))
c = fft([p * q for p, q in zip(ya, yb)], invert=True)
raw = [v / N for v in c]
return [round(v.real) for v in raw[:len(a) + len(b) - 1]], raw
def naive(a, b):
c = [0] * (len(a) + len(b) - 1)
for i, x in enumerate(a):
for j, y in enumerate(b):
c[i + j] += x * y
return c
A, B = [5, -2, 0, 3], [1, 4, -1, 2]
c, raw = fft_multiply(A, B)
print("FFT product: ", c)
print("naive product:", naive(A, B))
print("largest distance of a raw value from its integer:",
"below 1e-9" if max(abs(v - round(v.real)) for v in raw) < 1e-9 else "large")
rng = random.Random(1)
for n in [100, 1000]:
a = [rng.randint(-1000, 1000) for _ in range(n)]
b = [rng.randint(-1000, 1000) for _ in range(n)]
print(f"n = {n}: FFT product equals the naive product: {fft_multiply(a, b)[0] == naive(a, b)}")FFT product: [5, 18, -13, 15, 8, -3, 6]
naive product: [5, 18, -13, 15, 8, -3, 6]
largest distance of a raw value from its integer: below 1e-9
n = 100: FFT product equals the naive product: True
n = 1000: FFT product equals the naive product: True
Multiplying large integers
An integer in base 10 is a polynomial evaluated at : at . Multiplying the digit polynomials and then propagating carries gives the product of the integers. Each coefficient of the product is at most , so it fits easily, and the work is for -digit numbers, against for schoolbook multiplication and for Karatsuba's algorithm.
import cmath, random
def fft(a, invert=False):
n = len(a)
if n == 1:
return list(a)
y0, y1 = fft(a[0::2], invert), fft(a[1::2], invert)
sign = -1 if invert else 1
y = [0] * n
for k in range(n // 2):
t = cmath.exp(sign * 2j * cmath.pi * k / n) * y1[k]
y[k], y[k + n // 2] = y0[k] + t, y0[k] - t
return y
def multiply_digits(x, y):
a = [int(d) for d in reversed(str(x))]
b = [int(d) for d in reversed(str(y))]
N = 1
while N < len(a) + len(b):
N *= 2
ya, yb = fft(a + [0] * (N - len(a))), fft(b + [0] * (N - len(b)))
c = [round((v / N).real) for v in fft([p * q for p, q in zip(ya, yb)], invert=True)]
carry, digits = 0, []
for v in c: # propagate carries
carry += v
digits.append(carry % 10)
carry //= 10
while carry:
digits.append(carry % 10); carry //= 10
return int("".join(map(str, reversed(digits))))
print("4096 * 1234 =", multiply_digits(4096, 1234))
rng = random.Random(7)
x, y = rng.randrange(10**499, 10**500), rng.randrange(10**499, 10**500)
p = multiply_digits(x, y)
print("two 500-digit numbers: product has", len(str(p)), "digits, matches Python:", p == x * y)
print("first 30 digits:", str(p)[:30])4096 * 1234 = 5054464
two 500-digit numbers: product has 1000 digits, matches Python: True
first 30 digits: 428222593237343509176374624340
Python's own integers use Karatsuba multiplication; libraries for huge numbers such as GMP switch to FFT-based methods (Schönhage-Strassen) beyond tens of thousands of digits. In 2019 Harvey and van der Hoeven gave an algorithm for integer multiplication in the bit model, the bound conjectured by Schönhage and Strassen in 1971.
When rounding fails
Floating-point FFTs accumulate error roughly in proportion to times the magnitude of the coefficients. With 53-bit doubles, products whose coefficients reach about can round to the wrong integer. Two standard remedies: split each coefficient into smaller pieces (for example base digits, or two 16-bit halves) so the products stay small, or use the number-theoretic transform, the same algorithm in arithmetic modulo a prime that has -th roots of unity. Its results are exact; the next lesson implements it. The Signals course discusses the same convolution theorem for signals in Fast Convolution and Fast Multiplication.
In C++
FFT multiplication in C++, with the forward and inverse transforms sharing one function, checked against the naive product on random polynomials.
#include <cmath>
#include <complex>
#include <cstdio>
#include <random>
#include <vector>
using cd = std::complex<double>;
std::vector<cd> fft(const std::vector<cd>& a, int sign) {
size_t n = a.size();
if (n == 1) return a;
std::vector<cd> even(n / 2), odd(n / 2);
for (size_t j = 0; j < n / 2; j++) { even[j] = a[2 * j]; odd[j] = a[2 * j + 1]; }
auto y0 = fft(even, sign), y1 = fft(odd, sign);
std::vector<cd> y(n);
const double PI = std::acos(-1.0);
for (size_t k = 0; k < n / 2; k++) {
cd t = std::polar(1.0, sign * 2 * PI * double(k) / double(n)) * y1[k];
y[k] = y0[k] + t;
y[k + n / 2] = y0[k] - t;
}
return y;
}
std::vector<long long> multiply(const std::vector<long long>& a, const std::vector<long long>& b) {
size_t need = a.size() + b.size() - 1, N = 1;
while (N < need) N *= 2;
std::vector<cd> fa(a.begin(), a.end()), fb(b.begin(), b.end());
fa.resize(N); fb.resize(N);
auto ya = fft(fa, 1), yb = fft(fb, 1);
for (size_t k = 0; k < N; k++) ya[k] *= yb[k];
auto c = fft(ya, -1);
std::vector<long long> out(need);
for (size_t i = 0; i < need; i++) out[i] = std::llround(c[i].real() / double(N));
return out;
}
int main() {
auto c = multiply({5, -2, 0, 3}, {1, 4, -1, 2});
std::printf("product:");
for (long long v : c) std::printf(" %lld", v);
std::printf("\n");
std::mt19937 rng(1);
for (int n : {100, 1000, 4000}) {
std::vector<long long> a(n), b(n);
for (auto& x : a) x = int(rng() % 2001) - 1000;
for (auto& x : b) x = int(rng() % 2001) - 1000;
std::vector<long long> naive(2 * n - 1, 0);
for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) naive[i + j] += a[i] * b[j];
std::printf("n = %4d: FFT matches naive: %s\n", n, multiply(a, b) == naive ? "yes" : "no");
}
}product: 5 18 -13 15 8 -3 6
n = 100: FFT matches naive: yes
n = 1000: FFT matches naive: yes
n = 4000: FFT matches naive: yes
Test yourself
How does the inverse DFT differ from the DFT?
- It uses
- It uses instead of and divides the results by
- It needs time
- It sorts the values first
To multiply two polynomials of degree-bound 300 with the FFT, what transform length is used?
- 300
- 512
- 600
- 1024
Why does an FFT product of integer polynomials need rounding at the end?
- The FFT is approximate by design
- Floating-point roots of unity introduce tiny errors, and the exact coefficients are integers
- The inverse transform divides by , which is not an integer
- Because the coefficients are negative
What is the running time of multiplying two -digit integers with an FFT on their digit polynomials (ignoring precision issues)?