Polynomial Multiplication
Polynomial multiplication is a binary operation that takes two polynomials as inputs and produces a polynomial.
P(x)=a0+a1x1+a2x2+...+anxn−1
Now Given
A(x)=i=0∑n−1aixi
B(x)=i=0∑m−1bixi
C(x)=A(x)B(x)
C is called the convolution of A and B.
Problem: How to multiply two polynomials in O(nlogn) time
To solve the problem, we need to apply the Fast Fourier Transform (FFT) algorithm, rather than the traditional method of multiplying each term of one polynomial by each term of the other polynomial. Then it it suffices to answer: How to multiply two polynomials using FFT?
DFT
There is two forms of representation of a polynomial. One is the coefficient form and another is the point-value form. The point-value form is the value of the polynomial at some points. The Discrete Fourier Transform (DFT) is a transformation that converts a polynomial from the coefficient form to the point-value form.
IDFT
The inverse DFT converts a polynomial from the point-value form to the coefficient form.
FFT
We have to evaluate the polynomial at o=n+m points. The simple operation costs O(n2) time. There is a better way to do this in O(nlogn) time:
Root of unity
Let ωnk denotes the kth root of unity of order n. Namely, ωnk=cosn−12πk+isinn−12πk=en−12πk
It can be easily proved that
- ωnk= ω2n2k
- ωnk=−ωnk+2n(assert n is even)
- ωnk⋅ωnl=ωnk+l
We just need to evaluate the polynomial at ωn0,ωn1,...,ωnn−1.
Assert n is even, if n is odd, we can add a zero term to the polynomial.
For 0≤k<n/2, we have
P(ωnk)=a0+a1ωnk+a2(ωnk)2+...+an(ωnk)n−1=(a0+a2(ωnk)2+a4(ωnk)4a+...+an−1(ωnk)n−2)+ωnk(a1+...+an(ωnk)n−2)=(a0+a2ω2nk+a4(ω2nk)2+...+an(ω2nk)2n−1)+ωnk(a1+...+an(ω2nk)2n−1)=R(ω2nk)+ωnkS(ω2nk)
And for P(ωnk+2n) we have
P(ωnk+2n)=P(−ωnk)=R(ω2nk)−ωnkS(ω2nk)
Then the problem is divided into two subproblems of size 2n. We can solve the problem recursively.
Why Does FFT Save Time: For every recursion, we have R(ω2nk) and S(ω2nk), so we could get P(ωnk) and P(ωnk+2n) at the same time(even if we do not need R(ω2nk) and S(ω2nk) in lower layers for calculating the value at one point, it makes sense for n points)
Time complexity
For k from 0 to n-1, calculating the DFT of two halves of P(ωnk) costs T(2n) time.
Adding the two halves of P(ωnk) costs O(n) time.
T(n)=2T(2n)+O(n)
In total, the time complexity is O(nlogn).
Now we have the point-value form of the polynomial, Let P(ωnk)=vk.
Let Q(x)=v0+v1x+v2x2+...+vnxn−1
Q(ωn−k)=i=0∑n−1vi(ωn−k)i=i=0∑n−1viωn−ik=i=0∑n−1j=0∑n−1ajωnijωn−ik=j=0∑n−1aji=0∑n−1ωni(j−k)=j=0∑n−1aji=0∑n−1(ωnj−k)i=j=0∑n−1najδj,k=naj
How to calculate Q(ωn−k)
Use the FFT algorithm to calculate the point-value form of the polynomial. Then we can get the coefficient form of the polynomial.
Time complexity
The same as DFT, O(nlogn).
Now we can multiply two polynomials in O(nlogn) time.