Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
106 changes: 106 additions & 0 deletions maths/number_theoretic_transform.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
"""
Number theoretic transform (NTT): the discrete Fourier transform computed in the
integers modulo a prime instead of the complex numbers, so convolutions of integer
sequences are exact, with no floating point rounding.

The modulus 998244353 = 119 * 2**23 + 1 is prime and 3 is a primitive root of it, so
transforms whose length is a power of two up to 2**23 are supported.

https://en.wikipedia.org/wiki/Discrete_Fourier_transform_(general)#Number-theoretic_transform
"""

MODULUS = 998244353
PRIMITIVE_ROOT = 3


def number_theoretic_transform(values: list[int], inverse: bool = False) -> list[int]:
"""
Return the NTT of ``values`` modulo 998244353, or the inverse NTT if ``inverse``.
The length must be a power of two.

>>> number_theoretic_transform([1, 2, 3, 4])
[10, 173167434, 998244351, 825076915]
>>> number_theoretic_transform(number_theoretic_transform([1, 2, 3, 4]), True)
[1, 2, 3, 4]
>>> number_theoretic_transform([7])
[7]
>>> number_theoretic_transform([1, 2, 3])
Traceback (most recent call last):
...
ValueError: the length must be a power of two
>>> number_theoretic_transform([])
Traceback (most recent call last):
...
ValueError: the length must be a power of two
"""
size = len(values)
if size == 0 or size & (size - 1):
raise ValueError("the length must be a power of two")

result = [value % MODULUS for value in values]

# Reorder the elements by reversing the bits of their indices
j = 0
for i in range(1, size):
bit = size >> 1
while j & bit:
j ^= bit
bit >>= 1
j |= bit
if i < j:
result[i], result[j] = result[j], result[i]

length = 2
while length <= size:
root = pow(PRIMITIVE_ROOT, (MODULUS - 1) // length, MODULUS)
if inverse:
root = pow(root, -1, MODULUS)
half = length // 2
for start in range(0, size, length):
twiddle = 1
for offset in range(start, start + half):
even = result[offset]
odd = result[offset + half] * twiddle % MODULUS
result[offset] = (even + odd) % MODULUS
result[offset + half] = (even - odd) % MODULUS
twiddle = twiddle * root % MODULUS
length *= 2

if inverse:
size_inverse = pow(size, -1, MODULUS)
result = [value * size_inverse % MODULUS for value in result]
return result


def convolve(first: list[int], second: list[int]) -> list[int]:
"""
Return the convolution (polynomial product) of two integer sequences modulo
998244353 using the NTT.

>>> convolve([1, 2, 3], [4, 5])
[4, 13, 22, 15]
>>> convolve([1, 1], [1, 1])
[1, 2, 1]
>>> convolve([5], [7])
[35]
>>> convolve([2, 3], [])
[]
>>> convolve([MODULUS - 1, 1], [MODULUS - 1, 1])
[1, 998244351, 1]
"""
if not first or not second:
return []
result_length = len(first) + len(second) - 1
size = 1
while size < result_length:
size *= 2
transformed_first = number_theoretic_transform(first + [0] * (size - len(first)))
transformed_second = number_theoretic_transform(second + [0] * (size - len(second)))
product = [a * b % MODULUS for a, b in zip(transformed_first, transformed_second)]
return number_theoretic_transform(product, inverse=True)[:result_length]


if __name__ == "__main__":
import doctest

doctest.testmod()
Loading