#!/usr/bin/env python3 """0029_ntt.py — an exact truncated-convolution primitive with no FLINT. Programme 0029. The reference certificate uses `fmpz_poly.mul_low` for its exact truncated products. The task excludes FLINT, so this module supplies the primitive independently: fixed point at `2**SHIFT` with exact integer coefficients carried in a residue number system, and convolution by NTT over 16 primes that are ~1 mod 2**18. Everything here is exact: the CRT modulus is 480+ bits, larger than the largest coefficient any fixed-point product in the pg186 cap computation can reach (< 2**465), so the reconstruction is the true integer. Layout: a polynomial is a `(K, n)` int64 array whose row t holds the coefficients reduced mod `PRIMES[t]`. `mul_low` returns the exact truncated product followed by `x -> x >> SHIFT`, re-encoded in the same layout (the reference's `mul_low(...) // (1 << bits)`). """ from __future__ import annotations import numpy as np K = 16 N_BITS = 18 # NTT length 2**18 = 262144 L = 1 << N_BITS # --------------------------------------------------------------------------- primes def _is_prime(n): if n < 2: return False for p in (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37): if n % p == 0: return n == p d, s = n - 1, 0 while d % 2 == 0: d //= 2 s += 1 for a in (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37): x = pow(a, d, n) if x in (1, n - 1): continue for _ in range(s - 1): x = x * x % n if x == n - 1: break else: return False return True def _primes_1_mod(n_need, n_bits, lo, hi): """`n_need` primes in [lo, hi) congruent to 1 mod 2**n_bits.""" out = [] base = lo // L + 1 while len(out) < n_need: p = base * L + 1 if p >= hi: raise RuntimeError("prime search exhausted") if _is_prime(p): out.append(p) base += 1 return tuple(sorted(out)) PRIMES = _primes_1_mod(K, N_BITS, 1 << 30, 1 << 31) _PRIME_ARR = np.array(PRIMES, dtype=np.int64) assert len(PRIMES) == K def _generator(p): fac, m, d = [2], (p - 1) // 2, 2 while d * d <= m: if m % d == 0: fac.append(d) while m % d == 0: m //= d d += 1 if m > 1: fac.append(m) g = 2 while any(pow(g, (p - 1) // q, p) == 1 for q in fac): g += 1 return g # primitive 2**18-th roots of unity ROOTS = tuple(pow(_generator(p), (p - 1) // L, p) for p in PRIMES) _ROOT_ARR = np.array(ROOTS, dtype=np.int64) # CRT ladder: P_l = prod_{i= 470, CRT_MODULUS.bit_length() # --------------------------------------------------------------------------- NTT try: import numba @numba.njit(cache=False, fastmath=False, inline="always") def _modpow(b, e, p): r = 1 b %= p while e > 0: if e & 1: r = r * b % p b = b * b % p e >>= 1 return r @numba.njit(cache=False, fastmath=False) def _ntt(a, p, w, inverse): n = a.shape[0] j = 0 for i in range(1, n): bit = n >> 1 while j & bit: j ^= bit bit >>= 1 j |= bit if i < j: a[i], a[j] = a[j], a[i] m = 1 ww = w if not inverse else _modpow(w, p - 2, p) while m < n: step = _modpow(ww, n // (2 * m), p) wm = 1 for i in range(m): for k in range(i, n, 2 * m): u = a[k] v = a[k + m] * wm % p a[k] = (u + v) % p a[k + m] = (u - v) % p wm = wm * step % p m <<= 1 if inverse: ninv = _modpow(n, p - 2, p) for i in range(n): a[i] = a[i] * ninv % p @numba.njit(cache=False, parallel=True) def _ntt_all(bufs, primes, roots, inverse): for t in numba.prange(bufs.shape[0]): _ntt(bufs[t], primes[t], roots[t], inverse) _ntt_all(np.zeros((K, L), dtype=np.int64), _PRIME_ARR, _ROOT_ARR, False) HAVE_NUMBA = True except Exception: # pragma: no cover HAVE_NUMBA = False def _ntt_all_numpy(bufs, inverse): """Fallback NTT (correct, slower).""" for t in range(K): p, w = PRIMES[t], ROOTS[t] a = bufs[t] n = L j = 0 for i in range(1, n): bit = n >> 1 while j & bit: j ^= bit bit >>= 1 j |= bit if i < j: a[i], a[j] = a[j], a[i] m = 1 ww = w if not inverse else pow(w, p - 2, p) while m < n: step = pow(ww, n // (2 * m), p) ws = np.empty(m, dtype=np.int64) cur = 1 for i in range(m): ws[i] = cur cur = cur * step % p b = a.reshape(-1, 2 * m) u = b[:, :m].copy() v = b[:, m:] * ws % p b[:, :m] = (u + v) % p b[:, m:] = (u - v) % p m <<= 1 if inverse: a *= pow(n, p - 2, p) a %= p def _transform(bufs, inverse): if HAVE_NUMBA: _ntt_all(bufs, _PRIME_ARR, _ROOT_ARR, inverse) else: _ntt_all_numpy(bufs, inverse) # --------------------------------------------------------------- CRT decode/encode def decode_g(res): """Garner digits of every coefficient: returns (K, n) int64 array g.""" k, n = res.shape g = np.empty_like(res) g[0] = res[0] for t in range(1, k): p = PRIMES[t] acc = np.zeros(n, dtype=np.int64) ct = C_TABLE[t] for l in range(t): acc = (acc + g[l] * ct[l]) % p g[t] = (res[t] - acc) % p * INV_TABLE[t] % p return g def decode_ints(res): """Exact integer coefficients (list of Python ints of length n).""" k, n = res.shape g = decode_g(res) cols = g.T.tolist() p = PRIMES out = [0] * n for j in range(n): col = cols[j] x = col[k - 1] for t in range(k - 2, -1, -1): x = x * p[t] + col[t] out[j] = x return out def encode_ints(values, n, dtype=np.int64): """Residue representation of a list of nonnegative Python ints of length n.""" res = np.empty((K, n), dtype=dtype) for t in range(K): p = PRIMES[t] res[t] = [v % p for v in values] return res def encode_ints_fast(values, n): """Same as `encode_ints` but reducing via bytes limbs (faster for big values).""" res = np.empty((K, n), dtype=np.int64) # pack each value into 40 little-endian bytes, then reduce limb-wise mod p width = 44 raw = b"".join(int(v).to_bytes(width, "little") for v in values) buf = np.frombuffer(raw, dtype=np.uint8).reshape(n, width) # limbs of 28 bits nlimb = 12 # 12 * 28 = 336 bits covers the fixed-point payload limbs = np.zeros((nlimb, n), dtype=np.int64) for i in range(nlimb): lo = i * 28 chunk = buf[:, lo // 8: lo // 8 + 4].copy() shift = lo % 8 val = chunk[:, 0].astype(np.int64) val |= chunk[:, 1].astype(np.int64) << 8 val |= chunk[:, 2].astype(np.int64) << 16 val |= chunk[:, 3].astype(np.int64) << 24 limbs[i] = (val >> shift) & ((1 << 28) - 1) for t in range(K): p = PRIMES[t] acc = np.zeros(n, dtype=np.int64) pow2 = 1 base = (1 << 28) % p for i in range(nlimb): acc = (acc + limbs[i] * pow2) % p pow2 = pow2 * base % p res[t] = acc return res # --------------------------------------------------------------------------- engine class ConvolutionEngine: """Exact truncated products of fixed-point integer polynomials.""" def __init__(self, n, shift): if L < 2 * n - 1: raise ValueError("NTT length too small for this polynomial length") self.n = int(n) self.shift = int(shift) self._a = np.zeros((K, L), dtype=np.int64) self._b = np.zeros((K, L), dtype=np.int64) self.n_mul = 0 def mul_raw(self, a, b): """Exact truncated product of two (K, n) polynomials (no rescale).""" n = self.n A, B = self._a, self._b A[:, :n] = a A[:, n:] = 0 B[:, :n] = b B[:, n:] = 0 _transform(A, False) _transform(B, False) A *= B A %= _PRIME_ARR[:, None] _transform(A, True) return A[:, :n].copy() def rescale(self, raw): """`floor(x / 2**shift)` re-encoded, coefficientwise.""" n = self.n k = K g = decode_g(raw) cols = g.T.tolist() p = PRIMES shift = self.shift out = [0] * n for j in range(n): col = cols[j] x = col[k - 1] for t in range(k - 2, -1, -1): x = x * p[t] + col[t] y = x >> shift out[j] = [y % p[t] for t in range(k)] res = np.array(out, dtype=np.int64).T return np.ascontiguousarray(res) def mul_low(self, a, b): self.n_mul += 1 return self.rescale(self.mul_raw(a, b)) def shift_of(self, raw): """floor(x / 2**shift) as a list of Python ints (for reporting).""" vals = decode_ints(raw) return [v >> self.shift for v in vals]