Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
ntt.H
Go to the documentation of this file.
1/*
2 Aleph_w
3
4 Data structures & Algorithms
5 version 2.0.0b
6 https://github.com/lrleon/Aleph-w
7
8 This file is part of Aleph-w library
9
10 Copyright (c) 2002-2026 Leandro Rabindranath Leon
11
12 Permission is hereby granted, free of charge, to any person obtaining a copy
13 of this software and associated documentation files (the "Software"), to deal
14 in the Software without restriction, including without limitation the rights
15 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16 copies of the Software, and to permit persons to whom the Software is
17 furnished to do so, subject to the following conditions:
18
19 The above copyright notice and this permission notice shall be included in all
20 copies or substantial portions of the Software.
21
22 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28 SOFTWARE.
29*/
30
43# ifndef NTT_H
44# define NTT_H
45
46# if !defined(__SIZEOF_INT128__)
47# error "ntt.H requires compiler support for __uint128_t"
48# endif
49
50# include <algorithm>
51# include <cstdlib>
52# include <cstdint>
53# include <future>
54# include <limits>
55# include <memory>
56# include <string>
57# include <string_view>
58# include <type_traits>
59# include <utility>
60
61# if (defined(__GNUC__) or defined(__clang__)) \
62 and (defined(__x86_64__) or defined(__i386__) \
63 or defined(_M_X64) or defined(_M_IX86))
64# include <immintrin.h>
65# define ALEPH_NTT_HAS_X86_AVX2_DISPATCH 1
66# define ALEPH_NTT_AVX2_TARGET __attribute__((target("avx2")))
67# else
68# define ALEPH_NTT_HAS_X86_AVX2_DISPATCH 0
69# endif
70
71# if (defined(__GNUC__) or defined(__clang__)) \
72 and (defined(__aarch64__) or defined(_M_ARM64))
73# include <arm_neon.h>
74# define ALEPH_NTT_HAS_ARM_NEON_DISPATCH 1
75# else
76# define ALEPH_NTT_HAS_ARM_NEON_DISPATCH 0
77# endif
78
79# if ALEPH_NTT_HAS_ARM_NEON_DISPATCH and defined(__linux__)
80# include <sys/auxv.h>
81# include <asm/hwcap.h>
82# endif
83
84# include <ah-errors.H>
85# include <modular_arithmetic.H>
86# include <thread_pool.H>
87# include <tpl_array.H>
88
89namespace Aleph
90{
113 template <uint64_t MOD = 998244353ULL, uint64_t ROOT = 3ULL>
114 class NTT
115 {
116 static_assert(MOD > 1, "NTT requires MOD > 1");
117 static_assert((MOD & 1ULL) == 1ULL, "NTT requires an odd modulus");
118 static_assert(ROOT > 0 and ROOT < MOD, "NTT root must lie in (0, MOD)");
119
120 public:
122 enum class NTTSimdBackend
123 {
124 scalar,
125 avx2,
126 neon
127 };
128
129 private:
130 enum class SimdPreference
131 {
132 automatic,
134 avx2_only,
136 };
137
138 enum class Representation
139 {
140 standard,
142 };
143
144 static constexpr MontgomeryCtx mctx_ = montgomery_ctx_for_mod<MOD>();
145
146 [[nodiscard]] static constexpr bool
147 is_power_of_two(const size_t n) noexcept
148 {
149 return n != 0 and (n & (n - 1)) == 0;
150 }
151
152 [[nodiscard]] static constexpr uint64_t
153 add_mod(const uint64_t lhs,
154 const uint64_t rhs) noexcept
155 {
156 const __uint128_t sum = static_cast<__uint128_t>(lhs) + rhs;
157 return static_cast<uint64_t>(sum >= MOD ? sum - MOD : sum);
158 }
159
160 [[nodiscard]] static constexpr uint64_t
161 sub_mod(const uint64_t lhs,
162 const uint64_t rhs) noexcept
163 {
164 return lhs >= rhs ? lhs - rhs : MOD - (rhs - lhs);
165 }
166
167 [[nodiscard]] static constexpr bool
169 {
170 return MOD <= std::numeric_limits<uint64_t>::max() / 2;
171 }
172
173 [[nodiscard]] static constexpr uint64_t
174 pow_mod_constexpr(uint64_t base,
175 uint64_t exp) noexcept
176 {
177 if (MOD == 1)
178 return 0;
179
180 uint64_t result = 1;
181 base %= MOD;
182 while (exp > 0)
183 {
184 if (exp & 1ULL)
185 result = static_cast<uint64_t>(
186 (static_cast<__uint128_t>(result) * base) % MOD);
187 base = static_cast<uint64_t>(
188 (static_cast<__uint128_t>(base) * base) % MOD);
189 exp >>= 1;
190 }
191
192 return result;
193 }
194
195 [[nodiscard]] static constexpr uint64_t
197 {
198 uint64_t value = MOD - 1;
199 uint64_t size = 1;
200 while ((value & 1ULL) == 0)
201 {
202 size <<= 1;
203 value >>= 1;
204 }
205 return size;
206 }
207
208 [[nodiscard]] static constexpr bool
209 supports_power_of_two_size(const size_t n) noexcept
210 {
211 return is_power_of_two(n)
212 and n <= static_cast<size_t>(max_transform_size_impl());
213 }
214
215 [[nodiscard]] static constexpr bool
216 supports_root_order(const uint64_t order) noexcept
217 {
218 return order != 0 and (MOD - 1) % order == 0;
219 }
220
221 [[nodiscard]] static constexpr bool
222 supports_bluestein_size(const size_t n) noexcept
223 {
224 if (n <= 1 or is_power_of_two(n))
225 return false;
226
227 if (n > static_cast<size_t>((MOD - 1) / 2))
228 return false;
229
230 const uint64_t order = static_cast<uint64_t>(n) * 2ULL;
231 if (not supports_root_order(order))
232 return false;
233
234 if (n > std::numeric_limits<size_t>::max() / 2)
235 return false;
236
237 const size_t required = n * 2 - 1;
238 size_t conv_size = 1;
239 while (conv_size < required)
240 {
241 if (conv_size > std::numeric_limits<size_t>::max() / 2)
242 return false;
243 conv_size <<= 1;
244 }
245
246 return supports_power_of_two_size(conv_size);
247 }
248
249 static void
250 validate_root_order(const uint64_t order,
251 const char * const ctx)
252 {
253 ah_invalid_argument_if(order == 0)
254 << ctx << ": root order must be positive";
256 << ctx << ": order " << order
257 << " does not divide MOD - 1 (" << (MOD - 1) << ")";
258 }
259
260 [[nodiscard]] static constexpr uint64_t
261 primitive_root_of_order(const uint64_t order)
262 {
263 return pow_mod_constexpr(ROOT, (MOD - 1) / order);
264 }
265
266 static void
268 const char * const ctx)
269 {
271 << ctx << ": size must be positive";
273 << ctx << ": size " << n
274 << " is not supported by MOD " << MOD
275 << " (power-of-two sizes require n | 2^k <= "
277 << "; Bluestein sizes require 2*n | (MOD - 1) and an internal "
278 << "power-of-two convolution size <= " << max_transform_size() << ")";
279 }
280
281 [[nodiscard]] static size_t
283 const char * const ctx)
284 {
285 if (n <= 1)
286 return 1;
287
288 size_t value = 1;
289 while (value < n)
290 {
291 ah_overflow_error_if(value > std::numeric_limits<size_t>::max() / 2)
292 << ctx << ": next power of two overflows size_t for requested size "
293 << n;
294 value <<= 1;
295 }
296
297 return value;
298 }
299
300 [[nodiscard]] static Array<uint64_t>
302 const size_t n)
303 {
305 for (size_t i = 0; i < n; ++i)
306 output(i) = 0;
307
308 for (size_t i = 0; i < input.size(); ++i)
309 output(i) = input[i] % MOD;
310
311 return output;
312 }
313
314 [[nodiscard]] static Array<uint64_t>
316 const size_t length)
317 {
318 ah_invalid_argument_if(length > input.size())
319 << "NTT::prefix_copy: length " << length
320 << " exceeds input size " << input.size();
321
323 output.reserve(length);
324 for (size_t i = 0; i < length; ++i)
325 output.append(input[i]);
326 return output;
327 }
328
329 public:
330 static constexpr uint64_t mod = MOD;
331 static constexpr uint64_t root = ROOT;
332
333 [[nodiscard]] static constexpr const char *
334 simd_backend_name(const NTTSimdBackend backend) noexcept
335 {
336 switch (backend)
337 {
339 return "avx2";
341 return "neon";
343 default:
344 return "scalar";
345 }
346 }
347
348 private:
349 [[nodiscard]] static constexpr const char *
350 simd_preference_name(const SimdPreference preference) noexcept
351 {
352 switch (preference)
353 {
355 return "scalar";
357 return "avx2";
359 return "neon";
361 default:
362 return "auto";
363 }
364 }
365
366 [[nodiscard]] static SimdPreference
368 {
369 if (const char *mode = std::getenv("ALEPH_NTT_SIMD");
370 mode != nullptr and mode[0] != '\0')
371 {
372 const std::string_view value(mode);
373 if (value == "scalar")
375 if (value == "avx2")
377 if (value == "neon")
379 }
380
382 }
383
384 [[nodiscard]] static NTTSimdBackend
393
394 public:
396 [[nodiscard]] static bool
398 {
399# if ALEPH_NTT_HAS_X86_AVX2_DISPATCH
400 static const bool available = []() noexcept
401 {
402 __builtin_cpu_init();
403 return static_cast<bool>(__builtin_cpu_supports("avx2"));
404 }();
405 return available;
406# else
407 return false;
408# endif
409 }
410
412 [[nodiscard]] static bool
414 {
415# if ALEPH_NTT_HAS_ARM_NEON_DISPATCH
416# if defined(__linux__) and defined(HWCAP_ASIMD)
417 static const bool available = []() noexcept
418 {
419 return (getauxval(AT_HWCAP) & HWCAP_ASIMD) != 0;
420 }();
421 return available;
422# else
423 return true;
424# endif
425# else
426 return false;
427# endif
428 }
429
431 [[nodiscard]] static NTTSimdBackend
432 simd_backend() noexcept
433 {
434 const NTTSimdBackend detected = detected_simd_backend();
435 switch (simd_preference())
436 {
440 return detected == NTTSimdBackend::avx2 ?
444 return detected == NTTSimdBackend::neon ?
448 default:
449 return detected;
450 }
451 }
452
454 [[nodiscard]] static const char *
456 {
458 }
459
465 class Plan
466 {
467 enum class Strategy
468 {
471 };
472
474 size_t n_ = 0;
475 size_t log_n_ = 0;
479 uint64_t inv_n_ = 0;
480 uint64_t inv_n_std_ = 1;
481 size_t bluestein_size_ = 0;
486 std::shared_ptr<const Plan> bluestein_plan_;
487
488 template <typename F>
489 static void
491 const size_t count,
492 F && fn,
493 const size_t chunk_size)
494 {
495 if (count == 0)
496 return;
497
498 if (pool != nullptr and pool->num_threads() > 1 and count > 1)
499 {
500 parallel_for_index(*pool, 0, count, std::forward<F>(fn),
501 chunk_size);
502 return;
503 }
504
505 for (size_t i = 0; i < count; ++i)
506 fn(i);
507 }
508
509 void
511 const Array<uint64_t> & twiddles,
512 const size_t base,
513 const size_t half,
514 const size_t offset,
515 const size_t begin,
516 const size_t end) const
517 {
518 for (size_t j = begin; j < end; ++j)
519 {
520 const uint64_t u = a[base + j];
521 const uint64_t v =
522 mont_mul(a[base + j + half], twiddles[offset + j], mctx_);
523 a(base + j) = add_mod(u, v);
524 a(base + j + half) = sub_mod(u, v);
525 }
526 }
527
528 [[nodiscard]] bool
529 should_use_avx2(ThreadPool * const pool) const noexcept
530 {
531# if !ALEPH_NTT_HAS_X86_AVX2_DISPATCH
532 (void) pool;
533 return false;
534# else
536 return false;
537
538 if (pool != nullptr and pool->num_threads() > 1)
539 return false;
540
542# endif
543 }
544
545 [[nodiscard]] bool
546 should_use_neon(ThreadPool * const pool) const noexcept
547 {
548# if !ALEPH_NTT_HAS_ARM_NEON_DISPATCH
549 (void) pool;
550 return false;
551# else
553 return false;
554
555 if (pool != nullptr and pool->num_threads() > 1)
556 return false;
557
559# endif
560 }
561
562# if ALEPH_NTT_HAS_X86_AVX2_DISPATCH
563 [[nodiscard]] static __m256i
564 avx2_cmp_ge_u64(const __m256i lhs,
565 const __m256i rhs) noexcept ALEPH_NTT_AVX2_TARGET
566 {
567 alignas(32) static const uint64_t sign_bits[4] = {
568 0x8000000000000000ULL,
569 0x8000000000000000ULL,
570 0x8000000000000000ULL,
571 0x8000000000000000ULL
572 };
573 const __m256i sign =
574 _mm256_load_si256(reinterpret_cast<const __m256i *>(sign_bits));
575 const __m256i lhs_signed = _mm256_xor_si256(lhs, sign);
576 const __m256i rhs_signed = _mm256_xor_si256(rhs, sign);
577 const __m256i gt = _mm256_cmpgt_epi64(lhs_signed, rhs_signed);
578 const __m256i eq = _mm256_cmpeq_epi64(lhs, rhs);
579 return _mm256_or_si256(gt, eq);
580 }
581
582 static void
583 avx2_apply_chunk(uint64_t * const low,
584 uint64_t * const high,
585 const uint64_t * const twiddle_ptr) ALEPH_NTT_AVX2_TARGET
586 {
587 alignas(32) uint64_t products[4];
588 for (size_t lane = 0; lane < 4; ++lane)
589 products[lane] = mont_mul(high[lane], twiddle_ptr[lane], mctx_);
590
591 alignas(32) static const uint64_t mod_lanes[4] = {MOD, MOD, MOD, MOD};
592 const __m256i modv =
593 _mm256_load_si256(reinterpret_cast<const __m256i *>(mod_lanes));
594 const __m256i u =
595 _mm256_loadu_si256(reinterpret_cast<const __m256i *>(low));
596 const __m256i v =
597 _mm256_load_si256(reinterpret_cast<const __m256i *>(products));
598
599 const __m256i sum = _mm256_add_epi64(u, v);
600 const __m256i sum_minus_mod = _mm256_sub_epi64(sum, modv);
601 const __m256i sum_mask = avx2_cmp_ge_u64(sum, modv);
602 const __m256i sum_result = _mm256_blendv_epi8(sum, sum_minus_mod, sum_mask);
603
604 const __m256i diff = _mm256_sub_epi64(u, v);
605 const __m256i vu = _mm256_sub_epi64(v, u);
606 const __m256i diff_alt = _mm256_sub_epi64(modv, vu);
607 const __m256i diff_mask = avx2_cmp_ge_u64(u, v);
608 const __m256i diff_result =
609 _mm256_blendv_epi8(diff_alt, diff, diff_mask);
610
611 _mm256_storeu_si256(reinterpret_cast<__m256i *>(low), sum_result);
612 _mm256_storeu_si256(reinterpret_cast<__m256i *>(high), diff_result);
613 }
614
615 void
616 apply_butterflies_avx2(Array<uint64_t> & a,
617 const Array<uint64_t> & twiddles) const ALEPH_NTT_AVX2_TARGET
618 {
619 for (size_t stage = 0; stage < log_n_; ++stage)
620 {
621 const size_t half = static_cast<size_t>(1) << stage;
622 const size_t len = half << 1;
623 const size_t blocks = n_ / len;
624 const size_t offset = half - 1;
625
626 for (size_t block = 0; block < blocks; ++block)
627 {
628 const size_t base = block * len;
629 size_t j = 0;
630 for (; j + 4 <= half; j += 4)
631 avx2_apply_chunk(&a(base + j),
632 &a(base + j + half),
633 &twiddles[offset + j]);
634 apply_scalar_butterfly_range(a, twiddles, base, half, offset,
635 j, half);
636 }
637 }
638 }
639# endif
640
641# if ALEPH_NTT_HAS_ARM_NEON_DISPATCH
642 static void
643 neon_apply_chunk(uint64_t * const low,
644 uint64_t * const high,
645 const uint64_t * const twiddle_ptr)
646 {
647 alignas(16) uint64_t products[2];
648 for (size_t lane = 0; lane < 2; ++lane)
649 products[lane] = mont_mul(high[lane], twiddle_ptr[lane], mctx_);
650
651 const uint64x2_t modv = vdupq_n_u64(MOD);
652 const uint64x2_t u = vld1q_u64(low);
653 const uint64x2_t v = vld1q_u64(products);
654 const uint64x2_t sum = vaddq_u64(u, v);
655 const uint64x2_t sum_minus_mod = vsubq_u64(sum, modv);
656 const uint64x2_t sum_mask = vcgeq_u64(sum, modv);
657 const uint64x2_t sum_result = vbslq_u64(sum_mask, sum_minus_mod, sum);
658
659 const uint64x2_t diff = vsubq_u64(u, v);
660 const uint64x2_t vu = vsubq_u64(v, u);
661 const uint64x2_t diff_alt = vsubq_u64(modv, vu);
662 const uint64x2_t diff_mask = vcgeq_u64(u, v);
663 const uint64x2_t diff_result = vbslq_u64(diff_mask, diff, diff_alt);
664
665 vst1q_u64(low, sum_result);
666 vst1q_u64(high, diff_result);
667 }
668
669 void
670 apply_butterflies_neon(Array<uint64_t> & a,
671 const Array<uint64_t> & twiddles) const
672 {
673 for (size_t stage = 0; stage < log_n_; ++stage)
674 {
675 const size_t half = static_cast<size_t>(1) << stage;
676 const size_t len = half << 1;
677 const size_t blocks = n_ / len;
678 const size_t offset = half - 1;
679
680 for (size_t block = 0; block < blocks; ++block)
681 {
682 const size_t base = block * len;
683 size_t j = 0;
684 for (; j + 2 <= half; j += 2)
685 neon_apply_chunk(&a(base + j),
686 &a(base + j + half),
687 &twiddles[offset + j]);
688 apply_scalar_butterfly_range(a, twiddles, base, half, offset,
689 j, half);
690 }
691 }
692 }
693# endif
694
695 void
697 {
699 bit_rev_(0) = 0;
700 for (size_t i = 1, j = 0; i < n_; ++i)
701 {
702 size_t bit = n_ >> 1;
703 for (; j & bit; bit >>= 1)
704 j ^= bit;
705 j ^= bit;
706 bit_rev_(i) = j;
707 }
708 }
709
710 void
712 {
713 if (n_ <= 1)
714 return;
715
718
719 const uint64_t mont_one = to_mont(1, mctx_);
720 for (size_t stage = 0; stage < log_n_; ++stage)
721 {
722 const size_t half = static_cast<size_t>(1) << stage;
723 const size_t len = half << 1;
724 const size_t offset = half - 1;
725
726 const uint64_t root_len = NTT::primitive_root_of_unity(len);
727 const uint64_t root_len_inv = mod_inv(root_len, MOD);
728
729 uint64_t w_fwd = mont_one;
730 uint64_t w_inv = mont_one;
731 const uint64_t w_step_fwd = to_mont(root_len, mctx_);
732 const uint64_t w_step_inv = to_mont(root_len_inv, mctx_);
733
734 for (size_t j = 0; j < half; ++j)
735 {
736 twiddles_fwd_(offset + j) = w_fwd;
737 twiddles_inv_(offset + j) = w_inv;
738 w_fwd = mont_mul(w_fwd, w_step_fwd, mctx_);
739 w_inv = mont_mul(w_inv, w_step_inv, mctx_);
740 }
741 }
742 }
743
744 void
746 {
748
749 for (size_t value = n_; value > 1; value >>= 1)
750 ++log_n_;
751
754 inv_n_ = to_mont(mod_inv(static_cast<uint64_t>(n_), MOD), mctx_);
755 }
756
757 void
759 {
761
762 ah_invalid_argument_if(n_ > std::numeric_limits<size_t>::max() / 2)
763 << "NTT::Plan: size " << n_
764 << " is too large for Bluestein convolution sizing";
765
766 const size_t required = n_ * 2 - 1;
767 bluestein_size_ = NTT::next_power_of_two(required, "NTT::Plan");
769 << "NTT::Plan: Bluestein internal size " << bluestein_size_
770 << " exceeds the power-of-two capacity of MOD " << MOD;
771
772 const uint64_t order = static_cast<uint64_t>(n_) * 2ULL;
773 NTT::validate_root_order(order, "NTT::Plan");
774
775 bluestein_plan_ = std::make_shared<Plan>(bluestein_size_);
778
779 const uint64_t z = NTT::primitive_root_of_order(order);
780 const uint64_t z_inv = mod_inv(z, MOD);
781 for (size_t i = 0; i < n_; ++i)
782 {
783 const uint64_t exponent =
784 static_cast<uint64_t>((static_cast<__uint128_t>(i) * i) % order);
785 bluestein_chirp_fwd_(i) = mod_exp(z, exponent, MOD);
786 bluestein_chirp_inv_(i) = mod_exp(z_inv, exponent, MOD);
787 }
788
791 for (size_t i = 0; i < bluestein_size_; ++i)
792 {
795 }
796
799 for (size_t i = 1; i < n_; ++i)
800 {
804
808 }
809
812 }
813
814 void
816 {
817 for (size_t i = 0; i < n_; ++i)
818 if (i < bit_rev_(i))
819 std::swap(a(i), a(bit_rev_(i)));
820 }
821
822 void
824 ThreadPool * const pool,
825 const size_t chunk_size) const
826 {
827 auto lift_one = [&a](const size_t i)
828 {
829 a(i) = to_mont(a[i] % MOD, mctx_);
830 };
831 for_each_index(pool, n_, lift_one, chunk_size);
832 }
833
834 void
836 ThreadPool * const pool,
837 const size_t chunk_size) const
838 {
839 auto scale_one = [this, &a](const size_t i)
840 {
841 a(i) = mont_mul(a[i], inv_n_, mctx_);
842 };
843 for_each_index(pool, n_, scale_one, chunk_size);
844 }
845
846 void
848 ThreadPool * const pool,
849 const size_t chunk_size) const
850 {
851 auto lower_one = [&a](const size_t i)
852 {
853 a(i) = from_mont(a[i], mctx_);
854 };
855 for_each_index(pool, n_, lower_one, chunk_size);
856 }
857
858 void
860 const Array<uint64_t> & twiddles,
861 ThreadPool * const pool,
862 const size_t chunk_size) const
863 {
864 for (size_t stage = 0; stage < log_n_; ++stage)
865 {
866 const size_t half = static_cast<size_t>(1) << stage;
867 const size_t len = half << 1;
868 const size_t blocks = n_ / len;
869 const size_t offset = half - 1;
870
871 auto butterfly_block = [this, &a, &twiddles, half, len, offset]
872 (const size_t block)
873 {
874 const size_t base = block * len;
875 apply_scalar_butterfly_range(a, twiddles, base, half, offset,
876 0, half);
877 };
878
879 for_each_index(pool, blocks, butterfly_block, chunk_size);
880 }
881 }
882
883 void
885 const bool invert,
886 ThreadPool * const pool,
887 const size_t chunk_size) const
888 {
889 const Array<uint64_t> & twiddles =
890 invert ? twiddles_inv_ : twiddles_fwd_;
891
892# if ALEPH_NTT_HAS_X86_AVX2_DISPATCH
893 if (should_use_avx2(pool))
894 {
895 apply_butterflies_avx2(a, twiddles);
896 return;
897 }
898# endif
899
900# if ALEPH_NTT_HAS_ARM_NEON_DISPATCH
901 if (should_use_neon(pool))
902 {
903 apply_butterflies_neon(a, twiddles);
904 return;
905 }
906# endif
907
908 apply_butterflies_scalar(a, twiddles, pool, chunk_size);
909 }
910
911 void
913 const bool invert,
914 ThreadPool * const pool,
915 const size_t chunk_size) const
916 {
918 << "NTT::Plan::apply_bluestein_transform: missing internal plan";
919
921 for (size_t i = 0; i < bluestein_size_; ++i)
922 work(i) = 0;
923
924 const Array<uint64_t> & input_chirp =
926 const Array<uint64_t> & output_chirp =
928 const Array<uint64_t> & kernel =
930
931 auto initialize = [&a, &work, &input_chirp](const size_t i)
932 {
933 if (i < a.size())
934 work(i) = mod_mul(a[i] % MOD, input_chirp[i], MOD);
935 };
936 for_each_index(pool, n_, initialize, chunk_size);
937
938 if (pool != nullptr and pool->num_threads() > 1)
939 bluestein_plan_->ptransform(*pool, work, false, chunk_size);
940 else
941 bluestein_plan_->transform(work, false);
942
943 auto pointwise = [&work, &kernel](const size_t i)
944 {
945 work(i) = mod_mul(work[i], kernel[i], MOD);
946 };
947 for_each_index(pool, bluestein_size_, pointwise, chunk_size);
948
949 if (pool != nullptr and pool->num_threads() > 1)
950 bluestein_plan_->ptransform(*pool, work, true, chunk_size);
951 else
952 bluestein_plan_->transform(work, true);
953
954 auto finalize = [this, &a, &work, &output_chirp, invert](const size_t i)
955 {
956 uint64_t value = mod_mul(work[i], output_chirp[i], MOD);
957 if (invert)
959 a(i) = value;
960 };
961 for_each_index(pool, n_, finalize, chunk_size);
962 }
963
964 void
966 const bool invert,
967 const Representation input_repr,
968 const Representation output_repr,
969 ThreadPool * const pool,
970 const size_t chunk_size) const
971 {
973 << "NTT::Plan::transform: input size " << a.size()
974 << " does not match plan size " << n_;
975
976 switch (strategy_)
977 {
979 if (input_repr == Representation::standard)
980 lift_input(a, pool, chunk_size);
981
982 if (n_ > 1)
983 {
985 apply_butterflies(a, invert, pool, chunk_size);
986 }
987
988 if (invert)
989 scale_inverse(a, pool, chunk_size);
990
991 if (output_repr == Representation::standard)
992 lower_output(a, pool, chunk_size);
993 break;
994
997 << "NTT::Plan::apply_transform: Bluestein path expects standard "
998 << "input representation";
1000 << "NTT::Plan::apply_transform: Bluestein path returns standard "
1001 << "output representation";
1002 apply_bluestein_transform(a, invert, pool, chunk_size);
1003 break;
1004 }
1005 }
1006
1007 [[nodiscard]] Array<uint64_t>
1009 const Array<uint64_t> & b,
1010 ThreadPool * const pool,
1011 const size_t chunk_size) const
1012 {
1013 if (a.is_empty() or b.is_empty())
1014 return {};
1015
1017 std::numeric_limits<size_t>::max()
1018 - b.size() + 1)
1019 << "NTT::Plan::multiply: product size exceeds size_t capacity";
1020
1021 const size_t required = a.size() + b.size() - 1;
1022 ah_invalid_argument_if(required > n_)
1023 << "NTT::Plan::multiply: product size " << required
1024 << " exceeds plan size " << n_;
1025
1028
1030 {
1031 apply_transform(fa, false,
1034 pool, chunk_size);
1035 apply_transform(fb, false,
1038 pool, chunk_size);
1039
1040 auto pointwise_product = [&fa, &fb](const size_t i)
1041 {
1042 fa(i) = mont_mul(fa[i], fb[i], mctx_);
1043 };
1044 for_each_index(pool, n_, pointwise_product, chunk_size);
1045
1046 apply_transform(fa, true,
1049 pool, chunk_size);
1050 }
1051 else
1052 {
1053 apply_transform(fa, false,
1056 pool, chunk_size);
1057 apply_transform(fb, false,
1060 pool, chunk_size);
1061
1062 auto pointwise_product = [&fa, &fb](const size_t i)
1063 {
1064 fa(i) = mod_mul(fa[i], fb[i], MOD);
1065 };
1066 for_each_index(pool, n_, pointwise_product, chunk_size);
1067
1068 apply_transform(fa, true,
1071 pool, chunk_size);
1072 }
1073
1074 return NTT::prefix_copy(fa, required);
1075 }
1076
1077 public:
1085 explicit Plan(const size_t n) : n_(n)
1086 {
1087 NTT::validate_supported_size(n_, "NTT::Plan");
1088 inv_n_std_ = mod_inv(static_cast<uint64_t>(n_), MOD);
1089
1092 else
1094 }
1095
1100 Plan(const Plan & other) = default;
1101
1112 Plan(Plan && other) noexcept
1113 : strategy_(std::exchange(other.strategy_, Strategy::power_of_two)),
1114 n_(std::exchange(other.n_, 0)),
1115 log_n_(std::exchange(other.log_n_, 0)),
1116 bit_rev_(std::move(other.bit_rev_)),
1117 twiddles_fwd_(std::move(other.twiddles_fwd_)),
1118 twiddles_inv_(std::move(other.twiddles_inv_)),
1119 inv_n_(std::exchange(other.inv_n_, 0)),
1120 inv_n_std_(std::exchange(other.inv_n_std_, 1)),
1121 bluestein_size_(std::exchange(other.bluestein_size_, 0)),
1122 bluestein_chirp_fwd_(std::move(other.bluestein_chirp_fwd_)),
1123 bluestein_chirp_inv_(std::move(other.bluestein_chirp_inv_)),
1124 bluestein_kernel_forward_(std::move(other.bluestein_kernel_forward_)),
1125 bluestein_kernel_inverse_(std::move(other.bluestein_kernel_inverse_)),
1126 bluestein_plan_(std::move(other.bluestein_plan_))
1127 {}
1128
1134 Plan & operator = (const Plan & other) = default;
1135
1142 Plan & operator = (Plan && other) noexcept
1143 {
1144 swap(other);
1145 return *this;
1146 }
1147
1151 void swap(Plan & other) noexcept
1152 {
1153 std::swap(strategy_, other.strategy_);
1154 std::swap(n_, other.n_);
1155 std::swap(log_n_, other.log_n_);
1156 bit_rev_.swap(other.bit_rev_);
1157 twiddles_fwd_.swap(other.twiddles_fwd_);
1158 twiddles_inv_.swap(other.twiddles_inv_);
1159 std::swap(inv_n_, other.inv_n_);
1160 std::swap(inv_n_std_, other.inv_n_std_);
1161 std::swap(bluestein_size_, other.bluestein_size_);
1162 bluestein_chirp_fwd_.swap(other.bluestein_chirp_fwd_);
1163 bluestein_chirp_inv_.swap(other.bluestein_chirp_inv_);
1164 bluestein_kernel_forward_.swap(other.bluestein_kernel_forward_);
1165 bluestein_kernel_inverse_.swap(other.bluestein_kernel_inverse_);
1166 bluestein_plan_.swap(other.bluestein_plan_);
1167 }
1168
1170 [[nodiscard]] size_t size() const noexcept
1171 {
1172 return n_;
1173 }
1174
1180 void
1182 const bool invert) const
1183 {
1184 apply_transform(a, invert,
1187 nullptr, 0);
1188 }
1189
1196 [[nodiscard]] Array<uint64_t>
1198 const bool invert = false) const
1199 {
1200 Array<uint64_t> output = input;
1201 transform(output, invert);
1202 return output;
1203 }
1204
1213 [[nodiscard]] Array<uint64_t>
1215 const Array<uint64_t> & b) const
1216 {
1217 return multiply_impl(a, b, nullptr, 0);
1218 }
1219
1228 void
1230 Array<uint64_t> & a,
1231 const bool invert,
1232 const size_t chunk_size = 0) const
1233 {
1234 apply_transform(a, invert,
1237 &pool, chunk_size);
1238 }
1239
1249 [[nodiscard]] Array<uint64_t>
1251 const Array<uint64_t> & input,
1252 const bool invert = false,
1253 const size_t chunk_size = 0) const
1254 {
1255 Array<uint64_t> output = input;
1256 ptransform(pool, output, invert, chunk_size);
1257 return output;
1258 }
1259
1270 [[nodiscard]] Array<uint64_t>
1272 const Array<uint64_t> & a,
1273 const Array<uint64_t> & b,
1274 const size_t chunk_size = 0) const
1275 {
1276 return multiply_impl(a, b, &pool, chunk_size);
1277 }
1278
1284 void
1286 const bool invert) const
1287 {
1288 for (size_t i = 0; i < batch.size(); ++i)
1289 {
1290 ah_invalid_argument_if(batch[i].size() != n_)
1291 << "NTT::Plan::transform_batch: batch item " << i
1292 << " has size " << batch[i].size()
1293 << " but plan size is " << n_;
1294 apply_transform(batch(i), invert,
1297 nullptr, 0);
1298 }
1299 }
1300
1312 void
1314 Array<Array<uint64_t>> & batch,
1315 const bool invert,
1316 const size_t chunk_size = 0) const
1317 {
1318 for (size_t i = 0; i < batch.size(); ++i)
1319 ah_invalid_argument_if(batch[i].size() != n_)
1320 << "NTT::Plan::ptransform_batch: batch item " << i
1321 << " has size " << batch[i].size()
1322 << " but plan size is " << n_;
1323
1324 if (batch.is_empty())
1325 return;
1326
1327 if (batch.size() == 1 or pool.num_threads() <= 1)
1328 {
1329 for (size_t i = 0; i < batch.size(); ++i)
1330 apply_transform(batch(i), invert,
1333 &pool, chunk_size);
1334 return;
1335 }
1336
1337 auto transform_one = [this, &batch, invert](const size_t i)
1338 {
1339 apply_transform(batch(i), invert,
1342 nullptr, 0);
1343 };
1344 parallel_for_index(pool, 0, batch.size(), transform_one, chunk_size);
1345 }
1346
1353 [[nodiscard]] Array<Array<uint64_t>>
1355 const bool invert = false) const
1356 {
1358 transform_batch(output, invert);
1359 return output;
1360 }
1361
1371 [[nodiscard]] Array<Array<uint64_t>>
1373 const Array<Array<uint64_t>> & input,
1374 const bool invert = false,
1375 const size_t chunk_size = 0) const
1376 {
1378 ptransform_batch(pool, output, invert, chunk_size);
1379 return output;
1380 }
1381 };
1382
1383 private:
1384 static void
1386 {
1387 while (not poly.is_empty() and poly.get_last() % MOD == 0)
1388 static_cast<void>(poly.remove_last());
1389 }
1390
1391 [[nodiscard]] static Array<uint64_t>
1393 {
1395 output.reserve(input.size());
1396 for (size_t i = 0; i < input.size(); ++i)
1397 output.append(input[i] % MOD);
1399 return output;
1400 }
1401
1402 [[nodiscard]] static Array<uint64_t>
1403 zero_series(const size_t n)
1404 {
1406 for (size_t i = 0; i < n; ++i)
1407 output(i) = 0;
1408 return output;
1409 }
1410
1411 [[nodiscard]] static Array<uint64_t>
1413 const size_t n)
1414 {
1416 const size_t limit = std::min(input.size(), n);
1417 for (size_t i = 0; i < limit; ++i)
1418 output(i) = input[i] % MOD;
1419 return output;
1420 }
1421
1422 [[nodiscard]] static Array<uint64_t>
1424 const size_t n)
1425 {
1427 output.reserve(std::min(input.size(), n));
1428 for (size_t i = 0; i < input.size() and i < n; ++i)
1429 output.append(input[i] % MOD);
1430 return output;
1431 }
1432
1433 [[nodiscard]] static Array<uint64_t>
1435 {
1437 output.reserve(input.size());
1438 for (size_t i = input.size(); i > 0; --i)
1439 output.append(input[i - 1] % MOD);
1440 return output;
1441 }
1442
1443 [[nodiscard]] static Array<uint64_t>
1445 const Array<uint64_t> & rhs,
1446 const size_t n)
1447 {
1449 for (size_t i = 0; i < n; ++i)
1450 {
1451 const uint64_t a = i < lhs.size() ? lhs[i] % MOD : 0;
1452 const uint64_t b = i < rhs.size() ? rhs[i] % MOD : 0;
1453 output(i) = add_mod(a, b);
1454 }
1455 return output;
1456 }
1457
1458 [[nodiscard]] static Array<uint64_t>
1460 const Array<uint64_t> & rhs,
1461 const size_t n)
1462 {
1464 for (size_t i = 0; i < n; ++i)
1465 {
1466 const uint64_t a = i < lhs.size() ? lhs[i] % MOD : 0;
1467 const uint64_t b = i < rhs.size() ? rhs[i] % MOD : 0;
1468 output(i) = sub_mod(a, b);
1469 }
1470 return output;
1471 }
1472
1473 [[nodiscard]] static Array<uint64_t>
1475 const Array<uint64_t> & rhs)
1476 {
1477 const size_t n = std::max(lhs.size(), rhs.size());
1478 Array<uint64_t> output = poly_add_series(lhs, rhs, n);
1480 return output;
1481 }
1482
1483 [[nodiscard]] static Array<uint64_t>
1485 const Array<uint64_t> & rhs)
1486 {
1487 const size_t n = std::max(lhs.size(), rhs.size());
1488 Array<uint64_t> output = poly_sub_series(lhs, rhs, n);
1490 return output;
1491 }
1492
1493 [[nodiscard]] static Array<uint64_t>
1495 const uint64_t scalar,
1496 const size_t n)
1497 {
1499 const uint64_t factor = scalar % MOD;
1500 for (size_t i = 0; i < input.size() and i < n; ++i)
1501 output(i) = mod_mul(input[i] % MOD, factor, MOD);
1502 return output;
1503 }
1504
1505 [[nodiscard]] static Array<uint64_t>
1507 const Array<uint64_t> & rhs,
1508 const size_t n)
1509 {
1510 if (n == 0)
1511 return {};
1512
1513 const Array<uint64_t> left = truncate_poly(lhs, n);
1514 const Array<uint64_t> right = truncate_poly(rhs, n);
1515 if (left.is_empty() or right.is_empty())
1516 return zero_series(n);
1517
1518 return series_prefix(multiply(left, right), n);
1519 }
1520
1521 [[nodiscard]] static Array<uint64_t>
1523 {
1524 if (coeffs.size() <= 1)
1525 return {};
1526
1528 for (size_t i = 1; i < coeffs.size(); ++i)
1529 output(i - 1) = mod_mul(coeffs[i] % MOD,
1530 static_cast<uint64_t>(i) % MOD,
1531 MOD);
1532 return output;
1533 }
1534
1535 [[nodiscard]] static Array<uint64_t>
1537 {
1539 output(0) = 0;
1540 for (size_t i = 0; i < coeffs.size(); ++i)
1541 {
1542 const uint64_t inv = mod_inv(static_cast<uint64_t>(i + 1), MOD);
1543 output(i + 1) = mod_mul(coeffs[i] % MOD, inv, MOD);
1544 }
1545 return output;
1546 }
1547
1548 [[nodiscard]] static uint64_t
1549 tonelli_shanks(const uint64_t value,
1550 const char * const ctx)
1551 {
1552 const uint64_t a = value % MOD;
1553 if (a == 0)
1554 return 0;
1555
1556 const uint64_t legendre = mod_exp(a, (MOD - 1) / 2, MOD);
1557 ah_invalid_argument_if(legendre != 1)
1558 << ctx << ": constant term " << a
1559 << " is not a quadratic residue modulo " << MOD;
1560
1561 if (MOD % 4 == 3)
1562 {
1563 const uint64_t root = mod_exp(a, (MOD + 1) / 4, MOD);
1564 return std::min(root, root == 0 ? 0 : MOD - root);
1565 }
1566
1567 uint64_t q = MOD - 1;
1568 size_t s = 0;
1569 while ((q & 1ULL) == 0)
1570 {
1571 q >>= 1;
1572 ++s;
1573 }
1574
1575 uint64_t z = 2;
1576 while (mod_exp(z, (MOD - 1) / 2, MOD) != MOD - 1)
1577 ++z;
1578
1579 uint64_t c = mod_exp(z, q, MOD);
1580 uint64_t r = mod_exp(a, (q + 1) / 2, MOD);
1581 uint64_t t = mod_exp(a, q, MOD);
1582 size_t m = s;
1583
1584 while (t != 1)
1585 {
1586 size_t i = 1;
1587 uint64_t t2i = mod_mul(t, t, MOD);
1588 while (i < m and t2i != 1)
1589 {
1590 t2i = mod_mul(t2i, t2i, MOD);
1591 ++i;
1592 }
1593
1595 << ctx << ": Tonelli-Shanks failed to converge";
1596
1597 uint64_t b = c;
1598 for (size_t j = 0; j + i + 1 < m; ++j)
1599 b = mod_mul(b, b, MOD);
1600
1601 r = mod_mul(r, b, MOD);
1602 const uint64_t bb = mod_mul(b, b, MOD);
1603 t = mod_mul(t, bb, MOD);
1604 c = bb;
1605 m = i;
1606 }
1607
1608 return std::min(r, r == 0 ? 0 : MOD - r);
1609 }
1610
1611 [[nodiscard]] static Array<Array<uint64_t>>
1613 {
1615 const size_t capacity = count == 0 ? 0 : count * 4 + 4;
1616 tree.reserve(capacity);
1617 for (size_t i = 0; i < capacity; ++i)
1618 tree.append(Array<uint64_t>());
1619 return tree;
1620 }
1621
1622 static void
1624 const Array<uint64_t> & points,
1625 const size_t node,
1626 const size_t left,
1627 const size_t right)
1628 {
1629 if (left + 1 == right)
1630 {
1631 tree(node) = {
1632 sub_mod(0, points[left] % MOD),
1633 1
1634 };
1635 return;
1636 }
1637
1638 const size_t mid = left + (right - left) / 2;
1639 build_product_tree(tree, points, node << 1, left, mid);
1640 build_product_tree(tree, points, (node << 1) | 1, mid, right);
1641 tree(node) = multiply(tree[node << 1], tree[(node << 1) | 1]);
1642 }
1643
1644 static void
1646 const char * const ctx)
1647 {
1648 for (size_t i = 0; i < points.size(); ++i)
1649 for (size_t j = i + 1; j < points.size(); ++j)
1650 ah_invalid_argument_if(points[i] % MOD == points[j] % MOD)
1651 << ctx << ": points[" << i << "] and points[" << j
1652 << "] collide modulo " << MOD;
1653 }
1654
1655 [[nodiscard]] static Array<uint64_t>
1656 poly_mod(const Array<uint64_t> & dividend,
1657 const Array<uint64_t> & divisor)
1658 {
1659 if (dividend.is_empty())
1660 return {};
1661
1662 if (divisor.is_empty())
1663 return dividend;
1664
1665 if (dividend.size() < divisor.size())
1666 return dividend;
1667
1668 return poly_divmod(dividend, divisor).second;
1669 }
1670
1671 static void
1673 const Array<uint64_t> & poly,
1675 const size_t node,
1676 const size_t left,
1677 const size_t right)
1678 {
1679 if (left + 1 == right)
1680 {
1681 output(left) = poly.is_empty() ? 0 : poly[0] % MOD;
1682 return;
1683 }
1684
1685 const size_t mid = left + (right - left) / 2;
1686 const Array<uint64_t> left_remainder =
1687 poly.size() < tree[node << 1].size() ?
1688 poly :
1689 poly_mod(poly, tree[node << 1]);
1690 const Array<uint64_t> right_remainder =
1691 poly.size() < tree[(node << 1) | 1].size() ?
1692 poly :
1693 poly_mod(poly, tree[(node << 1) | 1]);
1694
1695 multipoint_eval_recursive(tree, left_remainder, output,
1696 node << 1, left, mid);
1697 multipoint_eval_recursive(tree, right_remainder, output,
1698 (node << 1) | 1, mid, right);
1699 }
1700
1701 [[nodiscard]] static Array<uint64_t>
1703 const Array<uint64_t> & scaled_values,
1704 const size_t node,
1705 const size_t left,
1706 const size_t right)
1707 {
1708 if (left + 1 == right)
1709 return Array<uint64_t>({scaled_values[left] % MOD});
1710
1711 const size_t mid = left + (right - left) / 2;
1712 const Array<uint64_t> left_poly =
1713 interpolate_recursive(tree, scaled_values, node << 1, left, mid);
1714 const Array<uint64_t> right_poly =
1715 interpolate_recursive(tree, scaled_values, (node << 1) | 1, mid, right);
1716
1717 return poly_add_normalized(
1718 multiply(left_poly, tree[(node << 1) | 1]),
1719 multiply(right_poly, tree[node << 1]));
1720 }
1721
1722 public:
1723
1728 [[nodiscard]] static constexpr uint64_t
1730 {
1731 return max_transform_size_impl();
1732 }
1733
1740 [[nodiscard]] static constexpr bool
1741 supports_size(const size_t n) noexcept
1742 {
1743 return n > 0
1746 }
1747
1754 [[nodiscard]] static constexpr uint64_t
1756 {
1757 if (not std::is_constant_evaluated())
1758 validate_supported_size(n, "NTT::primitive_root_of_unity");
1759
1760 if (n <= 1)
1761 return 1;
1762
1763 return primitive_root_of_order(static_cast<uint64_t>(n));
1764 }
1765
1771 static void
1773 const bool invert)
1774 {
1775 Plan(a.size()).transform(a, invert);
1776 }
1777
1784 [[nodiscard]] static Array<uint64_t>
1786 const bool invert = false)
1787 {
1788 Array<uint64_t> output = input;
1789 transform(output, invert);
1790 return output;
1791 }
1792
1801 [[nodiscard]] static Array<uint64_t>
1803 const Array<uint64_t> & b)
1804 {
1805 if (a.is_empty() or b.is_empty())
1806 return {};
1807
1809 std::numeric_limits<size_t>::max()
1810 - b.size() + 1)
1811 << "NTT::multiply: product size exceeds size_t capacity";
1812
1813 const size_t required = a.size() + b.size() - 1;
1814 const size_t n =
1815 supports_size(required) ?
1816 required :
1817 next_power_of_two(required, "NTT::multiply");
1818 validate_supported_size(n, "NTT::multiply");
1819
1820 return Plan(n).multiply(a, b);
1821 }
1822
1828 static void
1830 const Array<uint64_t> & b)
1831 {
1832 a = multiply(a, b);
1833 }
1834
1849 [[nodiscard]] static Array<uint64_t>
1851 const Array<uint64_t> & b)
1852 {
1854 << "NTT::negacyclic_multiply: inputs must have positive size";
1855 ah_invalid_argument_if(a.size() != b.size())
1856 << "NTT::negacyclic_multiply: lhs size " << a.size()
1857 << " does not match rhs size " << b.size();
1858
1859 const size_t n = a.size();
1861 << "NTT::negacyclic_multiply: size " << n
1862 << " is not a power of two";
1863 ah_invalid_argument_if(n > static_cast<size_t>(max_transform_size() / 2))
1864 << "NTT::negacyclic_multiply: size " << n
1865 << " requires a primitive root of order " << (n << 1)
1866 << ", but the largest supported power-of-two order is "
1867 << max_transform_size();
1868
1869 const uint64_t twist = primitive_root_of_unity(n << 1);
1870 const uint64_t inv_twist = mod_inv(twist, MOD);
1871 Plan plan(n);
1872
1875 uint64_t power = 1;
1876 for (size_t i = 0; i < n; ++i)
1877 {
1878 lhs(i) = mod_mul(a[i] % MOD, power, MOD);
1879 rhs(i) = mod_mul(b[i] % MOD, power, MOD);
1880 power = mod_mul(power, twist, MOD);
1881 }
1882
1883 plan.transform(lhs, false);
1884 plan.transform(rhs, false);
1885 for (size_t i = 0; i < n; ++i)
1886 lhs(i) = mod_mul(lhs[i], rhs[i], MOD);
1887 plan.transform(lhs, true);
1888
1889 power = 1;
1890 for (size_t i = 0; i < n; ++i)
1891 {
1892 lhs(i) = mod_mul(lhs[i], power, MOD);
1893 power = mod_mul(power, inv_twist, MOD);
1894 }
1895
1896 return lhs;
1897 }
1898
1905 static void
1907 const bool invert)
1908 {
1909 if (batch.is_empty())
1910 return;
1911
1912 Plan(batch[0].size()).transform_batch(batch, invert);
1913 }
1914
1922 [[nodiscard]] static Array<Array<uint64_t>>
1924 const bool invert = false)
1925 {
1926 if (batch.is_empty())
1927 return {};
1928
1929 return Plan(batch[0].size()).transformed_batch(batch, invert);
1930 }
1931
1940 static void
1942 Array<uint64_t> & a,
1943 const bool invert,
1944 const size_t chunk_size = 0)
1945 {
1946 Plan(a.size()).ptransform(pool, a, invert, chunk_size);
1947 }
1948
1958 [[nodiscard]] static Array<uint64_t>
1960 const Array<uint64_t> & input,
1961 const bool invert = false,
1962 const size_t chunk_size = 0)
1963 {
1964 Array<uint64_t> output = input;
1965 ptransform(pool, output, invert, chunk_size);
1966 return output;
1967 }
1968
1979 [[nodiscard]] static Array<uint64_t>
1981 const Array<uint64_t> & a,
1982 const Array<uint64_t> & b,
1983 const size_t chunk_size = 0)
1984 {
1985 if (a.is_empty() or b.is_empty())
1986 return {};
1987
1989 std::numeric_limits<size_t>::max()
1990 - b.size() + 1)
1991 << "NTT::pmultiply: product size exceeds size_t capacity";
1992
1993 const size_t required = a.size() + b.size() - 1;
1994 const size_t n =
1995 supports_size(required) ?
1996 required :
1997 next_power_of_two(required, "NTT::pmultiply");
1998 validate_supported_size(n, "NTT::pmultiply");
1999
2000 return Plan(n).pmultiply(pool, a, b, chunk_size);
2001 }
2002
2012 static void
2014 Array<Array<uint64_t>> & batch,
2015 const bool invert,
2016 const size_t chunk_size = 0)
2017 {
2018 if (batch.is_empty())
2019 return;
2020
2021 Plan(batch[0].size()).ptransform_batch(pool, batch, invert, chunk_size);
2022 }
2023
2030 [[nodiscard]] static uint64_t
2032 const uint64_t x)
2033 {
2034 uint64_t value = 0;
2035 const uint64_t x_mod = x % MOD;
2036 for (size_t i = coeffs.size(); i > 0; --i)
2037 {
2038 value = mod_mul(value, x_mod, MOD);
2039 value = add_mod(value, coeffs[i - 1] % MOD);
2040 }
2041 return value;
2042 }
2043
2051 [[nodiscard]] static Array<uint64_t>
2053 const size_t n)
2054 {
2055 if (n == 0)
2056 return {};
2057
2059 << "NTT::poly_inverse: input polynomial must be non-empty";
2060
2061 const uint64_t c0 = coeffs[0] % MOD;
2062 ah_invalid_argument_if(c0 == 0)
2063 << "NTT::poly_inverse: constant term must be invertible modulo " << MOD;
2064
2066 inverse(0) = mod_inv(c0, MOD);
2067
2068 size_t m = 1;
2069 while (m < n)
2070 {
2071 const size_t m2 = std::min(n, m << 1);
2072 const Array<uint64_t> fg =
2073 poly_mul_trunc(truncate_poly(coeffs, m2), inverse, m2);
2074 Array<uint64_t> correction = zero_series(m2);
2075 correction(0) = sub_mod(2 % MOD, fg[0]);
2076 for (size_t i = 1; i < m2; ++i)
2077 correction(i) = fg[i] == 0 ? 0 : MOD - fg[i];
2078 inverse = poly_mul_trunc(inverse, correction, m2);
2079 m = m2;
2080 }
2081
2082 return series_prefix(inverse, n);
2083 }
2084
2092 [[nodiscard]] static std::pair<Array<uint64_t>, Array<uint64_t>>
2094 const Array<uint64_t> & divisor)
2095 {
2096 const Array<uint64_t> a = normalize_poly(dividend);
2097 const Array<uint64_t> b = normalize_poly(divisor);
2098
2100 << "NTT::poly_divmod: divisor cannot be the zero polynomial";
2101
2102 if (a.is_empty() or a.size() < b.size())
2103 return {{}, a};
2104
2105 const size_t quotient_size = a.size() - b.size() + 1;
2106 const Array<uint64_t> q_rev = poly_mul_trunc(
2107 reverse_poly(a),
2108 poly_inverse(reverse_poly(b), quotient_size),
2109 quotient_size);
2110 Array<uint64_t> quotient = reverse_poly(q_rev);
2111 trim_trailing_zeros(quotient);
2112
2114 poly_sub_normalized(a, multiply(b, quotient));
2115 if (remainder.size() >= b.size())
2118 return {quotient, remainder};
2119 }
2120
2128 [[nodiscard]] static Array<uint64_t>
2130 const size_t n)
2131 {
2132 if (n == 0)
2133 return {};
2134
2135 const uint64_t c0 = coeffs.is_empty() ? 0 : coeffs[0] % MOD;
2136 ah_invalid_argument_if(c0 != 1)
2137 << "NTT::poly_log: constant term must be 1 modulo " << MOD;
2138
2139 if (n == 1)
2140 return zero_series(1);
2141
2142 const Array<uint64_t> derivative =
2143 poly_derivative(truncate_poly(coeffs, n));
2144 const Array<uint64_t> inverse = poly_inverse(coeffs, n - 1);
2146 poly_mul_trunc(derivative, inverse, n - 1)), n);
2147 }
2148
2156 [[nodiscard]] static Array<uint64_t>
2158 const size_t n)
2159 {
2160 if (n == 0)
2161 return {};
2162
2163 const uint64_t c0 = coeffs.is_empty() ? 0 : coeffs[0] % MOD;
2164 ah_invalid_argument_if(c0 != 0)
2165 << "NTT::poly_exp: constant term must be 0 modulo " << MOD;
2166
2168 result(0) = 1;
2169
2170 size_t m = 1;
2171 while (m < n)
2172 {
2173 const size_t m2 = std::min(n, m << 1);
2174 Array<uint64_t> delta =
2175 poly_sub_series(series_prefix(coeffs, m2),
2176 poly_log(result, m2), m2);
2177 delta(0) = add_mod(delta[0], 1);
2178 result = poly_mul_trunc(result, delta, m2);
2179 m = m2;
2180 }
2181
2182 return series_prefix(result, n);
2183 }
2184
2193 [[nodiscard]] static Array<uint64_t>
2195 const size_t n)
2196 {
2197 if (n == 0)
2198 return {};
2199
2200 const Array<uint64_t> input = truncate_poly(coeffs, n);
2201 size_t lead = 0;
2202 while (lead < input.size() and input[lead] % MOD == 0)
2203 ++lead;
2204
2205 if (lead == input.size())
2206 return zero_series(n);
2207
2208 ah_invalid_argument_if((lead & 1U) != 0)
2209 << "NTT::poly_sqrt: first non-zero term appears at odd degree "
2210 << lead;
2211
2212 if (lead > 0)
2213 {
2214 const size_t shift = lead / 2;
2215 Array<uint64_t> tail;
2216 tail.reserve(input.size() - lead);
2217 for (size_t i = lead; i < input.size(); ++i)
2218 tail.append(input[i] % MOD);
2219
2220 const Array<uint64_t> rooted = poly_sqrt(tail, n - shift);
2222 for (size_t i = 0; i < rooted.size() and i + shift < n; ++i)
2223 output(i + shift) = rooted[i];
2224 return output;
2225 }
2226
2228 result(0) = tonelli_shanks(input[0], "NTT::poly_sqrt");
2229
2230 const uint64_t inv_two = mod_inv(2, MOD);
2231 size_t m = 1;
2232 while (m < n)
2233 {
2234 const size_t m2 = std::min(n, m << 1);
2235 const Array<uint64_t> quotient =
2236 poly_mul_trunc(series_prefix(input, m2),
2237 poly_inverse(result, m2), m2);
2238 result = poly_scalar_mul_series(
2239 poly_add_series(result, quotient, m2), inv_two, m2);
2240 m = m2;
2241 }
2242
2243 return series_prefix(result, n);
2244 }
2245
2253 [[nodiscard]] static Array<uint64_t>
2255 const uint64_t k,
2256 const size_t n)
2257 {
2258 if (n == 0)
2259 return {};
2260
2261 if (k == 0)
2262 {
2264 output(0) = 1;
2265 return output;
2266 }
2267
2268 const Array<uint64_t> input = truncate_poly(coeffs, n);
2269 size_t lead = 0;
2270 while (lead < input.size() and input[lead] % MOD == 0)
2271 ++lead;
2272
2273 if (lead == input.size())
2274 return zero_series(n);
2275
2276 const __uint128_t shift128 =
2277 static_cast<__uint128_t>(lead) * static_cast<__uint128_t>(k);
2278 if (shift128 >= n)
2279 return zero_series(n);
2280
2281 const size_t shift = static_cast<size_t>(shift128);
2282 const size_t target = n - shift;
2283 const uint64_t lead_coeff = input[lead] % MOD;
2284 const uint64_t inv_lead = mod_inv(lead_coeff, MOD);
2285
2286 Array<uint64_t> normalized;
2287 normalized.reserve(input.size() - lead);
2288 for (size_t i = lead; i < input.size(); ++i)
2289 normalized.append(mod_mul(input[i] % MOD, inv_lead, MOD));
2290
2291 Array<uint64_t> scaled_log = poly_log(normalized, target);
2292 for (size_t i = 0; i < scaled_log.size(); ++i)
2293 scaled_log(i) = mod_mul(scaled_log[i],
2294 static_cast<uint64_t>(k % MOD), MOD);
2295
2296 Array<uint64_t> powered = poly_exp(scaled_log, target);
2297 powered = poly_scalar_mul_series(powered, mod_exp(lead_coeff, k, MOD),
2298 target);
2299
2301 for (size_t i = 0; i < powered.size() and i + shift < n; ++i)
2302 output(i + shift) = powered[i];
2303 return output;
2304 }
2305
2312 [[nodiscard]] static Array<uint64_t>
2314 const Array<uint64_t> & points)
2315 {
2316 if (points.is_empty())
2317 return {};
2318
2319 Array<uint64_t> reduced_points = Array<uint64_t>::create(points.size());
2320 for (size_t i = 0; i < points.size(); ++i)
2321 reduced_points(i) = points[i] % MOD;
2322
2324 build_product_tree(tree, reduced_points, 1, 0, reduced_points.size());
2325
2327 for (size_t i = 0; i < output.size(); ++i)
2328 output(i) = 0;
2329
2331 1, 0, reduced_points.size());
2332 return output;
2333 }
2334
2344 [[nodiscard]] static Array<uint64_t>
2346 const Array<uint64_t> & values)
2347 {
2348 ah_invalid_argument_if(points.size() != values.size())
2349 << "NTT::interpolate: points size " << points.size()
2350 << " does not match values size " << values.size();
2351
2352 if (points.is_empty())
2353 return {};
2354
2355 Array<uint64_t> reduced_points = Array<uint64_t>::create(points.size());
2356 Array<uint64_t> reduced_values = Array<uint64_t>::create(values.size());
2357 for (size_t i = 0; i < points.size(); ++i)
2358 {
2359 reduced_points(i) = points[i] % MOD;
2360 reduced_values(i) = values[i] % MOD;
2361 }
2362
2363 validate_distinct_points(reduced_points, "NTT::interpolate");
2364
2366 build_product_tree(tree, reduced_points, 1, 0, reduced_points.size());
2367
2368 const Array<uint64_t> total_derivative = poly_derivative(tree[1]);
2369 const Array<uint64_t> weights =
2370 multipoint_eval(total_derivative, reduced_points);
2371
2372 Array<uint64_t> scaled_values = Array<uint64_t>::create(values.size());
2373 for (size_t i = 0; i < values.size(); ++i)
2374 {
2375 ah_invalid_argument_if(weights[i] == 0)
2376 << "NTT::interpolate: derivative vanished at point index " << i;
2377 scaled_values(i) = mod_mul(reduced_values[i],
2378 mod_inv(weights[i], MOD), MOD);
2379 }
2380
2381 return normalize_poly(interpolate_recursive(tree, scaled_values,
2382 1, 0, reduced_points.size()));
2383 }
2384
2406 template <uint64_t Base = (1ULL << 15)>
2407 [[nodiscard]] static Array<uint64_t>
2408 bigint_multiply(const Array<uint64_t> & a,
2409 const Array<uint64_t> & b);
2410
2427 template <uint64_t Base = (1ULL << 15)>
2428 [[nodiscard]] static Array<uint64_t>
2429 pbigint_multiply(ThreadPool & pool,
2430 const Array<uint64_t> & a,
2431 const Array<uint64_t> & b,
2432 const size_t chunk_size = 0);
2433 };
2434
2440 struct NTTPrime
2441 {
2442 uint64_t mod = 0;
2443 uint64_t root = 0;
2444 uint64_t max_power_of_two = 0;
2445 };
2446
2462 class NTTExact
2463 {
2464 public:
2465 using coeff_type = __uint128_t;
2466
2467 private:
2468 using Prime0NTT = NTT<998244353ULL, 3ULL>;
2469 using Prime1NTT = NTT<469762049ULL, 3ULL>;
2470 using Prime2NTT = NTT<1004535809ULL, 3ULL>;
2471
2472 struct CoefficientStats
2473 {
2474 uint64_t max_value = 0;
2475 size_t non_zero = 0;
2476 coeff_type sum = 0;
2477 };
2478
2479 static constexpr NTTPrime primes_[] = {
2480 {998244353ULL, 3ULL, 23ULL},
2481 {469762049ULL, 3ULL, 26ULL},
2482 {1004535809ULL, 3ULL, 21ULL}
2483 };
2484
2485 [[nodiscard]] static constexpr coeff_type
2486 exact_modulus_product_impl() noexcept
2487 {
2488 return static_cast<coeff_type>(primes_[0].mod)
2489 * static_cast<coeff_type>(primes_[1].mod)
2490 * static_cast<coeff_type>(primes_[2].mod);
2491 }
2492
2493 [[nodiscard]] static constexpr uint64_t
2494 sub_mod(const uint64_t lhs,
2495 const uint64_t rhs,
2496 const uint64_t mod) noexcept
2497 {
2498 return lhs >= rhs ? lhs - rhs : mod - (rhs - lhs);
2499 }
2500
2501 [[nodiscard]] static constexpr coeff_type
2502 add_capped(const coeff_type lhs,
2503 const coeff_type rhs,
2504 const coeff_type cap) noexcept
2505 {
2506 return lhs >= cap - rhs ? cap : lhs + rhs;
2507 }
2508
2509 [[nodiscard]] static constexpr coeff_type
2511 const coeff_type rhs,
2512 const coeff_type cap) noexcept
2513 {
2514 if (lhs == 0 or rhs == 0)
2515 return 0;
2516 return lhs > cap / rhs ? cap : lhs * rhs;
2517 }
2518
2519 [[nodiscard]] static constexpr size_t
2520 next_power_of_two(const size_t n) noexcept
2521 {
2522 if (n <= 1)
2523 return 1;
2524
2525 size_t value = 1;
2526 while (value < n)
2527 {
2528 if (value > std::numeric_limits<size_t>::max() / 2)
2529 return 0;
2530 value <<= 1;
2531 }
2532
2533 return value;
2534 }
2535
2536 template <typename PrimeNTT>
2537 [[nodiscard]] static constexpr bool
2538 prime_supports_product_size(const size_t required) noexcept
2539 {
2540 if (required == 0)
2541 return false;
2542
2543 if (PrimeNTT::supports_size(required))
2544 return true;
2545
2546 const size_t n = next_power_of_two(required);
2547 return n != 0 and PrimeNTT::supports_size(n);
2548 }
2549
2550 [[nodiscard]] static std::string
2552 {
2553 if (value == 0)
2554 return "0";
2555
2556 std::string digits;
2557 while (value > 0)
2558 {
2559 const auto digit = static_cast<unsigned>(value % 10);
2560 digits.push_back(static_cast<char>('0' + digit));
2561 value /= 10;
2562 }
2563
2564 std::reverse(digits.begin(), digits.end());
2565 return digits;
2566 }
2567
2568 [[nodiscard]] static CoefficientStats
2570 {
2571 CoefficientStats stats;
2572 const coeff_type cap = exact_modulus_product();
2573 for (size_t i = 0; i < input.size(); ++i)
2574 {
2575 const uint64_t value = input[i];
2576 if (value == 0)
2577 continue;
2578
2579 ++stats.non_zero;
2580 if (value > stats.max_value)
2581 stats.max_value = value;
2582 stats.sum = add_capped(stats.sum, static_cast<coeff_type>(value), cap);
2583 }
2584
2585 return stats;
2586 }
2587
2588 [[nodiscard]] static coeff_type
2590 const Array<uint64_t> & b)
2591 {
2592 if (a.is_empty() or b.is_empty())
2593 return 0;
2594
2595 const coeff_type cap = exact_modulus_product();
2596 const CoefficientStats lhs = analyze_coefficients(a);
2597 const CoefficientStats rhs = analyze_coefficients(b);
2598
2599 if (lhs.non_zero == 0 or rhs.non_zero == 0)
2600 return 0;
2601
2602 coeff_type bound = cap;
2603
2604 const coeff_type max_product =
2605 mul_capped(static_cast<coeff_type>(lhs.max_value),
2606 static_cast<coeff_type>(rhs.max_value), cap);
2607
2608 const coeff_type overlap_bound =
2609 mul_capped(static_cast<coeff_type>(std::min(lhs.non_zero, rhs.non_zero)),
2610 max_product, cap);
2611 if (overlap_bound < bound)
2612 bound = overlap_bound;
2613
2614 const coeff_type lhs_sum_bound =
2615 mul_capped(lhs.sum, static_cast<coeff_type>(rhs.max_value), cap);
2616 if (lhs_sum_bound < bound)
2617 bound = lhs_sum_bound;
2618
2619 const coeff_type rhs_sum_bound =
2620 mul_capped(rhs.sum, static_cast<coeff_type>(lhs.max_value), cap);
2621 if (rhs_sum_bound < bound)
2622 bound = rhs_sum_bound;
2623
2624 return bound;
2625 }
2626
2627 static void
2629 const Array<uint64_t> & b,
2630 const char * const ctx)
2631 {
2633 std::numeric_limits<size_t>::max()
2634 - b.size() + 1)
2635 << ctx << ": product size exceeds size_t capacity";
2636
2637 const size_t required = a.size() + b.size() - 1;
2638 ah_invalid_argument_if(not supports_product_size(required))
2639 << ctx << ": required product size " << required
2640 << " is not supported by the three-prime CRT pack";
2641
2642 const coeff_type bound = conservative_bound(a, b);
2643 ah_invalid_argument_if(bound >= exact_modulus_product())
2644 << ctx << ": cannot guarantee exact reconstruction inside CRT range "
2645 << coeff_to_string(exact_modulus_product())
2646 << " with conservative coefficient bound "
2647 << coeff_to_string(bound);
2648 }
2649
2650 [[nodiscard]] static coeff_type
2651 reconstruct_coefficient(const uint64_t r0,
2652 const uint64_t r1,
2653 const uint64_t r2)
2654 {
2655 static const uint64_t m0 = primes_[0].mod;
2656 static const uint64_t m1 = primes_[1].mod;
2657 static const uint64_t m2 = primes_[2].mod;
2658 static const coeff_type m0m1 =
2659 static_cast<coeff_type>(m0) * static_cast<coeff_type>(m1);
2660 static const uint64_t m0_inv_mod_m1 = mod_inv(m0 % m1, m1);
2661 static const uint64_t m0m1_inv_mod_m2 =
2662 mod_inv(static_cast<uint64_t>(m0m1 % m2), m2);
2663
2664 const uint64_t t1 =
2665 mod_mul(sub_mod(r1, r0 % m1, m1), m0_inv_mod_m1, m1);
2666 const coeff_type x01 =
2667 static_cast<coeff_type>(r0)
2668 + static_cast<coeff_type>(t1) * static_cast<coeff_type>(m0);
2669
2670 const uint64_t x01_mod_m2 = static_cast<uint64_t>(x01 % m2);
2671 const uint64_t t2 =
2672 mod_mul(sub_mod(r2, x01_mod_m2, m2), m0m1_inv_mod_m2, m2);
2673
2674 return x01 + static_cast<coeff_type>(t2) * m0m1;
2675 }
2676
2677 [[nodiscard]] static Array<coeff_type>
2679 const Array<uint64_t> & c1,
2680 const Array<uint64_t> & c2,
2681 ThreadPool * const pool,
2682 const size_t chunk_size)
2683 {
2684 ah_runtime_error_unless(c0.size() == c1.size() and c1.size() == c2.size())
2685 << "NTTExact::reconstruct_product: inconsistent residue sizes";
2686
2688
2689 auto reconstruct_one = [&output, &c0, &c1, &c2](const size_t i)
2690 {
2691 output(i) = reconstruct_coefficient(c0[i], c1[i], c2[i]);
2692 };
2693
2694 if (pool != nullptr and pool->num_threads() > 1 and c0.size() > 1)
2695 parallel_for_index(*pool, 0, c0.size(), reconstruct_one, chunk_size);
2696 else
2697 for (size_t i = 0; i < c0.size(); ++i)
2698 reconstruct_one(i);
2699
2700 return output;
2701 }
2702
2703 public:
2705 [[nodiscard]] static constexpr size_t
2706 prime_count() noexcept
2707 {
2708 return sizeof(primes_) / sizeof(primes_[0]);
2709 }
2710
2716 [[nodiscard]] static constexpr coeff_type
2718 {
2719 return exact_modulus_product_impl();
2720 }
2721
2728 [[nodiscard]] static constexpr bool
2729 supports_product_size(const size_t required) noexcept
2730 {
2731 return prime_supports_product_size<Prime0NTT>(required)
2732 and prime_supports_product_size<Prime1NTT>(required)
2733 and prime_supports_product_size<Prime2NTT>(required);
2734 }
2735
2745 [[nodiscard]] static Array<coeff_type>
2747 const Array<uint64_t> & b)
2748 {
2749 if (a.is_empty() or b.is_empty())
2750 return {};
2751
2752 validate_inputs(a, b, "NTTExact::multiply");
2753
2754 const Array<uint64_t> c0 = Prime0NTT::multiply(a, b);
2755 const Array<uint64_t> c1 = Prime1NTT::multiply(a, b);
2756 const Array<uint64_t> c2 = Prime2NTT::multiply(a, b);
2757 return reconstruct_product(c0, c1, c2, nullptr, 0);
2758 }
2759
2776 [[nodiscard]] static Array<coeff_type>
2778 const Array<uint64_t> & a,
2779 const Array<uint64_t> & b,
2780 const size_t chunk_size = 0)
2781 {
2782 if (a.is_empty() or b.is_empty())
2783 return {};
2784
2785 validate_inputs(a, b, "NTTExact::pmultiply");
2786
2787 if (pool.num_threads() <= 1)
2788 return multiply(a, b);
2789
2790 auto f0 = pool.enqueue([&a, &b]()
2791 {
2792 return Prime0NTT::multiply(a, b);
2793 });
2794 auto f1 = pool.enqueue([&a, &b]()
2795 {
2796 return Prime1NTT::multiply(a, b);
2797 });
2798 auto f2 = pool.enqueue([&a, &b]()
2799 {
2800 return Prime2NTT::multiply(a, b);
2801 });
2802
2803 const Array<uint64_t> c0 = f0.get();
2804 const Array<uint64_t> c1 = f1.get();
2805 const Array<uint64_t> c2 = f2.get();
2806 return reconstruct_product(c0, c1, c2, &pool, chunk_size);
2807 }
2808 };
2809
2810 template <uint64_t MOD, uint64_t ROOT>
2811 template <uint64_t Base>
2814 const Array<uint64_t> & b)
2815 {
2816 static_assert(Base > 1, "NTT::bigint_multiply requires Base >= 2");
2817 using ExactCoeff = NTTExact::coeff_type;
2818
2819 auto zero_digits = []()
2820 {
2822 output(0) = 0;
2823 return output;
2824 };
2825
2826 auto validate_digits = [](const Array<uint64_t> & digits,
2827 const char * const name,
2828 const char * const ctx)
2829 {
2830 for (size_t i = 0; i < digits.size(); ++i)
2831 ah_invalid_argument_if(digits[i] >= Base)
2832 << ctx << ": " << name << "[" << i << "] = " << digits[i]
2833 << " is not in [0, " << Base << ")";
2834 };
2835
2836 auto normalize_digits = [](const Array<uint64_t> & input)
2837 {
2839 output.reserve(input.size());
2840 for (size_t i = 0; i < input.size(); ++i)
2841 output.append(input[i]);
2842
2843 while (not output.is_empty() and output.get_last() == 0)
2844 static_cast<void>(output.remove_last());
2845 return output;
2846 };
2847
2848 auto propagate_carries = [&zero_digits](const Array<ExactCoeff> & coeffs)
2849 {
2850 if (coeffs.is_empty())
2851 return zero_digits();
2852
2854 output.reserve(coeffs.size() + 2);
2855
2856 ExactCoeff carry = 0;
2857 for (size_t i = 0; i < coeffs.size(); ++i)
2858 {
2859 const ExactCoeff total = coeffs[i] + carry;
2860 output.append(static_cast<uint64_t>(total % Base));
2861 carry = total / Base;
2862 }
2863
2864 while (carry > 0)
2865 {
2866 output.append(static_cast<uint64_t>(carry % Base));
2867 carry /= Base;
2868 }
2869
2870 while (output.size() > 1 and output.get_last() == 0)
2871 static_cast<void>(output.remove_last());
2872
2873 return output.is_empty() ? zero_digits() : output;
2874 };
2875
2876 validate_digits(a, "a", "NTT::bigint_multiply");
2877 validate_digits(b, "b", "NTT::bigint_multiply");
2878
2879 const Array<uint64_t> lhs = normalize_digits(a);
2880 const Array<uint64_t> rhs = normalize_digits(b);
2881 if (lhs.is_empty() or rhs.is_empty())
2882 return zero_digits();
2883
2885 std::numeric_limits<size_t>::max()
2886 - rhs.size() + 1)
2887 << "NTT::bigint_multiply: product size exceeds size_t capacity";
2888
2889 const size_t required = lhs.size() + rhs.size() - 1;
2890 const size_t internal_size =
2891 supports_size(required) ?
2892 required :
2893 next_power_of_two(required, "NTT::bigint_multiply");
2894
2895 const ExactCoeff digit_max = static_cast<ExactCoeff>(Base - 1);
2896 const ExactCoeff single_prime_bound =
2897 static_cast<ExactCoeff>(std::min(lhs.size(), rhs.size()))
2898 * digit_max * digit_max;
2899
2900 if (single_prime_bound < static_cast<ExactCoeff>(MOD)
2901 and supports_size(internal_size))
2902 {
2903 const Array<uint64_t> coeffs = multiply(lhs, rhs);
2905 for (size_t i = 0; i < coeffs.size(); ++i)
2906 exact(i) = static_cast<ExactCoeff>(coeffs[i]);
2907 return propagate_carries(exact);
2908 }
2909
2910 return propagate_carries(NTTExact::multiply(lhs, rhs));
2911 }
2912
2913 template <uint64_t MOD, uint64_t ROOT>
2914 template <uint64_t Base>
2917 const Array<uint64_t> & a,
2918 const Array<uint64_t> & b,
2919 const size_t chunk_size)
2920 {
2921 static_assert(Base > 1, "NTT::pbigint_multiply requires Base >= 2");
2922 using ExactCoeff = NTTExact::coeff_type;
2923
2924 auto zero_digits = []()
2925 {
2927 output(0) = 0;
2928 return output;
2929 };
2930
2931 auto validate_digits = [](const Array<uint64_t> & digits,
2932 const char * const name,
2933 const char * const ctx)
2934 {
2935 for (size_t i = 0; i < digits.size(); ++i)
2936 ah_invalid_argument_if(digits[i] >= Base)
2937 << ctx << ": " << name << "[" << i << "] = " << digits[i]
2938 << " is not in [0, " << Base << ")";
2939 };
2940
2941 auto normalize_digits = [](const Array<uint64_t> & input)
2942 {
2944 output.reserve(input.size());
2945 for (size_t i = 0; i < input.size(); ++i)
2946 output.append(input[i]);
2947
2948 while (not output.is_empty() and output.get_last() == 0)
2949 static_cast<void>(output.remove_last());
2950 return output;
2951 };
2952
2953 auto propagate_carries = [&zero_digits](const Array<ExactCoeff> & coeffs)
2954 {
2955 if (coeffs.is_empty())
2956 return zero_digits();
2957
2959 output.reserve(coeffs.size() + 2);
2960
2961 ExactCoeff carry = 0;
2962 for (size_t i = 0; i < coeffs.size(); ++i)
2963 {
2964 const ExactCoeff total = coeffs[i] + carry;
2965 output.append(static_cast<uint64_t>(total % Base));
2966 carry = total / Base;
2967 }
2968
2969 while (carry > 0)
2970 {
2971 output.append(static_cast<uint64_t>(carry % Base));
2972 carry /= Base;
2973 }
2974
2975 while (output.size() > 1 and output.get_last() == 0)
2976 static_cast<void>(output.remove_last());
2977
2978 return output.is_empty() ? zero_digits() : output;
2979 };
2980
2981 validate_digits(a, "a", "NTT::pbigint_multiply");
2982 validate_digits(b, "b", "NTT::pbigint_multiply");
2983
2984 const Array<uint64_t> lhs = normalize_digits(a);
2985 const Array<uint64_t> rhs = normalize_digits(b);
2986 if (lhs.is_empty() or rhs.is_empty())
2987 return zero_digits();
2988
2990 std::numeric_limits<size_t>::max()
2991 - rhs.size() + 1)
2992 << "NTT::pbigint_multiply: product size exceeds size_t capacity";
2993
2994 const size_t required = lhs.size() + rhs.size() - 1;
2995 const size_t internal_size =
2996 supports_size(required) ?
2997 required :
2998 next_power_of_two(required, "NTT::pbigint_multiply");
2999
3000 const ExactCoeff digit_max = static_cast<ExactCoeff>(Base - 1);
3001 const ExactCoeff single_prime_bound =
3002 static_cast<ExactCoeff>(std::min(lhs.size(), rhs.size()))
3003 * digit_max * digit_max;
3004
3005 if (single_prime_bound < static_cast<ExactCoeff>(MOD)
3006 and supports_size(internal_size))
3007 {
3008 const Array<uint64_t> coeffs = pmultiply(pool, lhs, rhs, chunk_size);
3010 for (size_t i = 0; i < coeffs.size(); ++i)
3011 exact(i) = static_cast<ExactCoeff>(coeffs[i]);
3012 return propagate_carries(exact);
3013 }
3014
3015 return propagate_carries(NTTExact::pmultiply(pool, lhs, rhs, chunk_size));
3016 }
3017} // namespace Aleph
3018
3019# endif // NTT_H
Exception handling system with formatted messages for Aleph-w.
#define ah_runtime_error_unless(C)
Throws std::runtime_error if condition does NOT hold.
Definition ah-errors.H:399
#define ah_overflow_error_if(C)
Throws std::overflow_error if condition holds.
Definition ah-errors.H:611
#define ah_runtime_error_if(C)
Throws std::runtime_error if condition holds.
Definition ah-errors.H:415
#define ah_invalid_argument_if(C)
Throws std::invalid_argument if condition holds.
Definition ah-errors.H:787
size_t size_t int32_t value
Definition ca-c-api.h:116
Simple dynamic array with automatic resizing and functional operations.
Definition tpl_array.H:141
constexpr size_t size() const noexcept
Return the number of elements stored in the stack.
Definition tpl_array.H:450
constexpr bool is_empty() const noexcept
Checks if the container is empty.
Definition tpl_array.H:444
void swap(Array &s) noexcept
Swap this with s
Definition tpl_array.H:313
T & get_last()
Return a modifiable reference to the last element.
Definition tpl_array.H:483
static Array create(const size_t n)
Create an array with n logical elements.
Definition tpl_array.H:245
T & append(const T &data)
Append a copy of data
Definition tpl_array.H:331
void reserve(size_t cap)
Reserves cap cells into the array.
Definition tpl_array.H:402
static coeff_type conservative_bound(const Array< uint64_t > &a, const Array< uint64_t > &b)
Definition ntt.H:2589
static constexpr coeff_type mul_capped(const coeff_type lhs, const coeff_type rhs, const coeff_type cap) noexcept
Definition ntt.H:2510
static Array< coeff_type > reconstruct_product(const Array< uint64_t > &c0, const Array< uint64_t > &c1, const Array< uint64_t > &c2, ThreadPool *const pool, const size_t chunk_size)
Definition ntt.H:2678
static constexpr coeff_type exact_modulus_product() noexcept
Product of the three CRT moduli.
Definition ntt.H:2717
static CoefficientStats analyze_coefficients(const Array< uint64_t > &input)
Definition ntt.H:2569
static coeff_type reconstruct_coefficient(const uint64_t r0, const uint64_t r1, const uint64_t r2)
Definition ntt.H:2651
__uint128_t coeff_type
Definition ntt.H:2465
static Array< coeff_type > pmultiply(ThreadPool &pool, const Array< uint64_t > &a, const Array< uint64_t > &b, const size_t chunk_size=0)
Exact parallel polynomial multiplication.
Definition ntt.H:2777
static constexpr bool prime_supports_product_size(const size_t required) noexcept
Definition ntt.H:2538
static constexpr bool supports_product_size(const size_t required) noexcept
Check whether a target product length is supported.
Definition ntt.H:2729
static constexpr size_t next_power_of_two(const size_t n) noexcept
Definition ntt.H:2520
static std::string coeff_to_string(coeff_type value)
Definition ntt.H:2551
static void validate_inputs(const Array< uint64_t > &a, const Array< uint64_t > &b, const char *const ctx)
Definition ntt.H:2628
static Array< coeff_type > multiply(const Array< uint64_t > &a, const Array< uint64_t > &b)
Exact sequential polynomial multiplication.
Definition ntt.H:2746
static constexpr size_t prime_count() noexcept
Number of CRT primes in the exact multiplier.
Definition ntt.H:2706
Precomputed plans for NTT transforms.
Definition ntt.H:466
Array< Array< uint64_t > > transformed_batch(const Array< Array< uint64_t > > &input, const bool invert=false) const
Return a transformed copy of an entire batch.
Definition ntt.H:1354
Array< uint64_t > multiply(const Array< uint64_t > &a, const Array< uint64_t > &b) const
Multiply two polynomials using this plan size.
Definition ntt.H:1214
void ptransform(ThreadPool &pool, Array< uint64_t > &a, const bool invert, const size_t chunk_size=0) const
Parallel in-place transform using a ThreadPool.
Definition ntt.H:1229
Array< uint64_t > multiply_impl(const Array< uint64_t > &a, const Array< uint64_t > &b, ThreadPool *const pool, const size_t chunk_size) const
Definition ntt.H:1008
size_t size() const noexcept
Return the transform size bound to the plan.
Definition ntt.H:1170
void initialize_twiddles()
Definition ntt.H:711
Array< uint64_t > bluestein_kernel_forward_
Definition ntt.H:484
void apply_bit_reversal(Array< uint64_t > &a) const noexcept
Definition ntt.H:815
Array< uint64_t > transformed(const Array< uint64_t > &input, const bool invert=false) const
Transform an input array and return the result.
Definition ntt.H:1197
std::shared_ptr< const Plan > bluestein_plan_
Definition ntt.H:486
uint64_t inv_n_std_
Definition ntt.H:480
Array< uint64_t > pmultiply(ThreadPool &pool, const Array< uint64_t > &a, const Array< uint64_t > &b, const size_t chunk_size=0) const
Parallel polynomial multiplication using this plan size.
Definition ntt.H:1271
Strategy strategy_
Definition ntt.H:473
Plan(const size_t n)
Construct a reusable plan for a fixed transform size.
Definition ntt.H:1085
Array< uint64_t > bluestein_chirp_inv_
Definition ntt.H:483
void swap(Plan &other) noexcept
Exchange in O(1) the tables of this plan and another.
Definition ntt.H:1151
void transform(Array< uint64_t > &a, const bool invert) const
In-place forward or inverse transform.
Definition ntt.H:1181
void ptransform_batch(ThreadPool &pool, Array< Array< uint64_t > > &batch, const bool invert, const size_t chunk_size=0) const
Parallel batch transform for equal-sized inputs.
Definition ntt.H:1313
void lift_input(Array< uint64_t > &a, ThreadPool *const pool, const size_t chunk_size) const
Definition ntt.H:823
Array< size_t > bit_rev_
Definition ntt.H:476
void initialize_power_of_two_plan()
Definition ntt.H:745
Array< uint64_t > twiddles_inv_
Definition ntt.H:478
Plan & operator=(const Plan &other)=default
Copy the tables of another plan.
static void for_each_index(ThreadPool *const pool, const size_t count, F &&fn, const size_t chunk_size)
Definition ntt.H:490
Array< Array< uint64_t > > ptransformed_batch(ThreadPool &pool, const Array< Array< uint64_t > > &input, const bool invert=false, const size_t chunk_size=0) const
Return a parallel-transformed copy of an entire batch.
Definition ntt.H:1372
Array< uint64_t > bluestein_chirp_fwd_
Definition ntt.H:482
size_t n_
Definition ntt.H:474
void apply_transform(Array< uint64_t > &a, const bool invert, const Representation input_repr, const Representation output_repr, ThreadPool *const pool, const size_t chunk_size) const
Definition ntt.H:965
bool should_use_avx2(ThreadPool *const pool) const noexcept
Definition ntt.H:529
void apply_butterflies_scalar(Array< uint64_t > &a, const Array< uint64_t > &twiddles, ThreadPool *const pool, const size_t chunk_size) const
Definition ntt.H:859
void apply_butterflies(Array< uint64_t > &a, const bool invert, ThreadPool *const pool, const size_t chunk_size) const
Definition ntt.H:884
void apply_bluestein_transform(Array< uint64_t > &a, const bool invert, ThreadPool *const pool, const size_t chunk_size) const
Definition ntt.H:912
bool should_use_neon(ThreadPool *const pool) const noexcept
Definition ntt.H:546
void initialize_bit_reversal()
Definition ntt.H:696
Plan(Plan &&other) noexcept
Take the tables of another plan, which is left empty: its size is 0, and it only transforms empty arr...
Definition ntt.H:1112
size_t log_n_
Definition ntt.H:475
void scale_inverse(Array< uint64_t > &a, ThreadPool *const pool, const size_t chunk_size) const
Definition ntt.H:835
void apply_scalar_butterfly_range(Array< uint64_t > &a, const Array< uint64_t > &twiddles, const size_t base, const size_t half, const size_t offset, const size_t begin, const size_t end) const
Definition ntt.H:510
void transform_batch(Array< Array< uint64_t > > &batch, const bool invert) const
Sequential batch transform for equal-sized inputs.
Definition ntt.H:1285
Array< uint64_t > twiddles_fwd_
Definition ntt.H:477
void lower_output(Array< uint64_t > &a, ThreadPool *const pool, const size_t chunk_size) const
Definition ntt.H:847
Plan(const Plan &other)=default
Copy the tables of another plan.
size_t bluestein_size_
Definition ntt.H:481
void initialize_bluestein_plan()
Definition ntt.H:758
Array< uint64_t > bluestein_kernel_inverse_
Definition ntt.H:485
Array< uint64_t > ptransformed(ThreadPool &pool, const Array< uint64_t > &input, const bool invert=false, const size_t chunk_size=0) const
Parallel transform returning a new array.
Definition ntt.H:1250
uint64_t inv_n_
Definition ntt.H:479
Number Theoretic Transform over Z / MOD Z.
Definition ntt.H:115
static Array< uint64_t > interpolate_recursive(const Array< Array< uint64_t > > &tree, const Array< uint64_t > &scaled_values, const size_t node, const size_t left, const size_t right)
Definition ntt.H:1702
static Array< uint64_t > poly_sqrt(const Array< uint64_t > &coeffs, const size_t n)
Formal polynomial square root modulo x^n.
Definition ntt.H:2194
static uint64_t tonelli_shanks(const uint64_t value, const char *const ctx)
Definition ntt.H:1549
static bool avx2_dispatch_available() noexcept
Returns whether AVX2 dispatch is available at runtime.
Definition ntt.H:397
static constexpr const char * simd_preference_name(const SimdPreference preference) noexcept
Definition ntt.H:350
static void validate_distinct_points(const Array< uint64_t > &points, const char *const ctx)
Definition ntt.H:1645
static constexpr bool supports_bluestein_size(const size_t n) noexcept
Definition ntt.H:222
static Array< uint64_t > bigint_multiply(const Array< uint64_t > &a, const Array< uint64_t > &b)
Multiply two non-negative integers represented as base-Base digits.
Definition ntt.H:2813
static Array< uint64_t > poly_exp(const Array< uint64_t > &coeffs, const size_t n)
Formal polynomial exponential modulo x^n.
Definition ntt.H:2157
static Array< Array< uint64_t > > transformed_batch(const Array< Array< uint64_t > > &batch, const bool invert=false)
Return a transformed copy of an entire batch.
Definition ntt.H:1923
static constexpr uint64_t add_mod(const uint64_t lhs, const uint64_t rhs) noexcept
Definition ntt.H:153
static void transform_batch(Array< Array< uint64_t > > &batch, const bool invert)
Sequential batch transform for equal-sized inputs.
Definition ntt.H:1906
static Array< uint64_t > poly_sub_series(const Array< uint64_t > &lhs, const Array< uint64_t > &rhs, const size_t n)
Definition ntt.H:1459
static Array< uint64_t > negacyclic_multiply(const Array< uint64_t > &a, const Array< uint64_t > &b)
Negacyclic convolution modulo x^N + 1.
Definition ntt.H:1850
static Array< uint64_t > poly_integral(const Array< uint64_t > &coeffs)
Definition ntt.H:1536
static constexpr bool supports_size(const size_t n) noexcept
Check whether a transform size is supported.
Definition ntt.H:1741
static constexpr uint64_t sub_mod(const uint64_t lhs, const uint64_t rhs) noexcept
Definition ntt.H:161
static void multipoint_eval_recursive(const Array< Array< uint64_t > > &tree, const Array< uint64_t > &poly, Array< uint64_t > &output, const size_t node, const size_t left, const size_t right)
Definition ntt.H:1672
static Array< Array< uint64_t > > make_product_tree_storage(const size_t count)
Definition ntt.H:1612
NTTSimdBackend
SIMD backends available to the NTT butterfly core.
Definition ntt.H:123
@ avx2
x86-64 AVX2 grouped butterfly path.
@ scalar
Portable scalar implementation.
@ neon
AArch64 NEON grouped butterfly path.
static Array< uint64_t > poly_power(const Array< uint64_t > &coeffs, const uint64_t k, const size_t n)
Formal polynomial power modulo x^n.
Definition ntt.H:2254
static constexpr bool supports_root_order(const uint64_t order) noexcept
Definition ntt.H:216
static size_t next_power_of_two(size_t n, const char *const ctx)
Definition ntt.H:282
static Array< uint64_t > multipoint_eval(const Array< uint64_t > &coeffs, const Array< uint64_t > &points)
Evaluate a polynomial on multiple points modulo MOD.
Definition ntt.H:2313
static Array< uint64_t > poly_inverse(const Array< uint64_t > &coeffs, const size_t n)
Formal polynomial inverse modulo x^n.
Definition ntt.H:2052
static Array< uint64_t > poly_sub_normalized(const Array< uint64_t > &lhs, const Array< uint64_t > &rhs)
Definition ntt.H:1484
static Array< uint64_t > multiply(const Array< uint64_t > &a, const Array< uint64_t > &b)
Multiply two polynomials modulo MOD.
Definition ntt.H:1802
static Array< uint64_t > poly_add_series(const Array< uint64_t > &lhs, const Array< uint64_t > &rhs, const size_t n)
Definition ntt.H:1444
static Array< uint64_t > reverse_poly(const Array< uint64_t > &input)
Definition ntt.H:1434
static Array< uint64_t > poly_derivative(const Array< uint64_t > &coeffs)
Definition ntt.H:1522
static void validate_root_order(const uint64_t order, const char *const ctx)
Definition ntt.H:250
static Array< uint64_t > pmultiply(ThreadPool &pool, const Array< uint64_t > &a, const Array< uint64_t > &b, const size_t chunk_size=0)
Parallel polynomial multiplication modulo MOD.
Definition ntt.H:1980
static Array< uint64_t > truncate_poly(const Array< uint64_t > &input, const size_t n)
Definition ntt.H:1423
static void ptransform(ThreadPool &pool, Array< uint64_t > &a, const bool invert, const size_t chunk_size=0)
Parallel in-place transform using a ThreadPool.
Definition ntt.H:1941
static Array< uint64_t > prefix_copy(const Array< uint64_t > &input, const size_t length)
Definition ntt.H:315
static constexpr uint64_t max_transform_size() noexcept
Maximum supported power-of-two transform size.
Definition ntt.H:1729
static constexpr const char * simd_backend_name(const NTTSimdBackend backend) noexcept
Definition ntt.H:334
static Array< uint64_t > interpolate(const Array< uint64_t > &points, const Array< uint64_t > &values)
Interpolate a polynomial from point-value samples modulo MOD.
Definition ntt.H:2345
static void multiply_inplace(Array< uint64_t > &a, const Array< uint64_t > &b)
Replace a by the product a * b.
Definition ntt.H:1829
static constexpr uint64_t mod
Definition ntt.H:330
static Array< uint64_t > ptransformed(ThreadPool &pool, const Array< uint64_t > &input, const bool invert=false, const size_t chunk_size=0)
Parallel transform returning a new array.
Definition ntt.H:1959
static SimdPreference simd_preference() noexcept
Definition ntt.H:367
static uint64_t poly_eval(const Array< uint64_t > &coeffs, const uint64_t x)
Evaluate a polynomial at a single point modulo MOD.
Definition ntt.H:2031
static Array< uint64_t > transformed(const Array< uint64_t > &input, const bool invert=false)
Transform an input array and return the result.
Definition ntt.H:1785
static Array< uint64_t > series_prefix(const Array< uint64_t > &input, const size_t n)
Definition ntt.H:1412
static void ptransform_batch(ThreadPool &pool, Array< Array< uint64_t > > &batch, const bool invert, const size_t chunk_size=0)
Parallel batch transform for equal-sized inputs.
Definition ntt.H:2013
static NTTSimdBackend detected_simd_backend() noexcept
Definition ntt.H:385
static constexpr bool supports_power_of_two_size(const size_t n) noexcept
Definition ntt.H:209
static constexpr MontgomeryCtx mctx_
Definition ntt.H:144
static constexpr bool simd_mod_supported() noexcept
Definition ntt.H:168
static constexpr uint64_t pow_mod_constexpr(uint64_t base, uint64_t exp) noexcept
Definition ntt.H:174
static Array< uint64_t > poly_mul_trunc(const Array< uint64_t > &lhs, const Array< uint64_t > &rhs, const size_t n)
Definition ntt.H:1506
static constexpr uint64_t root
Definition ntt.H:331
static bool neon_dispatch_available() noexcept
Returns whether AArch64 NEON dispatch is available at runtime.
Definition ntt.H:413
static Array< uint64_t > poly_add_normalized(const Array< uint64_t > &lhs, const Array< uint64_t > &rhs)
Definition ntt.H:1474
static std::pair< Array< uint64_t >, Array< uint64_t > > poly_divmod(const Array< uint64_t > &dividend, const Array< uint64_t > &divisor)
Polynomial division with remainder modulo MOD.
Definition ntt.H:2093
static void transform(Array< uint64_t > &a, const bool invert)
In-place forward or inverse transform.
Definition ntt.H:1772
static Array< uint64_t > poly_mod(const Array< uint64_t > &dividend, const Array< uint64_t > &divisor)
Definition ntt.H:1656
static constexpr uint64_t primitive_root_of_unity(const size_t n)
Return an n-th primitive root of unity modulo MOD.
Definition ntt.H:1755
static Array< uint64_t > normalize_poly(const Array< uint64_t > &input)
Definition ntt.H:1392
static NTTSimdBackend simd_backend() noexcept
Returns the SIMD backend selected under ALEPH_NTT_SIMD.
Definition ntt.H:432
static void validate_supported_size(const size_t n, const char *const ctx)
Definition ntt.H:267
static Array< uint64_t > poly_scalar_mul_series(const Array< uint64_t > &input, const uint64_t scalar, const size_t n)
Definition ntt.H:1494
static Array< uint64_t > pbigint_multiply(ThreadPool &pool, const Array< uint64_t > &a, const Array< uint64_t > &b, const size_t chunk_size=0)
Parallel big-integer multiplication in base Base.
Definition ntt.H:2916
static void trim_trailing_zeros(Array< uint64_t > &poly)
Definition ntt.H:1385
SimdPreference
Definition ntt.H:131
static constexpr bool is_power_of_two(const size_t n) noexcept
Definition ntt.H:147
static Array< uint64_t > padded_copy(const Array< uint64_t > &input, const size_t n)
Definition ntt.H:301
Representation
Definition ntt.H:139
static Array< uint64_t > zero_series(const size_t n)
Definition ntt.H:1403
static constexpr uint64_t primitive_root_of_order(const uint64_t order)
Definition ntt.H:261
static const char * simd_backend_name() noexcept
Returns the active SIMD backend name.
Definition ntt.H:455
static void build_product_tree(Array< Array< uint64_t > > &tree, const Array< uint64_t > &points, const size_t node, const size_t left, const size_t right)
Definition ntt.H:1623
static Array< uint64_t > poly_log(const Array< uint64_t > &coeffs, const size_t n)
Formal polynomial logarithm modulo x^n.
Definition ntt.H:2129
static constexpr uint64_t max_transform_size_impl() noexcept
Definition ntt.H:196
A reusable thread pool for efficient parallel task execution.
size_t num_threads() const noexcept
Get the number of worker threads.
auto enqueue(F &&f, Args &&... args) -> std::future< std::invoke_result_t< F, Args... > >
Submit a task for execution and get a future for the result.
__gmp_expr< T, __gmp_unary_expr< __gmp_expr< T, U >, __gmp_exp_function > > exp(const __gmp_expr< T, U > &expr)
Definition gmpfrxx.h:4144
__gmp_expr< typename __gmp_resolve_expr< T, V >::value_type, __gmp_binary_expr< __gmp_expr< T, U >, __gmp_expr< V, W >, __gmp_remainder_function > > remainder(const __gmp_expr< T, U > &expr1, const __gmp_expr< V, W > &expr2)
Definition gmpfrxx.h:4193
const long double offset[]
Offset values indexed by symbol string length (bounded by MAX_OFFSET_INDEX)
Safe modular arithmetic, extended Euclidean algorithm, and Chinese Remainder Theorem.
Compiler_SSA_Block & block(Compiler_SSA_Function &function, const Compiler_SSA_Block_Id id)
Definition SSA.H:636
Main namespace for Aleph-w library functions.
uint64_t mod_inv(const uint64_t a, const uint64_t m)
Modular Inverse.
bool eq(const C1 &c1, const C2 &c2, Eq e=Eq())
Check equality of two containers using a predicate.
size_t size(Node *root) noexcept
See compute_cardinality_rec(Node * root).
static long & low(typename GT::Node *p)
Internal helper: low-link value stored directly in NODE_COOKIE(p).
void parallel_for_index(ThreadPool &pool, size_t start, size_t end, F &&f, size_t chunk_size=0)
Apply a function to each element in parallel (index-based).
and
Check uniqueness with explicit hash + equality functors.
uint64_t mod_exp(uint64_t base, uint64_t exp, const uint64_t m)
Modular exponentiation.
bool diff(const C1 &c1, const C2 &c2, Eq e=Eq())
Check if two containers differ.
uint64_t mod_mul(uint64_t a, uint64_t b, uint64_t m)
Safe 64-bit modular multiplication.
auto mode(const Container &data) -> std::decay_t< decltype(*std::begin(data))>
Compute the mode (most frequent value).
Definition stat_utils.H:447
Itor::difference_type count(const Itor &beg, const Itor &end, const T &value)
Count elements equal to a value.
Definition ahAlgo.H:127
T sum(const Container &container, const T &init=T{})
Compute sum of all elements.
#define MOD(p)
Definition ntreepic.C:346
@ ROOT
Definition ntreepic.C:221
FooMap m(5, fst_unit_pair_hash, snd_unit_pair_hash)
static int * k
Gsl_Compatible_Rng r
A modern, efficient thread pool for parallel task execution.
Dynamic array container with automatic resizing.
ofstream output
Definition writeHeap.C:215