defFFT(P): n = len(P) if n == 1: return P even = FFT(P[0::2]) odd = FFT(P[1::2]) w = math.e ** (-2j * math.pi / n) y = [0] * n for i inrange(n//2): y[i] = even[i] + w ** i * odd[i] y[i + n//2] = even[i] - w ** i * odd[i] return y
非2的幂的情况
这里采用补0的方式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
import math
defFFT(P): n = len(P) old_n = n if n == 1: return P if n & (n - 1) != 0: new_n = 1 << n.bit_length() P = P + [0] * (new_n - n) n = new_n even = FFT(P[0::2]) odd = FFT(P[1::2]) w = math.e ** (-2j * math.pi / n) y = [0] * n for i inrange(n//2): y[i] = even[i] + w ** i * odd[i] y[i + n//2] = even[i] - w ** i * odd[i] return y[:old_n]