|
| 1 | +#ifndef WEILYCODER_POLY_NTT_HPP |
| 2 | +#define WEILYCODER_POLY_NTT_HPP |
| 3 | + |
| 4 | +#include "../number-theory/mod_utility.hpp" |
| 5 | +#include "../number-theory/primitive_root.hpp" |
| 6 | +#include "fft_utility.hpp" |
| 7 | +#include <cstdint> |
| 8 | +#include <vector> |
| 9 | + |
| 10 | +namespace weilycoder { |
| 11 | +/** |
| 12 | + * @brief Number Theoretic Transform (NTT) |
| 13 | + * @tparam mod The prime modulus |
| 14 | + * @tparam inverse Whether to perform the inverse NTT |
| 15 | + * @tparam bit32 Whether to use 32-bit modular multiplication |
| 16 | + * @tparam root A primitive root modulo mod |
| 17 | + * @param y The input/output vector to be transformed |
| 18 | + */ |
| 19 | +template <uint64_t mod, bool inverse = false, bool bit32 = false, |
| 20 | + uint64_t root = prime_primitive_root<mod>()> |
| 21 | +void ntt(std::vector<uint64_t> &y) { |
| 22 | + static_assert(is_prime(mod), "mod must be a prime"); |
| 23 | + fft_change(y); |
| 24 | + size_t len = y.size(); |
| 25 | + if (len == 0 || (len & (len - 1)) != 0) |
| 26 | + throw std::invalid_argument("Length of input vector must be a power of two"); |
| 27 | + if ((mod - 1) % len != 0) |
| 28 | + throw std::invalid_argument( |
| 29 | + "mod - 1 must be divisible by the length of input vector"); |
| 30 | + constexpr uint64_t g = inverse ? mod_pow<bit32>(root, mod - 2, mod) : root; |
| 31 | + for (size_t h = 2; h <= len; h <<= 1) { |
| 32 | + uint64_t wn = mod_pow<bit32>(g, (mod - 1) / h, mod); |
| 33 | + for (size_t j = 0; j < len; j += h) { |
| 34 | + uint64_t w = 1; |
| 35 | + for (size_t k = j; k < j + (h >> 1); ++k) { |
| 36 | + uint64_t u = y[k]; |
| 37 | + uint64_t t = mod_mul<bit32>(w, y[k + (h >> 1)], mod); |
| 38 | + y[k] = mod_add<bit32>(u, t, mod); |
| 39 | + y[k + (h >> 1)] = mod_sub<bit32>(u, t, mod); |
| 40 | + w = mod_mul<bit32>(w, wn, mod); |
| 41 | + } |
| 42 | + } |
| 43 | + } |
| 44 | + if constexpr (inverse) { |
| 45 | + uint64_t inv_len = mod_pow<bit32>(len, mod - 2, mod); |
| 46 | + for (size_t i = 0; i < len; ++i) |
| 47 | + y[i] = mod_mul<bit32>(y[i], inv_len, mod); |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +/** |
| 52 | + * @brief Number Theoretic Transform (NTT) using 32-bit modular multiplication |
| 53 | + * @tparam mod The prime modulus |
| 54 | + * @tparam inverse Whether to perform the inverse NTT |
| 55 | + * @tparam root A primitive root modulo mod |
| 56 | + * @param y The input/output vector to be transformed |
| 57 | + */ |
| 58 | +template <uint64_t mod, bool inverse = false, uint64_t root = prime_primitive_root(mod)> |
| 59 | +void ntt_32(std::vector<uint64_t> &y) { |
| 60 | + ntt<mod, inverse, true, root>(y); |
| 61 | +} |
| 62 | +} // namespace weilycoder |
| 63 | + |
| 64 | +#endif |
0 commit comments