Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
tpl_polynomial.H
Go to the documentation of this file.
1
2/*
3 Aleph_w
4
5 Data structures & Algorithms
6 version 2.0.0b
7 https://github.com/lrleon/Aleph-w
8
9 This file is part of Aleph-w library
10
11 Copyright (c) 2002-2026 Leandro Rabindranath Leon
12
13 Permission is hereby granted, free of charge, to any person obtaining a copy
14 of this software and associated documentation files (the "Software"), to deal
15 in the Software without restriction, including without limitation the rights
16 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17 copies of the Software, and to permit persons to whom the Software is
18 furnished to do so, subject to the following conditions:
19
20 The above copyright notice and this permission notice shall be included in all
21 copies or substantial portions of the Software.
22
23 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29 SOFTWARE.
30*/
31
57#ifndef TPL_POLYNOMIAL_H
58#define TPL_POLYNOMIAL_H
59
60#include <cmath>
61#include <initializer_list>
62#include <limits>
63#include <sstream>
64#include <string>
65#include <type_traits>
66#include <utility>
67#include <numeric> // std::gcd
68#include <random> // std::mt19937_64
69
70#include <ah-errors.H>
71#include <tpl_dynMapTree.H>
72#include <tpl_array.H>
73#include <htlist.H>
74#include <modular_arithmetic.H> // mod_inv, mod_mul
75
76namespace Aleph {
77
79namespace polynomial_detail {
80
86template <typename C>
87C power(C base, size_t exp)
88{
89 C result = C(1);
90 while (exp > 0)
91 {
92 if (exp & 1)
93 result = result * base;
94 base = base * base;
95 exp >>= 1;
96 }
97 return result;
98}
99
100template <typename Int>
101 requires std::is_integral_v<Int>
102[[nodiscard]] uint64_t abs_to_u64(Int value) noexcept
103{
104 if constexpr (std::is_signed_v<Int>)
105 {
106 using Unsigned = std::make_unsigned_t<Int>;
107 const Unsigned magnitude =
108 value < Int{} ? Unsigned{} - static_cast<Unsigned>(value) : static_cast<Unsigned>(value);
109 return static_cast<uint64_t>(magnitude);
110 }
111 else
112 return static_cast<uint64_t>(value);
113}
114
115template <typename Int>
116 requires std::is_integral_v<Int>
117[[nodiscard]] uint64_t normalize_mod_u64(Int value, const uint64_t modulus) noexcept
118{
119 if (modulus == 0)
120 return 0;
121
122 if constexpr (std::is_signed_v<Int>)
123 {
124 const auto mod_i64 = static_cast<int64_t>(modulus);
125 auto rem = static_cast<int64_t>(value % static_cast<Int>(mod_i64));
126 if (rem < 0)
127 rem += mod_i64;
128 return static_cast<uint64_t>(rem);
129 }
130 else
131 return static_cast<uint64_t>(value % static_cast<Int>(modulus));
132}
133
134template <typename Int>
135 requires std::is_integral_v<Int>
136[[nodiscard]] Int centered_from_mod_u64(const uint64_t value, const uint64_t modulus) noexcept
137{
138 if constexpr (std::is_signed_v<Int>)
139 {
140 const uint64_t canonical = modulus == 0 ? 0 : value % modulus;
141 const uint64_t half = modulus / 2;
142 if (canonical > half)
143 return static_cast<Int>(static_cast<int64_t>(canonical) - static_cast<int64_t>(modulus));
144 return static_cast<Int>(canonical);
145 }
146 else
147 return static_cast<Int>(modulus == 0 ? 0 : value % modulus);
148}
149
150} // end namespace polynomial_detail
151
165template <typename Coefficient = double>
167{
168public:
169 using Coeff = Coefficient;
170
171private:
172 using Term = std::pair<size_t, Coefficient>;
174
175 // --- Epsilon-based zero detection for floating-point types ----------
176
182 static constexpr Coefficient epsilon() noexcept
183 {
184 if constexpr (std::is_floating_point_v<Coefficient>)
185 return Coefficient(128) * std::numeric_limits<Coefficient>::epsilon();
186 else
187 return Coefficient{};
188 }
189
195 static bool coeff_is_zero(const Coefficient &c) noexcept
196 {
197 if constexpr (std::is_floating_point_v<Coefficient>)
198 return std::abs(c) <= epsilon();
199 else
200 return c == Coefficient{};
201 }
202
205 {
206 DynList<size_t> zeros;
207 for (auto it = coeffs.get_it(); it.has_curr(); it.next_ne())
208 {
209 auto &p = it.get_curr();
210 if (coeff_is_zero(p.second))
211 zeros.append(p.first);
212 }
213 zeros.for_each([this](size_t e)
214 {
215 coeffs.remove_key(e);
216 });
217 }
218
222 [[nodiscard]] bool all_coefficients_finite() const noexcept
223 {
224 if constexpr (std::is_floating_point_v<Coefficient>)
225 for (auto it = coeffs.get_it(); it.has_curr(); it.next_ne())
226 if (not std::isfinite(it.get_curr_ne().second))
227 return false;
228 return true;
229 }
230
232 Coefficient coeff_at(size_t exp) const
233 {
234 auto *p = coeffs.search(exp);
235 return p != nullptr ? p->second : Coefficient{};
236 }
237
239 Coefficient *coeff_ptr(size_t exp) noexcept
240 {
241 auto *p = coeffs.search(exp);
242 return p != nullptr ? &p->second : nullptr;
243 }
244
246 const Coefficient *coeff_ptr(size_t exp) const noexcept
247 {
248 auto *p = coeffs.search(exp);
249 return p != nullptr ? &p->second : nullptr;
250 }
251
253 void add_to_coeff(size_t exp, const Coefficient &delta)
254 {
255 if (coeff_is_zero(delta))
256 return;
257
258 if (auto *slot = coeff_ptr(exp); slot != nullptr)
259 {
260 *slot = *slot + delta;
261 if (coeff_is_zero(*slot))
262 coeffs.remove_key(exp);
263 }
264 else
265 coeffs.insert(exp, delta);
266 }
267
269 void add_scaled_shifted(const Gen_Polynomial &src, const Coefficient &scale, size_t shift = 0)
270 {
271 if (coeff_is_zero(scale) or src.is_zero())
272 return;
273
274 src.for_each_term([this, &scale, shift](size_t exp, const Coefficient &c)
275 {
276 add_to_coeff(exp + shift, c * scale);
277 });
278 }
279
281 void scale_inplace(const Coefficient &s)
282 {
283 if (coeffs.is_empty())
284 return;
285
286 if (coeff_is_zero(s))
287 {
289 return;
290 }
291
292 if (s == Coefficient(1))
293 return;
294
295 DynList<size_t> zeros;
296 for (auto it = coeffs.get_it(); it.has_curr(); it.next_ne())
297 {
298 auto &p = it.get_curr();
299 p.second = p.second * s;
300 if (coeff_is_zero(p.second))
301 zeros.append(p.first);
302 }
303
304 zeros.for_each([this](size_t exp)
305 {
306 coeffs.remove_key(exp);
307 });
308 }
309
311 void divide_scalar_inplace(const Coefficient &s)
312 {
313 ah_domain_error_if(coeff_is_zero(s)) << "polynomial division by zero scalar";
314
315 if (coeffs.is_empty())
316 return;
317
318 if (s == Coefficient(1))
319 return;
320
321 DynList<size_t> zeros;
322 for (auto it = coeffs.get_it(); it.has_curr(); it.next_ne())
323 {
324 auto &p = it.get_curr();
325 p.second = p.second / s;
326 if (coeff_is_zero(p.second))
327 zeros.append(p.first);
328 }
329
330 zeros.for_each([this](size_t exp)
331 {
332 coeffs.remove_key(exp);
333 });
334 }
335
337 template <class Op>
338 void for_each_term_desc(Op &&op) const
339 {
340 auto desc_terms = Array<const Term *>::create_reserved(coeffs.size());
341 for (auto it = coeffs.get_it(); it.has_curr(); it.next_ne())
342 {
343 const auto &p = it.get_curr();
344 desc_terms.append(&p);
345 }
346
347 for (size_t i = desc_terms.size(); i > 0; --i)
348 {
349 const Term &term = *desc_terms(i - 1);
350 op(term.first, term.second);
351 }
352 }
353
355 [[nodiscard]] Gen_Polynomial multiply_by_monic_linear(const Coefficient &c) const
356 {
357 if (is_zero())
358 return Gen_Polynomial();
359
360 Gen_Polynomial result;
361 for (auto it = coeffs.get_it(); it.has_curr(); it.next_ne())
362 {
363 auto &p = it.get_curr();
364 result.add_to_coeff(p.first, p.second * c);
365 result.add_to_coeff(p.first + 1, p.second);
366 }
367 return result;
368 }
369
370public:
371 // =================================================================
372 // Construction
373 // =================================================================
374
376 Gen_Polynomial() = default;
377
381 explicit Gen_Polynomial(const Coefficient &c)
382 {
383 if (not coeff_is_zero(c))
384 coeffs[0] = c;
385 }
386
391 Gen_Polynomial(const Coefficient &c, size_t exp)
392 {
393 if (not coeff_is_zero(c))
394 coeffs[exp] = c;
395 }
396
404 Gen_Polynomial(std::initializer_list<Coefficient> il)
405 {
406 size_t exp = 0;
407 for (auto &c : il)
408 {
409 if (not coeff_is_zero(c))
410 coeffs[exp] = c;
411 ++exp;
412 }
413 }
414
422 {
423 size_t exp = 0;
424 l.for_each([this, &exp](const Coefficient &c)
425 {
426 if (not coeff_is_zero(c))
427 coeffs[exp] = c;
428 ++exp;
429 });
430 }
431
439 explicit Gen_Polynomial(const DynList<std::pair<size_t, Coefficient>> &term_list)
440 {
441 term_list.for_each([this](const Term &t)
442 {
443 if (not coeff_is_zero(t.second))
444 add_to_coeff(t.first, t.second);
445 });
446 }
447
448 // =================================================================
449 // Static factory methods
450 // =================================================================
451
453 [[nodiscard]] static Gen_Polynomial zero()
454 {
455 return Gen_Polynomial();
456 }
457
459 [[nodiscard]] static Gen_Polynomial one()
460 {
461 return Gen_Polynomial(Coefficient(1));
462 }
463
467 [[nodiscard]] static Gen_Polynomial x_to(size_t n)
468 {
469 return Gen_Polynomial(Coefficient(1), n);
470 }
471
481 [[nodiscard]] static Gen_Polynomial from_roots(const DynList<Coefficient> &roots)
482 {
483 Gen_Polynomial result(Coefficient(1)); // start with constant 1
484 roots.for_each([&result](const Coefficient &r)
485 {
486 result = result.multiply_by_monic_linear(-r); // (x - r)
487 });
488 return result;
489 }
490
505 [[nodiscard]] static Gen_Polynomial interpolate(
506 const DynList<std::pair<Coefficient, Coefficient>> &points)
507 {
508 ah_domain_error_if(points.is_empty()) << "interpolate requires at least one point";
509
510 const size_t n = points.size();
513 xs.putn(n);
514 dd.putn(n);
515
516 size_t idx = 0;
517 points.for_each([&](const std::pair<Coefficient, Coefficient> &pt)
518 {
519 xs[idx] = pt.first;
520 dd[idx] = pt.second;
521 ++idx;
522 });
523
524 for (size_t i = 0; i < n; ++i)
525 for (size_t j = i + 1; j < n; ++j)
526 ah_domain_error_if(coeff_is_zero(xs[i] - xs[j])) << "interpolate: duplicate x-values";
527
528 for (size_t order = 1; order < n; ++order)
529 for (size_t i = n - 1; i >= order; --i)
530 {
531 Coefficient denom = xs[i] - xs[i - order];
532 dd[i] = (dd[i] - dd[i - 1]) / denom;
533 if (i == order)
534 break;
535 }
536
537 Gen_Polynomial result(dd[0]);
538 Gen_Polynomial basis(Coefficient(1));
539 for (size_t i = 1; i < n; ++i)
540 {
541 basis = basis.multiply_by_monic_linear(-xs[i - 1]);
542 if (not coeff_is_zero(dd[i]))
543 result.add_scaled_shifted(basis, dd[i]);
544 }
545
546 return result;
547 }
548
549 // =================================================================
550 // Properties
551 // =================================================================
552
554 [[nodiscard]] bool is_zero() const noexcept
555 {
556 return coeffs.is_empty();
557 }
558
564 [[nodiscard]] size_t degree() const noexcept
565 {
566 if (coeffs.is_empty())
567 return 0;
568 return coeffs.max().first;
569 }
570
572 [[nodiscard]] size_t num_terms() const noexcept
573 {
574 return coeffs.size();
575 }
576
578 [[nodiscard]] bool is_constant() const noexcept
579 {
580 return coeffs.is_empty() or (coeffs.size() == 1 and coeffs.min().first == 0);
581 }
582
584 [[nodiscard]] bool is_monomial() const noexcept
585 {
586 return coeffs.size() == 1;
587 }
588
590 [[nodiscard]] bool is_monic() const noexcept
591 {
592 return not coeffs.is_empty() and coeff_is_zero(coeffs.max().second - Coefficient(1));
593 }
594
595 // =================================================================
596 // Coefficient access
597 // =================================================================
598
600 [[nodiscard]] Coefficient operator [] (size_t exp) const
601 {
602 return coeff_at(exp);
603 }
604
608 [[nodiscard]] Coefficient leading_coeff() const noexcept
609 {
610 if (coeffs.is_empty())
611 return Coefficient{};
612 return coeffs.max().second;
613 }
614
616 [[nodiscard]] bool has_term(size_t exp) const noexcept
617 {
618 return coeffs.has(exp);
619 }
620
621 // =================================================================
622 // Evaluation
623 // =================================================================
624
634 [[nodiscard]] Coefficient horner_eval(const Coefficient &x) const
635 {
636 if (coeffs.is_empty())
637 return Coefficient{};
638
639 if (x == Coefficient{})
640 return coeff_at(0);
641
642 Coefficient result = Coefficient{};
643 size_t prev_exp = 0;
644 bool first = true;
645
646 for_each_term_desc([&](size_t exp, const Coefficient &c)
647 {
648 if (first)
649 {
650 result = c;
651 prev_exp = exp;
652 first = false;
653 return;
654 }
655
656 result = result * polynomial_detail::power(x, prev_exp - exp) + c;
657 prev_exp = exp;
658 });
659
660 if (prev_exp > 0)
661 result = result * polynomial_detail::power(x, prev_exp);
662
663 return result;
664 }
665
675 [[nodiscard]] Coefficient sparse_eval(const Coefficient &x) const
676 {
677 Coefficient result = Coefficient{};
678 for (auto it = coeffs.get_it(); it.has_curr(); it.next_ne())
679 {
680 auto &p = it.get_curr();
681 result = result + p.second * polynomial_detail::power(x, p.first);
682 }
683 return result;
684 }
685
694 [[nodiscard]] Coefficient eval(const Coefficient &x) const
695 {
696 if (coeffs.is_empty())
697 return Coefficient{};
698
699 if (x == Coefficient{})
700 return coeff_at(0);
701
702 if (num_terms() <= 2)
703 return sparse_eval(x);
704
705 return horner_eval(x);
706 }
707
709 [[nodiscard]] Coefficient operator () (const Coefficient &x) const
710 {
711 return eval(x);
712 }
713
723 [[nodiscard]] DynList<Coefficient> multi_eval(const DynList<Coefficient> &points) const
724 {
725 DynList<Coefficient> results;
726 points.for_each([this, &results](const Coefficient &x)
727 {
728 results.append(eval(x));
729 });
730 return results;
731 }
732
733 // =================================================================
734 // Arithmetic operators
735 // =================================================================
736
738 [[nodiscard]] Gen_Polynomial operator - () const
739 {
740 Gen_Polynomial result;
741 for (auto it = coeffs.get_it(); it.has_curr(); it.next_ne())
742 {
743 auto &p = it.get_curr();
744 result.coeffs[p.first] = -p.second;
745 }
746 return result;
747 }
748
750 [[nodiscard]] Gen_Polynomial operator + (const Gen_Polynomial &q) const
751 {
752 Gen_Polynomial result = *this;
753 result += q;
754 return result;
755 }
756
759 {
760 if (this == &q)
761 {
762 scale_inplace(Coefficient(1) + Coefficient(1));
763 return *this;
764 }
765
766 for (auto it = q.coeffs.get_it(); it.has_curr(); it.next_ne())
767 {
768 auto &p = it.get_curr();
769 add_to_coeff(p.first, p.second);
770 }
771 return *this;
772 }
773
775 [[nodiscard]] Gen_Polynomial operator + (const Coefficient &c) const
776 {
777 Gen_Polynomial result = *this;
778 result += c;
779 return result;
780 }
781
783 Gen_Polynomial &operator += (const Coefficient &c)
784 {
785 add_to_coeff(0, c);
786 return *this;
787 }
788
790 [[nodiscard]] Gen_Polynomial operator - (const Gen_Polynomial &q) const
791 {
792 Gen_Polynomial result = *this;
793 result -= q;
794 return result;
795 }
796
799 {
800 if (this == &q)
801 {
803 return *this;
804 }
805
806 for (auto it = q.coeffs.get_it(); it.has_curr(); it.next_ne())
807 {
808 auto &p = it.get_curr();
809 add_to_coeff(p.first, -p.second);
810 }
811 return *this;
812 }
813
815 [[nodiscard]] Gen_Polynomial operator - (const Coefficient &c) const
816 {
817 Gen_Polynomial result = *this;
818 result -= c;
819 return result;
820 }
821
823 Gen_Polynomial &operator -= (const Coefficient &c)
824 {
825 add_to_coeff(0, -c);
826 return *this;
827 }
828
834 [[nodiscard]] Gen_Polynomial operator * (const Gen_Polynomial &q) const
835 {
836 if (is_zero() or q.is_zero())
837 return Gen_Polynomial();
838
839 Gen_Polynomial result;
840 const Gen_Polynomial *outer = this;
841 const Gen_Polynomial *inner = &q;
842
843 if (q.num_terms() < num_terms())
844 {
845 outer = &q;
846 inner = this;
847 }
848
849 for (auto it1 = outer->coeffs.get_it(); it1.has_curr(); it1.next_ne())
850 {
851 auto &t1 = it1.get_curr();
852 for (auto it2 = inner->coeffs.get_it(); it2.has_curr(); it2.next_ne())
853 {
854 auto &t2 = it2.get_curr();
855 result.add_to_coeff(t1.first + t2.first, t1.second * t2.second);
856 }
857 }
858 return result;
859 }
860
863 {
864 *this = *this * q;
865 return *this;
866 }
867
869 [[nodiscard]] Gen_Polynomial operator * (const Coefficient &s) const
870 {
871 if (coeff_is_zero(s))
872 return Gen_Polynomial();
873 Gen_Polynomial result;
874 for (auto it = coeffs.get_it(); it.has_curr(); it.next_ne())
875 {
876 auto &p = it.get_curr();
877 Coefficient prod = p.second * s;
878 if (not coeff_is_zero(prod))
879 result.coeffs[p.first] = prod;
880 }
881 return result;
882 }
883
885 Gen_Polynomial &operator *= (const Coefficient &s)
886 {
887 scale_inplace(s);
888 return *this;
889 }
890
894 [[nodiscard]] Gen_Polynomial operator / (const Coefficient &s) const
895 {
896 ah_domain_error_if(coeff_is_zero(s)) << "polynomial division by zero scalar";
897 Gen_Polynomial result;
898 for (auto it = coeffs.get_it(); it.has_curr(); it.next_ne())
899 {
900 auto &p = it.get_curr();
901 Coefficient q = p.second / s;
902 if (not coeff_is_zero(q))
903 result.coeffs[p.first] = q;
904 }
905 return result;
906 }
907
909 Gen_Polynomial &operator /= (const Coefficient &s)
910 {
912 return *this;
913 }
914
915 // =================================================================
916 // Polynomial division
917 // =================================================================
918
931 [[nodiscard]] std::pair<Gen_Polynomial, Gen_Polynomial> divmod(const Gen_Polynomial &d) const
932 {
933 ah_domain_error_if(d.is_zero()) << "polynomial division by zero";
934
935 if (is_zero() or degree() < d.degree())
936 return {Gen_Polynomial(), *this};
937
938 Gen_Polynomial q; // quotient
939 Gen_Polynomial r = *this; // remainder
940 const size_t d_degree = d.degree();
941 const Coefficient d_lc = d.leading_coeff();
942
943 while (not r.is_zero())
944 {
945 const size_t r_degree = r.degree();
946 if (r_degree < d_degree)
947 break;
948
949 const Coefficient scale = r.leading_coeff() / d_lc;
951 << "divmod: inexact coefficient division (leading_coeff=" << r.leading_coeff()
952 << " / divisor_lc=" << d_lc << " = 0). "
953 << "For integral/non-field coefficients, use pseudo_divmod() instead.";
954 // An infinite coefficient turns into NaN, which is never zero: the
955 // degree of the remainder would not go down and the loop not end
956 if constexpr (std::is_floating_point_v<Coefficient>)
957 ah_domain_error_if(not std::isfinite(scale))
958 << "divmod: the quotient coefficient " << scale << " is not finite";
959 const size_t shift = r_degree - d_degree;
960
961 q.add_to_coeff(shift, scale);
962 r.add_scaled_shifted(d, -scale, shift);
963 }
964
965 // a coefficient below the leading one can overflow too, and then the
966 // loop ends by degree
967 ah_domain_error_if(not q.all_coefficients_finite() or not r.all_coefficients_finite())
968 << "divmod: a coefficient of the quotient or of the remainder overflowed";
969 return {q, r};
970 }
971
973 [[nodiscard]] Gen_Polynomial operator / (const Gen_Polynomial &d) const
974 {
975 return divmod(d).first;
976 }
977
979 [[nodiscard]] Gen_Polynomial operator % (const Gen_Polynomial &d) const
980 {
981 return divmod(d).second;
982 }
983
986 {
987 *this = divmod(d).first;
988 return *this;
989 }
990
993 {
994 *this = divmod(d).second;
995 return *this;
996 }
997
998 // =================================================================
999 // Calculus
1000 // =================================================================
1001
1007 [[nodiscard]] Gen_Polynomial derivative() const
1008 {
1009 Gen_Polynomial result;
1010 for (auto it = coeffs.get_it(); it.has_curr(); it.next_ne())
1011 {
1012 auto &p = it.get_curr();
1013 if (p.first == 0)
1014 continue; // derivative of constant is 0
1015 Coefficient dc = p.second * Coefficient(p.first);
1016 if (not coeff_is_zero(dc))
1017 result.coeffs[p.first - 1] = dc;
1018 }
1019 return result;
1020 }
1021
1033 [[nodiscard]] Gen_Polynomial nth_derivative(size_t n) const
1034 {
1035 Gen_Polynomial result = *this;
1036 for (size_t i = 0; i < n and not result.is_zero(); ++i)
1037 result = result.derivative();
1038 return result;
1039 }
1040
1051 [[nodiscard]] Gen_Polynomial integral(const Coefficient &C = Coefficient{}) const
1052 {
1053 Gen_Polynomial result;
1054 if (not coeff_is_zero(C))
1055 result.coeffs[0] = C;
1056 for (auto it = coeffs.get_it(); it.has_curr(); it.next_ne())
1057 {
1058 auto &p = it.get_curr();
1059 Coefficient ic = p.second / Coefficient(p.first + 1);
1060 if (not coeff_is_zero(ic))
1061 result.coeffs[p.first + 1] = ic;
1062 }
1063 return result;
1064 }
1065
1075 [[nodiscard]] Coefficient definite_integral(const Coefficient &a, const Coefficient &b) const
1076 {
1077 Coefficient result = Coefficient{};
1078
1079 for (auto it = coeffs.get_it(); it.has_curr(); it.next_ne())
1080 {
1081 auto &p = it.get_curr();
1082 const size_t next_exp = p.first + 1;
1083 const Coefficient scale = p.second / Coefficient(next_exp);
1084 if (coeff_is_zero(scale))
1085 continue;
1086
1087 result = result +
1088 scale * (polynomial_detail::power(b, next_exp) - polynomial_detail::power(a, next_exp));
1089 }
1090
1091 return result;
1092 }
1093
1094 // =================================================================
1095 // Composition and power
1096 // =================================================================
1097
1104 [[nodiscard]] Gen_Polynomial compose(const Gen_Polynomial &q) const
1105 {
1106 if (is_zero())
1107 return Gen_Polynomial();
1108
1109 if (q.is_constant())
1110 return Gen_Polynomial(eval(q[0]));
1111
1112 Gen_Polynomial result;
1113 size_t prev_exp = 0;
1114 bool first = true;
1115
1116 for_each_term_desc([&](size_t exp, const Coefficient &c)
1117 {
1118 if (first)
1119 {
1120 result = Gen_Polynomial(c);
1121 prev_exp = exp;
1122 first = false;
1123 return;
1124 }
1125
1126 const size_t gap = prev_exp - exp;
1127 if (gap == 1)
1128 result *= q;
1129 else if (gap > 1)
1130 result *= q.pow(gap);
1131
1132 result.add_to_coeff(0, c);
1133 prev_exp = exp;
1134 });
1135
1136 if (prev_exp == 1)
1137 result *= q;
1138 else if (prev_exp > 1)
1139 result *= q.pow(prev_exp);
1140
1141 return result;
1142 }
1143
1149 [[nodiscard]] Gen_Polynomial pow(size_t n) const
1150 {
1151 Gen_Polynomial result(Coefficient(1));
1152 Gen_Polynomial base = *this;
1153 while (n > 0)
1154 {
1155 if (n & 1)
1156 result *= base;
1157 base *= base;
1158 n >>= 1;
1159 }
1160 return result;
1161 }
1162
1163 // =================================================================
1164 // GCD
1165 // =================================================================
1166
1177 {
1178 while (not b.is_zero())
1179 {
1180 Gen_Polynomial r = a % b;
1181 a = b;
1182 b = r;
1183 }
1184 // Make monic
1185 if (not a.is_zero())
1186 a /= a.leading_coeff();
1187 return a;
1188 }
1189
1205
1207 {
1208 Gen_Polynomial s0(Coefficient(1)), s1;
1209 Gen_Polynomial t0, t1(Coefficient(1));
1210
1211 while (not b.is_zero())
1212 {
1213 auto [q, r] = a.divmod(b);
1214 a = b;
1215 b = r;
1216 Gen_Polynomial s2 = s0 - q * s1;
1217 Gen_Polynomial t2 = t0 - q * t1;
1218 s0 = s1;
1219 s1 = s2;
1220 t0 = t1;
1221 t1 = t2;
1222 }
1223
1224 if (not a.is_zero())
1225 {
1226 Coefficient lc = a.leading_coeff();
1227 a /= lc;
1228 s0 /= lc;
1229 t0 /= lc;
1230 }
1231
1232 return {a, s0, t0};
1233 }
1234
1243 [[nodiscard]] static Gen_Polynomial lcm(const Gen_Polynomial &a, const Gen_Polynomial &b)
1244 {
1245 if (a.is_zero() or b.is_zero())
1246 return Gen_Polynomial();
1247 Gen_Polynomial g = gcd(a, b);
1248 return a / g * b;
1249 }
1250
1264 [[nodiscard]] std::pair<Gen_Polynomial, Gen_Polynomial> pseudo_divmod(const Gen_Polynomial &d) const
1265 {
1266 ah_domain_error_if(d.is_zero()) << "pseudo-division by zero polynomial";
1267
1268 if (is_zero() or degree() < d.degree())
1269 return {Gen_Polynomial(), *this};
1270
1271 const Coefficient lc_d = d.leading_coeff();
1272 const size_t d_degree = d.degree();
1273 size_t delta = degree() - d_degree + 1;
1274
1276 Gen_Polynomial r = *this;
1277
1278 while (not r.is_zero())
1279 {
1280 const size_t r_degree = r.degree();
1281 if (r_degree < d_degree)
1282 break;
1283
1284 const Coefficient lc_r = r.leading_coeff();
1285 // A coefficient that overflowed turns into NaN, which is never
1286 // zero: the degree of the remainder would not go down and the loop
1287 // not end
1288 if constexpr (std::is_floating_point_v<Coefficient>)
1289 ah_domain_error_if(not std::isfinite(lc_r))
1290 << "pseudo_divmod: a coefficient of the remainder overflowed (" << lc_r << ")";
1291 const size_t exp = r_degree - d_degree;
1292
1293 // Multiply q and r by lc(d) to avoid division
1294 q.scale_inplace(lc_d);
1295 r.scale_inplace(lc_d);
1296 --delta;
1297
1298 q.add_to_coeff(exp, lc_r);
1299 r.add_scaled_shifted(d, -lc_r, exp);
1300 }
1301
1302 // Multiply by remaining powers of lc(d)
1303 if (delta > 0)
1304 {
1305 const Coefficient scale = polynomial_detail::power(lc_d, delta);
1306 q.scale_inplace(scale);
1307 r.scale_inplace(scale);
1308 }
1309
1310 // Scaling by lc(d) can overflow coefficients below the leading one, and
1311 // so can the last powers of lc(d)
1312 ah_domain_error_if(not q.all_coefficients_finite() or not r.all_coefficients_finite())
1313 << "pseudo_divmod: a coefficient of the quotient or of the remainder overflowed";
1314 return {q, r};
1315 }
1316
1317 // =================================================================
1318 // Algebraic transformations
1319 // =================================================================
1320
1326 [[nodiscard]] Gen_Polynomial to_monic() const
1327 {
1328 ah_domain_error_if(is_zero()) << "cannot make zero polynomial monic";
1329 return *this / leading_coeff();
1330 }
1331
1337 [[nodiscard]] Gen_Polynomial reverse() const
1338 {
1339 if (is_zero())
1340 return Gen_Polynomial();
1341 size_t d = degree();
1342 Gen_Polynomial result;
1343 for (auto it = coeffs.get_it(); it.has_curr(); it.next_ne())
1344 {
1345 auto &p = it.get_curr();
1346 result.coeffs[d - p.first] = p.second;
1347 }
1348 return result;
1349 }
1350
1355 [[nodiscard]] Gen_Polynomial negate_arg() const
1356 {
1357 Gen_Polynomial result;
1358 for (auto it = coeffs.get_it(); it.has_curr(); it.next_ne())
1359 {
1360 auto &p = it.get_curr();
1361 result.coeffs[p.first] = (p.first % 2 == 0) ? p.second : -p.second;
1362 }
1363 return result;
1364 }
1365
1376 [[nodiscard]] Gen_Polynomial shift(const Coefficient &k) const
1377 {
1378 return compose(Gen_Polynomial({k, Coefficient(1)}));
1379 }
1380
1386 [[nodiscard]] Gen_Polynomial shift_up(size_t k) const
1387 {
1388 if (k == 0)
1389 return *this;
1390 Gen_Polynomial result;
1391 for (auto it = coeffs.get_it(); it.has_curr(); it.next_ne())
1392 {
1393 auto &p = it.get_curr();
1394 result.coeffs[p.first + k] = p.second;
1395 }
1396 return result;
1397 }
1398
1406 [[nodiscard]] Gen_Polynomial shift_down(size_t k) const
1407 {
1408 if (k == 0)
1409 return *this;
1410 Gen_Polynomial result;
1411 for (auto it = coeffs.get_it(); it.has_curr(); it.next_ne())
1412 {
1413 auto &p = it.get_curr();
1414 if (p.first >= k)
1415 result.coeffs[p.first - k] = p.second;
1416 }
1417 return result;
1418 }
1419
1427 [[nodiscard]] Gen_Polynomial truncate(size_t n) const
1428 {
1429 Gen_Polynomial result;
1430 for (auto it = coeffs.get_it(); it.has_curr(); it.next_ne())
1431 {
1432 auto &p = it.get_curr();
1433 if (p.first < n)
1434 result.coeffs[p.first] = p.second;
1435 }
1436 return result;
1437 }
1438
1445 [[nodiscard]] Array<Coefficient> to_dense() const
1446 {
1447 if (is_zero())
1448 return Array<Coefficient>();
1449 size_t d = degree();
1450 Array<Coefficient> result(d + 1, Coefficient{});
1451 for (auto it = coeffs.get_it(); it.has_curr(); it.next_ne())
1452 {
1453 auto &p = it.get_curr();
1454 result(p.first) = p.second;
1455 }
1456 return result;
1457 }
1458
1471 [[nodiscard]] Gen_Polynomial square_free() const
1472 {
1473 if (is_zero() or is_constant())
1474 return *this;
1475 Gen_Polynomial g = gcd(*this, derivative());
1476 return *this / g;
1477 }
1478
1479 // =================================================================
1480 // Root analysis (floating-point coefficients)
1481 // =================================================================
1482
1491 [[nodiscard]] Coefficient cauchy_bound() const
1492 {
1493 ah_domain_error_if(is_zero()) << "cauchy_bound: zero polynomial has no roots";
1494 if (is_constant())
1495 return Coefficient{};
1496
1497 const size_t d = degree();
1498 const Coefficient lc = leading_coeff();
1499 if constexpr (std::is_floating_point_v<Coefficient>)
1500 {
1501 Coefficient max_ratio = Coefficient{};
1502 for (auto it = coeffs.get_it(); it.has_curr(); it.next_ne())
1503 {
1504 auto &p = it.get_curr();
1505 if (p.first == d)
1506 continue;
1507 const Coefficient ratio = std::abs(p.second / lc);
1508 if (ratio > max_ratio)
1509 max_ratio = ratio;
1510 }
1511 return Coefficient(1) + max_ratio;
1512 }
1513 else
1514 {
1515 long double max_ratio_ld = 0.0L;
1516 for (auto it = coeffs.get_it(); it.has_curr(); it.next_ne())
1517 {
1518 auto &p = it.get_curr();
1519 if (p.first == d)
1520 continue;
1521 const long double ratio =
1522 std::fabs(static_cast<long double>(p.second) / static_cast<long double>(lc));
1523 if (ratio > max_ratio_ld)
1524 max_ratio_ld = ratio;
1525 }
1526 return Coefficient(1) + static_cast<Coefficient>(std::ceil(max_ratio_ld));
1527 }
1528 }
1529
1538 [[nodiscard]] size_t sign_variations() const
1539 {
1540 if (coeffs.size() < 2)
1541 return 0;
1542
1543 size_t changes = 0;
1544 bool have_prev = false;
1545 bool prev_positive = false;
1546
1547 for (auto it = coeffs.get_it(); it.has_curr(); it.next_ne())
1548 {
1549 auto &p = it.get_curr();
1550 bool positive;
1551 if constexpr (std::is_floating_point_v<Coefficient>)
1552 positive = p.second > epsilon();
1553 else
1554 positive = p.second > Coefficient{};
1555
1556 bool is_neg;
1557 if constexpr (std::is_floating_point_v<Coefficient>)
1558 is_neg = p.second < -epsilon();
1559 else
1560 is_neg = p.second < Coefficient{};
1561
1562 if (not positive and not is_neg)
1563 continue; // skip zero coefficients
1564
1565 if (have_prev and positive != prev_positive)
1566 ++changes;
1567 prev_positive = positive;
1568 have_prev = true;
1569 }
1570 return changes;
1571 }
1572
1584 {
1586 chain.append(*this);
1587 if (is_zero() or is_constant())
1588 return chain;
1589
1590 Gen_Polynomial p0 = *this;
1592 chain.append(p1);
1593
1594 while (not p1.is_zero())
1595 {
1596 Gen_Polynomial r = -(p0 % p1);
1597 if (r.is_zero())
1598 break;
1599 chain.append(r);
1600 p0 = p1;
1601 p1 = r;
1602 }
1603
1604 return chain;
1605 }
1606
1613 [[nodiscard]] static size_t sturm_sign_changes(const DynList<Gen_Polynomial> &chain,
1614 const Coefficient &x)
1615 {
1616 size_t changes = 0;
1617 bool have_prev = false;
1618 bool prev_positive = false;
1619
1620 chain.for_each([&](const Gen_Polynomial &p)
1621 {
1622 Coefficient val = p(x);
1623 if (coeff_is_zero(val))
1624 return; // skip zeros in Sturm evaluation
1625
1626 bool positive = val > Coefficient{};
1627 if (have_prev and positive != prev_positive)
1628 ++changes;
1629 prev_positive = positive;
1630 have_prev = true;
1631 });
1632
1633 return changes;
1634 }
1635
1649 [[nodiscard]] size_t count_real_roots(const Coefficient &a, const Coefficient &b) const
1650 {
1651 if (b < a)
1652 return count_real_roots(b, a);
1653
1654 if (is_zero())
1655 return 0;
1656
1657 auto chain = sturm_chain();
1658 size_t sa = sturm_sign_changes(chain, a);
1659 size_t sb = sturm_sign_changes(chain, b);
1660 size_t count = sa > sb ? sa - sb : 0;
1661
1662 // Sturm's theorem counts roots in (a, b]; add root at a if present
1663 if (coeff_is_zero((*this)(a)))
1664 ++count;
1665
1666 return count;
1667 }
1668
1674 [[nodiscard]] size_t count_all_real_roots() const
1675 {
1676 if (is_zero() or is_constant())
1677 return 0;
1678 Coefficient bound = cauchy_bound();
1679 return count_real_roots(-bound, bound);
1680 }
1681
1695 [[nodiscard]] Coefficient bisect_root(Coefficient a,
1696 Coefficient b,
1697 Coefficient tol = Coefficient(1e-12),
1698 size_t max_iter = 200) const
1699 {
1700 if (b < a)
1701 std::swap(a, b);
1702
1703 Coefficient fa = eval(a), fb = eval(b);
1704 if (coeff_is_zero(fa))
1705 return a;
1706 if (coeff_is_zero(fb))
1707 return b;
1708
1709 ah_domain_error_if((fa > Coefficient{}) == (fb > Coefficient{}) and not coeff_is_zero(fa) and
1710 not coeff_is_zero(fb))
1711 << "bisect_root: f(a) and f(b) must have opposite signs";
1712
1713 for (size_t i = 0; i < max_iter; ++i)
1714 {
1715 Coefficient mid = (a + b) / Coefficient(2);
1716 if (b - a < tol)
1717 return mid;
1718 Coefficient fm = eval(mid);
1719 if (coeff_is_zero(fm))
1720 return mid;
1721 if (fa > Coefficient{} == fm > Coefficient{})
1722 {
1723 a = mid;
1724 fa = fm;
1725 }
1726 else
1727 {
1728 b = mid;
1729 fb = fm;
1730 }
1731 }
1732 return (a + b) / Coefficient(2);
1733 }
1734
1744 [[nodiscard]] Coefficient newton_root(Coefficient x0,
1745 Coefficient tol = Coefficient(1e-12),
1746 size_t max_iter = 100) const
1747 requires std::is_floating_point_v<Coefficient>
1748 {
1750
1751 for (size_t i = 0; i < max_iter; ++i)
1752 {
1753 Coefficient fx = eval(x0);
1754 if (coeff_is_zero(fx))
1755 return x0;
1756 Coefficient dfx = dp.eval(x0);
1757 ah_domain_error_if(coeff_is_zero(dfx)) << "newton_root: derivative is zero at x = " << x0;
1758 Coefficient x1 = x0 - fx / dfx;
1759 Coefficient delta = x1 - x0;
1760 if constexpr (std::is_floating_point_v<Coefficient>)
1761 {
1762 if (std::abs(delta) < tol)
1763 return x1;
1764 }
1765 else
1766 {
1767 if (delta == Coefficient{})
1768 return x1;
1769 }
1770 x0 = x1;
1771 }
1772 return x0;
1773 }
1774
1775 // =================================================================
1776 // Comparison
1777 // =================================================================
1778
1784 [[nodiscard]] bool operator == (const Gen_Polynomial &q) const noexcept
1785 {
1786 if (this == &q)
1787 return true;
1788
1789 auto it1 = coeffs.get_it();
1790 auto it2 = q.coeffs.get_it();
1791
1792 while (it1.has_curr() and it2.has_curr())
1793 {
1794 auto &lhs = it1.get_curr();
1795 auto &rhs = it2.get_curr();
1796
1797 if (lhs.first == rhs.first)
1798 {
1799 if (not coeff_is_zero(lhs.second - rhs.second))
1800 return false;
1801 it1.next_ne();
1802 it2.next_ne();
1803 continue;
1804 }
1805
1806 if (lhs.first < rhs.first)
1807 {
1808 if (not coeff_is_zero(lhs.second))
1809 return false;
1810 it1.next_ne();
1811 continue;
1812 }
1813
1814 if (not coeff_is_zero(rhs.second))
1815 return false;
1816 it2.next_ne();
1817 }
1818
1819 while (it1.has_curr())
1820 {
1821 if (not coeff_is_zero(it1.get_curr().second))
1822 return false;
1823 it1.next_ne();
1824 }
1825
1826 while (it2.has_curr())
1827 {
1828 if (not coeff_is_zero(it2.get_curr().second))
1829 return false;
1830 it2.next_ne();
1831 }
1832
1833 return true;
1834 }
1835
1837 [[nodiscard]] bool operator != (const Gen_Polynomial &q) const noexcept
1838 {
1839 return not (*this == q);
1840 }
1841
1842 // =================================================================
1843 // Iteration
1844 // =================================================================
1845
1850 template <class Op>
1851 void for_each_term(Op &&op) const
1852 {
1853 for (auto it = coeffs.get_it(); it.has_curr(); it.next_ne())
1854 {
1855 auto &p = it.get_curr();
1856 op(p.first, p.second);
1857 }
1858 }
1859
1862 {
1864 for (auto it = coeffs.get_it(); it.has_curr(); it.next_ne())
1865 {
1866 auto &p = it.get_curr();
1867 result.append({p.first, p.second});
1868 }
1869 return result;
1870 }
1871
1873 [[nodiscard]] DynList<size_t> exponents() const
1874 {
1875 return coeffs.keys();
1876 }
1877
1880 {
1881 return coeffs.values();
1882 }
1883
1884 // =================================================================
1885 // String representation
1886 // =================================================================
1887
1895 [[nodiscard]] std::string to_str(const std::string &var = "x") const
1896 {
1897 if (coeffs.is_empty())
1898 return "0";
1899
1900 std::ostringstream oss;
1901 bool first = true;
1902
1903 for_each_term_desc([&](size_t exp, const Coefficient &c)
1904 {
1905 bool negative = false;
1906 if constexpr (requires { c < Coefficient{}; })
1907 negative = c < Coefficient{};
1908
1909 Coefficient ac = negative ? -c : c;
1910
1911 // Sign
1912 if (first)
1913 {
1914 if (negative)
1915 oss << "-";
1916 }
1917 else
1918 oss << (negative ? " - " : " + ");
1919
1920 // Coefficient and variable
1921 if (exp == 0)
1922 oss << ac;
1923 else
1924 {
1925 if (not (ac == Coefficient(1)))
1926 oss << ac;
1927 oss << var;
1928 if (exp > 1)
1929 oss << "^" << exp;
1930 }
1931
1932 first = false;
1933 });
1934
1935 return oss.str();
1936 }
1937
1938 // =================================================================
1939 // Layer 5 — Exact Univariate Factorization
1940 // =================================================================
1941
1947 struct SfdTerm
1948 {
1951 };
1952
1958 [[nodiscard]] Coefficient get_coeff(size_t exp) const noexcept
1959 {
1960 return coeff_at(exp);
1961 }
1962
1968 void set_coeff(size_t exp, const Coefficient &c)
1969 {
1970 if (auto *slot = coeff_ptr(exp); slot != nullptr)
1971 {
1972 if (coeff_is_zero(c))
1973 coeffs.remove_key(exp);
1974 else
1975 *slot = c;
1976 }
1977 else if (not coeff_is_zero(c))
1978 coeffs.insert(exp, c);
1979 }
1980
1992 [[nodiscard]] Coefficient content() const
1993 requires std::is_integral_v<Coefficient>
1994 {
1995 if (coeffs.is_empty())
1996 return Coefficient{};
1997
1998 Coefficient result = Coefficient{};
1999 for (auto it = coeffs.get_it(); it.has_curr(); it.next_ne())
2000 {
2001 auto &p = it.get_curr();
2002 result = std::gcd(result, p.second);
2003 }
2004
2005 // Ensure sign follows leading coefficient
2006 const Coefficient lc = leading_coeff();
2007 if (lc < Coefficient{} and result > Coefficient{})
2008 result = -result;
2009
2010 return result;
2011 }
2012
2021 [[nodiscard]] Gen_Polynomial primitive_part() const
2022 requires std::is_integral_v<Coefficient>
2023 {
2024 if (is_zero())
2025 return Gen_Polynomial();
2026
2027 Coefficient c = content();
2028 if (c == Coefficient{} or c == Coefficient(1) or c == Coefficient(-1))
2029 {
2030 // Already primitive; ensure leading coefficient is positive
2031 Gen_Polynomial result = *this;
2032 if (leading_coeff() < Coefficient{})
2033 result.scale_inplace(Coefficient(-1));
2034 return result;
2035 }
2036
2037 Gen_Polynomial result;
2038 for (auto it = coeffs.get_it(); it.has_curr(); it.next_ne())
2039 {
2040 auto &p = it.get_curr();
2041 result.coeffs.insert(p.first, p.second / c);
2042 }
2043
2044 // Ensure leading coefficient is positive
2045 if (result.leading_coeff() < Coefficient{})
2046 result.scale_inplace(Coefficient(-1));
2047
2048 return result;
2049 }
2050
2064 requires std::is_integral_v<Coefficient>
2065 {
2066 if (a.is_zero())
2067 return b.primitive_part();
2068 if (b.is_zero())
2069 return a.primitive_part();
2070
2071 a = a.primitive_part();
2072 b = b.primitive_part();
2073
2074 while (not b.is_zero())
2075 {
2076 auto [quo, rem] = a.pseudo_divmod(b);
2077 a = b;
2078 b = rem.is_zero() ? rem : rem.primitive_part();
2079 }
2080
2081 return a.primitive_part();
2082 }
2083
2099 [[nodiscard]] DynList<SfdTerm> yun_sfd() const
2100 requires std::is_integral_v<Coefficient>
2101 {
2102 DynList<SfdTerm> result;
2103
2104 if (is_constant())
2105 return result;
2106
2107 const Gen_Polynomial f = primitive_part();
2108 const Gen_Polynomial fp = f.derivative();
2109
2110 Gen_Polynomial g = integer_gcd(f, fp);
2112
2113 size_t multiplicity = 1;
2114
2115 while (not h.is_constant())
2116 {
2117 Gen_Polynomial h_prev = h;
2118 h = integer_gcd(g, h);
2120
2121 if (not w.is_constant())
2122 result.append(SfdTerm{w.primitive_part(), multiplicity});
2123
2124 g = _integer_exact_quot(g, h);
2125 multiplicity++;
2126 }
2127
2128 // Final factor
2129 if (not g.is_constant())
2130 result.append(SfdTerm{g.primitive_part(), multiplicity});
2131
2132 return result;
2133 }
2134
2146 requires std::is_integral_v<Coefficient>
2147 {
2148 ah_domain_error_if(b.is_zero()) << "_integer_exact_quot: zero divisor";
2149 if (b.is_constant())
2150 {
2151 Coefficient d = b.leading_coeff();
2153 for (auto it = a.coeffs.get_it(); it.has_curr(); it.next_ne())
2154 {
2155 auto &p = it.get_curr();
2156 ah_domain_error_if(not coeff_is_zero(p.second % d))
2157 << "_integer_exact_quot: inexact constant division for coefficient " << p.second
2158 << " and divisor " << d;
2159 r.coeffs.insert(p.first, p.second / d);
2160 }
2161 return r;
2162 }
2163 auto [q, rem] = a.pseudo_divmod(b);
2164 ah_domain_error_if(not rem.is_zero())
2165 << "_integer_exact_quot: divisor does not divide dividend exactly";
2166 return q.is_zero() ? q : q.primitive_part();
2167 }
2168
2169 [[nodiscard]] static Gen_Polynomial reduce_coeffs_mod(const Gen_Polynomial &f, Coefficient mod)
2170 requires std::is_integral_v<Coefficient>
2171 {
2172 Gen_Polynomial reduced;
2173 f.for_each_term([&reduced, mod](size_t exp, const Coefficient &coeff)
2174 {
2175 Coefficient c = coeff % mod;
2176 if (c < Coefficient{})
2177 c = c + mod;
2178 if (c != Coefficient{})
2179 reduced.set_coeff(exp, c);
2180 });
2181 return reduced;
2182 }
2183
2184 [[nodiscard]] static uint64_t eval_mod_u64(const Gen_Polynomial &f, uint64_t x, uint64_t mod)
2185 requires std::is_integral_v<Coefficient>
2186 {
2187 if (mod == 0 or mod == 1)
2188 return 0;
2189
2190 uint64_t result = 0;
2191 f.for_each_term([&result, x, mod](size_t exp, const Coefficient &coeff)
2192 {
2193 const uint64_t c = polynomial_detail::normalize_mod_u64(coeff, mod);
2194 const uint64_t xpow = mod_exp(x, exp, mod);
2195 const uint64_t term = mod_mul(c, xpow, mod);
2196 result = (result + term) % mod;
2197 });
2198 return result;
2199 }
2200
2202 Coefficient root,
2203 Coefficient mod)
2204 requires std::is_integral_v<Coefficient>
2205 {
2206 ah_domain_error_if(f.degree() == 0)
2207 << "divide_by_monic_linear_mod: constant polynomial is not divisible by x - r";
2208
2209 const size_t degree = f.degree();
2210 Array<Coefficient> synthetic(degree + 1, Coefficient{});
2211
2212 synthetic(degree) = ((f.get_coeff(degree) % mod) + mod) % mod;
2213
2214 for (size_t idx = degree; idx-- > 0;)
2215 {
2216 Coefficient term = (f.get_coeff(idx) % mod + mod) % mod;
2217 Coefficient next = (term + (synthetic(idx + 1) * root) % mod) % mod;
2218 synthetic(idx) = next;
2219 }
2220
2221 ah_domain_error_if(synthetic(0) != Coefficient{})
2222 << "divide_by_monic_linear_mod: x - r does not divide polynomial modulo p";
2223
2224 Gen_Polynomial quotient;
2225 for (size_t exp = 0; exp < degree; ++exp)
2226 if (synthetic(exp + 1) != Coefficient{})
2227 quotient.set_coeff(exp, synthetic(exp + 1));
2228
2229 return quotient;
2230 }
2231
2232 [[nodiscard]] static DynList<Coefficient> positive_divisors(Coefficient value)
2233 requires std::is_integral_v<Coefficient>
2234 {
2235 DynList<Coefficient> result;
2236
2237 const uint64_t abs_value = polynomial_detail::abs_to_u64(value);
2238 if (abs_value == 0)
2239 return result;
2240
2241 for (uint64_t d = 1; d * d <= abs_value; ++d)
2242 if (abs_value % d == 0)
2243 {
2244 result.append(static_cast<Coefficient>(d));
2245 const uint64_t other = abs_value / d;
2246 if (other != d)
2247 result.append(static_cast<Coefficient>(other));
2248 }
2249
2250 return result;
2251 }
2252
2260 [[nodiscard]] static bool try_exact_candidate_division(const Gen_Polynomial &f,
2261 const Gen_Polynomial &candidate,
2262 Gen_Polynomial &quotient)
2263 requires std::is_integral_v<Coefficient>
2264 {
2265 try
2266 {
2267 auto [q, r] = f.divmod(candidate);
2268 if (not r.is_zero())
2269 return false;
2270 quotient = std::move(q);
2271 return true;
2272 }
2273 catch (const std::domain_error &)
2274 {
2275 return false;
2276 }
2277 }
2278
2279 [[nodiscard]] static bool try_divide_by_linear_factor(const Gen_Polynomial &f,
2280 Coefficient a,
2281 Coefficient b,
2282 Gen_Polynomial &quotient)
2283 requires std::is_integral_v<Coefficient>
2284 {
2285 if (f.is_zero() or f.degree() == 0)
2286 return false;
2287
2288 if (a == Coefficient{})
2289 return false;
2290
2291 const size_t degree = f.degree();
2292 Array<Coefficient> q_coeffs(degree, Coefficient{});
2293
2294 const Coefficient leading = f.get_coeff(degree);
2295 if (leading % a != Coefficient{})
2296 return false;
2297
2298 q_coeffs(degree - 1) = leading / a;
2299
2300 for (size_t k = degree - 1; k > 0; --k)
2301 {
2302 const Coefficient numerator = f.get_coeff(k) - b * q_coeffs(k);
2303 if (numerator % a != Coefficient{})
2304 return false;
2305 q_coeffs(k - 1) = numerator / a;
2306 }
2307
2308 if (f.get_coeff(0) - b * q_coeffs(0) != Coefficient{})
2309 return false;
2310
2311 quotient = Gen_Polynomial();
2312 for (size_t exp = 0; exp < degree; ++exp)
2313 if (q_coeffs(exp) != Coefficient{})
2314 quotient.set_coeff(exp, q_coeffs(exp));
2315
2316 return true;
2317 }
2318
2319 [[nodiscard]] static bool try_extract_rational_linear_factor(const Gen_Polynomial &f,
2320 Gen_Polynomial &factor,
2321 Gen_Polynomial &quotient)
2322 requires std::is_integral_v<Coefficient>
2323 {
2324 if (f.is_zero() or f.degree() == 0)
2325 return false;
2326
2327 if (f.get_coeff(0) == Coefficient{})
2328 {
2329 if (try_divide_by_linear_factor(f, Coefficient(1), Coefficient{}, quotient))
2330 {
2331 factor = Gen_Polynomial(Coefficient(1), 1);
2332 return true;
2333 }
2334 return false;
2335 }
2336
2337 DynList<Coefficient> numerator_divs = positive_divisors(f.get_coeff(0));
2338 DynList<Coefficient> denominator_divs = positive_divisors(f.leading_coeff());
2339
2340 for (auto den_it = denominator_divs.get_it(); den_it.has_curr(); den_it.next_ne())
2341 {
2342 const Coefficient den = den_it.get_curr();
2343
2344 for (auto num_it = numerator_divs.get_it(); num_it.has_curr(); num_it.next_ne())
2345 {
2346 const Coefficient num_abs = num_it.get_curr();
2347
2348 for (Coefficient sign : {Coefficient(1), Coefficient(-1)})
2349 {
2350 const Coefficient num = sign * num_abs;
2351 if (std::gcd(polynomial_detail::abs_to_u64(num),
2353 continue;
2354
2355 if (try_divide_by_linear_factor(f, den, -num, quotient))
2356 {
2357 factor = Gen_Polynomial();
2358 factor.set_coeff(0, -num);
2359 factor.set_coeff(1, den);
2360 return true;
2361 }
2362 }
2363 }
2364 }
2365
2366 return false;
2367 }
2368
2377 [[nodiscard]] static bool try_extract_primitive_quadratic_factor(const Gen_Polynomial &f,
2378 Gen_Polynomial &factor,
2379 Gen_Polynomial &quotient)
2380 requires std::is_integral_v<Coefficient>
2381 {
2382 if (f.is_zero() or f.degree() < 2)
2383 return false;
2384
2385 if (f.get_coeff(0) == Coefficient{})
2386 return false;
2387
2388 DynList<Coefficient> leading_divs = positive_divisors(f.leading_coeff());
2389 DynList<Coefficient> constant_divs = positive_divisors(f.get_coeff(0));
2390 if (leading_divs.is_empty() or constant_divs.is_empty())
2391 return false;
2392
2393 const double abs_lc = std::abs(static_cast<double>(f.leading_coeff()));
2394 double max_ratio = 0.0;
2395 for (auto it = f.coeffs.get_it(); it.has_curr(); it.next_ne())
2396 {
2397 const auto &term = it.get_curr();
2398 if (term.first == f.degree())
2399 continue;
2400 if (const double ratio = std::abs(static_cast<double>(term.second)) / abs_lc;
2401 ratio > max_ratio)
2402 max_ratio = ratio;
2403 }
2404
2405 const double root_bound = 1.0 + max_ratio;
2406
2407 for (auto a_it = leading_divs.get_it(); a_it.has_curr(); a_it.next_ne())
2408 {
2409 const Coefficient a = a_it.get_curr();
2410 const int64_t b_bound =
2411 static_cast<int64_t>(std::ceil(2.0 * std::abs(static_cast<double>(a)) * root_bound));
2412
2413 for (auto c_it = constant_divs.get_it(); c_it.has_curr(); c_it.next_ne())
2414 {
2415 const Coefficient c_abs = c_it.get_curr();
2416
2417 for (Coefficient sign : {Coefficient(1), Coefficient(-1)})
2418 {
2419 const Coefficient c = sign * c_abs;
2420
2421 for (int64_t b_i = -b_bound; b_i <= b_bound; ++b_i)
2422 {
2423 const Coefficient b = static_cast<Coefficient>(b_i);
2424 const uint64_t gcd_ab =
2426 if (std::gcd(gcd_ab, polynomial_detail::abs_to_u64(c)) != 1)
2427 continue;
2428
2429 Gen_Polynomial candidate;
2430 candidate.set_coeff(0, c);
2431 if (b != Coefficient{})
2432 candidate.set_coeff(1, b);
2433 candidate.set_coeff(2, a);
2434
2436 if (try_exact_candidate_division(f, candidate, q))
2437 {
2438 factor = candidate.primitive_part();
2439 quotient = q.is_zero() ? q : q.primitive_part();
2440 return true;
2441 }
2442 }
2443 }
2444 }
2445 }
2446
2447 return false;
2448 }
2449
2458 [[nodiscard]] static bool try_extract_primitive_cubic_factor(const Gen_Polynomial &f,
2459 Gen_Polynomial &factor,
2460 Gen_Polynomial &quotient)
2461 requires std::is_integral_v<Coefficient>
2462 {
2463 if (f.is_zero() or f.degree() < 3)
2464 return false;
2465
2466 if (f.get_coeff(0) == Coefficient{})
2467 return false;
2468
2469 DynList<Coefficient> leading_divs = positive_divisors(f.leading_coeff());
2470 DynList<Coefficient> constant_divs = positive_divisors(f.get_coeff(0));
2471 if (leading_divs.is_empty() or constant_divs.is_empty())
2472 return false;
2473
2474 const double abs_lc = std::abs(static_cast<double>(f.leading_coeff()));
2475 double l2_norm_sq = 0.0;
2476 for (auto it = f.coeffs.get_it(); it.has_curr(); it.next_ne())
2477 {
2478 const auto &term = it.get_curr();
2479 const double coeff_abs = std::abs(static_cast<double>(term.second));
2480 l2_norm_sq += coeff_abs * coeff_abs;
2481 }
2482
2483 const int64_t coeff_bound = static_cast<int64_t>(std::ceil(8.0 * std::sqrt(l2_norm_sq) / abs_lc));
2484 if (coeff_bound <= 0)
2485 return false;
2486
2487 for (auto a_it = leading_divs.get_it(); a_it.has_curr(); a_it.next_ne())
2488 {
2489 const Coefficient a = a_it.get_curr();
2490 if (polynomial_detail::abs_to_u64(a) > static_cast<uint64_t>(coeff_bound))
2491 continue;
2492
2493 for (auto d_it = constant_divs.get_it(); d_it.has_curr(); d_it.next_ne())
2494 {
2495 const Coefficient d_abs = d_it.get_curr();
2496 if (polynomial_detail::abs_to_u64(d_abs) > static_cast<uint64_t>(coeff_bound))
2497 continue;
2498
2499 for (Coefficient sign : {Coefficient(1), Coefficient(-1)})
2500 {
2501 const Coefficient d = sign * d_abs;
2502
2503 for (int64_t b_i = -coeff_bound; b_i <= coeff_bound; ++b_i)
2504 {
2505 const Coefficient b = static_cast<Coefficient>(b_i);
2506 const uint64_t gcd_ab =
2508
2509 for (int64_t c_i = -coeff_bound; c_i <= coeff_bound; ++c_i)
2510 {
2511 const Coefficient c = static_cast<Coefficient>(c_i);
2512 const uint64_t gcd_abc = std::gcd(gcd_ab, polynomial_detail::abs_to_u64(c));
2513 if (std::gcd(gcd_abc, polynomial_detail::abs_to_u64(d)) != 1)
2514 continue;
2515
2516 Gen_Polynomial candidate;
2517 candidate.set_coeff(0, d);
2518 if (c != Coefficient{})
2519 candidate.set_coeff(1, c);
2520 if (b != Coefficient{})
2521 candidate.set_coeff(2, b);
2522 candidate.set_coeff(3, a);
2523
2525 if (try_exact_candidate_division(f, candidate, q))
2526 {
2527 factor = candidate.primitive_part();
2528 quotient = q.is_zero() ? q : q.primitive_part();
2529 return true;
2530 }
2531 }
2532 }
2533 }
2534 }
2535 }
2536
2537 return false;
2538 }
2539
2558 requires std::is_integral_v<Coefficient>
2559 {
2560 ah_domain_error_if(p <= Coefficient(1)) << "factor_mod_p: modulus p must be > 1, got " << p;
2561
2563
2564 if (f.is_zero() or f.is_constant())
2565 return result;
2566
2567 Gen_Polynomial remaining = reduce_coeffs_mod(f, p);
2568
2569 for (Coefficient r = Coefficient{}; r < p; r = r + Coefficient(1))
2570 {
2571 while (not remaining.is_zero() and remaining.degree() > 0 and
2572 eval_mod_u64(remaining,
2575 {
2576 Gen_Polynomial factor;
2577 factor.set_coeff(0, ((-r) % p + p) % p);
2578 factor.set_coeff(1, Coefficient(1));
2579 result.append(factor);
2580 remaining = divide_by_monic_linear_mod(remaining, r, p);
2581 }
2582 }
2583
2584 if (not remaining.is_zero() and not remaining.is_constant())
2585 result.append(remaining);
2586
2587 return result;
2588 }
2589
2601 [[nodiscard]] double mignotte_bound() const
2602 requires std::is_integral_v<Coefficient>
2603 {
2604 if (is_zero())
2605 return 0.0;
2606
2607 const size_t d = degree();
2608 if (d == 0)
2609 return 0.0;
2610
2611 Coefficient max_coeff = Coefficient{};
2612 for (auto it = coeffs.get_it(); it.has_curr(); it.next_ne())
2613 {
2614 auto &p = it.get_curr();
2615 Coefficient abs_c = p.second < Coefficient{} ? -p.second : p.second;
2616 if (abs_c > max_coeff)
2617 max_coeff = abs_c;
2618 }
2619
2620 const auto d_real = static_cast<double>(d);
2621 const auto max_real = static_cast<double>(max_coeff);
2622 const double two_pow_d = polynomial_detail::power(2.0, d);
2623
2624 return std::sqrt(d_real + 1.0) * two_pow_d * max_real;
2625 }
2626
2650 Coefficient p,
2651 size_t levels)
2652 requires std::is_integral_v<Coefficient>
2653 {
2654 ah_domain_error_if(p <= Coefficient(1)) << "hensel_lift: modulus p must be > 1, got " << p;
2655 ah_domain_error_if(levels == 0) << "hensel_lift: levels must be >= 1, got " << levels;
2656 ah_domain_error_if(levels > 30)
2657 << "hensel_lift: levels must be <= 30 to avoid overflow, got " << levels;
2658
2659 if (factors.is_empty())
2660 return factors;
2661
2662 const size_t target_steps = static_cast<size_t>(1) << levels;
2663 const uint64_t p_u64 = polynomial_detail::abs_to_u64(p);
2664 const auto checked_mul_u64 = [](uint64_t lhs, uint64_t rhs, const char *name) -> uint64_t
2665 {
2666 ah_domain_error_if(rhs != 0 and lhs > std::numeric_limits<uint64_t>::max() / rhs)
2667 << "hensel_lift: overflow computing " << name << " (" << lhs << " * " << rhs << ")";
2668 return lhs * rhs;
2669 };
2670
2671 uint64_t target_u64 = p_u64;
2672 for (size_t i = 1; i < target_steps; ++i)
2673 target_u64 = checked_mul_u64(target_u64, p_u64, "target_u64");
2674
2675 ah_domain_error_if(target_u64 > static_cast<uint64_t>(std::numeric_limits<Coefficient>::max()))
2676 << "hensel_lift: target modulus " << target_u64 << " does not fit in coefficient type";
2677 const Coefficient p_power = static_cast<Coefficient>(target_u64);
2679
2681 for (auto it = factors.get_it(); it.has_curr(); it.next_ne())
2682 {
2683 const Gen_Polynomial &factor = it.get_curr();
2684 bool lifted_linear_factor = false;
2685
2686 if (factor.degree() == 1 and factor.get_coeff(1) == Coefficient(1))
2687 {
2688 uint64_t root = polynomial_detail::normalize_mod_u64(-factor.get_coeff(0), p_u64);
2689 uint64_t modulus = p_u64;
2690 bool simple = true;
2691
2692 for (size_t step = 1; step < target_steps; ++step)
2693 {
2694 const uint64_t next_mod = checked_mul_u64(modulus, p_u64, "next_mod");
2695 const uint64_t f_val = eval_mod_u64(f, root, next_mod);
2696 const uint64_t deriv_modp = eval_mod_u64(derivative, root % p_u64, p_u64);
2697
2698 if (f_val % modulus != 0 or std::gcd(deriv_modp, p_u64) != 1)
2699 {
2700 simple = false;
2701 break;
2702 }
2703
2704 const uint64_t e = (f_val / modulus) % p_u64;
2705 const uint64_t inv = mod_inv(deriv_modp, p_u64);
2706 const uint64_t t = (p_u64 - mod_mul(e, inv, p_u64)) % p_u64;
2707
2708 const uint64_t increment = checked_mul_u64(modulus, t, "root increment");
2709#if defined(_MSC_VER) or defined(_WIN32)
2710 // MSVC has no __int128. clang-cl on Windows has __int128 but
2711 // lacks the __umodti3 runtime helper for 128-bit modulo.
2712 // Compute (root+increment) % next_mod without 128-bit arithmetic.
2713 {
2714 const uint64_t a = root % next_mod;
2715 const uint64_t b = increment % next_mod;
2716 root = (a >= next_mod - b) ? (a - (next_mod - b)) : (a + b);
2717 }
2718#else
2719 root = static_cast<uint64_t>((static_cast<unsigned __int128>(root) + increment) %
2720 next_mod);
2721#endif
2722 modulus = next_mod;
2723 }
2724
2725 if (simple)
2726 {
2727 Gen_Polynomial lifted;
2728 lifted.set_coeff(0,
2729 polynomial_detail::centered_from_mod_u64<Coefficient>(
2730 (target_u64 - (root % target_u64)) % target_u64, target_u64));
2731 lifted.set_coeff(1, Coefficient(1));
2732 result.append(lifted);
2733 lifted_linear_factor = true;
2734 }
2735 }
2736
2737 if (lifted_linear_factor)
2738 continue;
2739
2740 Gen_Polynomial normalized;
2741 factor.for_each_term([&normalized, p_power](size_t exp, const Coefficient &coeff)
2742 {
2743 Coefficient canonical = coeff % p_power;
2744 if (canonical < Coefficient{})
2745 canonical += p_power;
2746 if (canonical != Coefficient{})
2747 normalized.set_coeff(exp, canonical);
2748 });
2749 result.append(normalized);
2750 }
2751
2752 return result;
2753 }
2754
2785 [[nodiscard]] DynList<SfdTerm> factorize() const
2786 requires std::is_integral_v<Coefficient>
2787 {
2788 DynList<SfdTerm> result;
2789
2790 if (is_zero() or is_constant())
2791 return result;
2792
2793 const Coefficient c = content();
2794 if (c != Coefficient(1))
2795 result.append(SfdTerm{Gen_Polynomial(c), 1});
2796
2797 // Step 1: Get primitive part
2799
2800 // Step 2: Compute square-free decomposition
2801 DynList<SfdTerm> sfd_terms = prim.yun_sfd();
2802
2803 if (sfd_terms.is_empty())
2804 return result;
2805
2806 // Step 3: For each square-free group, attempt factorization
2807 for (auto it = sfd_terms.get_it(); it.has_curr(); it.next_ne())
2808 {
2809 auto &sfd_term = it.get_curr();
2810 Gen_Polynomial factor = sfd_term.factor;
2811 size_t mult = sfd_term.multiplicity;
2812 Gen_Polynomial remaining = factor.primitive_part();
2813
2814 while (remaining.degree() > 0)
2815 {
2816 Gen_Polynomial exact_linear, quotient;
2817 if (not try_extract_rational_linear_factor(remaining, exact_linear, quotient))
2818 break;
2819
2820 result.append(SfdTerm{exact_linear.primitive_part(), mult});
2821 remaining = quotient.is_zero() ? quotient : quotient.primitive_part();
2822 }
2823
2824 while (remaining.degree() > 1)
2825 {
2826 Gen_Polynomial exact_quadratic, quotient;
2827 if (not try_extract_primitive_quadratic_factor(remaining, exact_quadratic, quotient))
2828 break;
2829
2830 result.append(SfdTerm{exact_quadratic.primitive_part(), mult});
2831 remaining = quotient.is_zero() ? quotient : quotient.primitive_part();
2832 }
2833
2834 while (remaining.degree() > 2)
2835 {
2836 Gen_Polynomial exact_cubic, quotient;
2837 if (not try_extract_primitive_cubic_factor(remaining, exact_cubic, quotient))
2838 break;
2839
2840 result.append(SfdTerm{exact_cubic.primitive_part(), mult});
2841 remaining = quotient.is_zero() ? quotient : quotient.primitive_part();
2842 }
2843
2844 if (remaining.is_constant() or remaining.is_zero())
2845 continue;
2846
2847 // Try modular factorization with a few small primes and exact redivision.
2848 for (Coefficient p : {Coefficient(3), Coefficient(5), Coefficient(7), Coefficient(11)})
2849 {
2850 if (remaining.leading_coeff() % p == Coefficient{})
2851 continue;
2852
2853 auto mod_factors = factor_mod_p(remaining, p);
2854 if (mod_factors.size() <= 1)
2855 continue;
2856
2857 auto lifted = hensel_lift(remaining, mod_factors, p, 2);
2858
2859 bool changed = false;
2860 for (auto jt = lifted.get_it(); jt.has_curr(); jt.next_ne())
2861 {
2862 Gen_Polynomial cand = jt.get_curr().primitive_part();
2863 if (cand.is_zero() or cand.is_constant() or cand.degree() != 1)
2864 continue;
2865
2866 Gen_Polynomial quotient;
2867 if (not try_divide_by_linear_factor(remaining, cand.get_coeff(1), cand.get_coeff(0),
2868 quotient))
2869 continue;
2870
2871 result.append(SfdTerm{cand, mult});
2872 remaining = quotient.is_zero() ? quotient : quotient.primitive_part();
2873 changed = true;
2874
2875 if (remaining.is_constant())
2876 break;
2877 }
2878
2879 if (changed)
2880 {
2881 if (remaining.is_constant())
2882 break;
2883 }
2884 }
2885
2886 if (not remaining.is_constant() and not remaining.is_zero())
2887 result.append(SfdTerm{remaining.primitive_part(), mult});
2888 }
2889
2890 return result;
2891 }
2892};
2893
2894// =================================================================
2895// Free functions
2896// =================================================================
2897
2899template <typename C>
2900[[nodiscard]] Gen_Polynomial<C> operator * (const C &s, const Gen_Polynomial<C> &p)
2901{
2902 return p * s;
2903}
2904
2906template <typename C>
2907[[nodiscard]] Gen_Polynomial<C> operator + (const C &s, const Gen_Polynomial<C> &p)
2908{
2909 return p + s;
2910}
2911
2913template <typename C>
2914[[nodiscard]] Gen_Polynomial<C> operator - (const C &s, const Gen_Polynomial<C> &p)
2915{
2916 return Gen_Polynomial<C>(s) - p;
2917}
2918
2920template <typename C>
2921std::ostream &operator << (std::ostream &out, const Gen_Polynomial<C> &p)
2922{
2923 return out << p.to_str();
2924}
2925
2926// =================================================================
2927// Convenience type aliases
2928// =================================================================
2929
2932
2935
2938
2941
2942} // end namespace Aleph
2943
2944#endif // TPL_POLYNOMIAL_H
Exception handling system with formatted messages for Aleph-w.
#define ah_domain_error_if(C)
Throws std::domain_error if condition holds.
Definition ah-errors.H:670
long double h
Definition btreepic.C:154
long double w
Definition btreepic.C:153
size_t size_t int32_t value
Definition ca-c-api.h:116
size_t size_t int32_t * out
Definition ca-c-api.h:120
Simple dynamic array with automatic resizing and functional operations.
Definition tpl_array.H:141
static Array create_reserved(const size_t cap)
Build an empty array with room for at least cap items.
Definition tpl_array.H:194
void putn(const size_t n)
Reserve n additional logical slots in the array without value-initializing them.
Definition tpl_array.H:392
Doubly-linked list (defined in tpl_dynList.H).
Definition htlist.H:1231
T & append(const T &item)
Definition htlist.H:1362
Generic key-value map implemented on top of a binary search tree.
auto for_each(Operation &operation) const -> decltype(self())
Apply an operation to each element (read-only).
Univariate polynomial over a generic coefficient ring.
Gen_Polynomial nth_derivative(size_t n) const
-th derivative .
std::pair< size_t, Coefficient > Term
static Gen_Polynomial divide_by_monic_linear_mod(const Gen_Polynomial &f, Coefficient root, Coefficient mod)
Gen_Polynomial(const DynList< std::pair< size_t, Coefficient > > &term_list)
Sparse construction from a list of (exponent, coefficient) pairs.
DynList< Gen_Polynomial > sturm_chain() const
Sturm sequence of this polynomial.
bool is_monic() const noexcept
True if leading coefficient equals 1.
Coefficient horner_eval(const Coefficient &x) const
Evaluate using gap-aware Horner's method.
Gen_Polynomial negate_arg() const
Argument negation: .
static Gen_Polynomial zero()
The zero polynomial.
void for_each_term(Op &&op) const
Iterate over non-zero terms in ascending exponent order.
static Gen_Polynomial one()
The constant polynomial 1.
Coefficient content() const
Content: GCD of all coefficients.
void divide_scalar_inplace(const Coefficient &s)
Divide every coefficient in place by a scalar.
size_t num_terms() const noexcept
Number of non-zero terms.
void add_scaled_shifted(const Gen_Polynomial &src, const Coefficient &scale, size_t shift=0)
Add scale times src shifted by shift to this polynomial.
DynList< size_t > exponents() const
All exponents with non-zero coefficients (sorted ascending).
void add_to_coeff(size_t exp, const Coefficient &delta)
Add a delta to one coefficient, erasing the term if it cancels.
Coefficient * coeff_ptr(size_t exp) noexcept
Pointer to stored coefficient, or null if absent.
Gen_Polynomial operator/(const Coefficient &s) const
Divide by a scalar.
static DynList< Gen_Polynomial > factor_mod_p(const Gen_Polynomial &f, Coefficient p)
Factorization over integers mod p (trial method).
Gen_Polynomial primitive_part() const
Primitive part: polynomial divided by its content.
Coefficient cauchy_bound() const
Cauchy upper bound on absolute value of roots.
Gen_Polynomial & operator-=(const Gen_Polynomial &q)
In-place subtraction.
static bool try_extract_rational_linear_factor(const Gen_Polynomial &f, Gen_Polynomial &factor, Gen_Polynomial &quotient)
void remove_zeros()
Remove all entries whose coefficient is (approximately) zero.
Coefficient eval(const Coefficient &x) const
Evaluate with adaptive strategy.
Coefficient coeff_at(size_t exp) const
Read coefficient at exponent (0 if absent).
Gen_Polynomial & operator+=(const Gen_Polynomial &q)
In-place addition.
Gen_Polynomial truncate(size_t n) const
Truncate to degree less than n.
std::string to_str(const std::string &var="x") const
Human-readable string representation.
static Gen_Polynomial from_roots(const DynList< Coefficient > &roots)
Build polynomial from its roots: .
static Gen_Polynomial interpolate(const DynList< std::pair< Coefficient, Coefficient > > &points)
Polynomial interpolation through a set of points.
Gen_Polynomial operator*(const Gen_Polynomial &q) const
Polynomial multiplication.
bool is_constant() const noexcept
True if constant or zero.
size_t count_real_roots(const Coefficient &a, const Coefficient &b) const
Count distinct real roots in via Sturm's theorem.
void scale_inplace(const Coefficient &s)
Multiply every coefficient in place by a scalar.
Gen_Polynomial pow(size_t n) const
Exponentiation by repeated squaring.
Coefficient operator[](size_t exp) const
Coefficient at exponent exp (0 if absent).
DynList< SfdTerm > yun_sfd() const
Yun's square-free decomposition (SFD).
size_t sign_variations() const
Count sign changes in the coefficient sequence.
bool is_monomial() const noexcept
True if exactly one non-zero term.
bool has_term(size_t exp) const noexcept
True if there is a non-zero coefficient at exp.
const Coefficient * coeff_ptr(size_t exp) const noexcept
Pointer to stored coefficient, or null if absent.
static Xgcd_Result xgcd(Gen_Polynomial a, Gen_Polynomial b)
static Gen_Polynomial integer_gcd(Gen_Polynomial a, Gen_Polynomial b)
Polynomial GCD over integers (Euclidean algorithm with primitive parts).
double mignotte_bound() const
Mignotte bound on integer roots.
Gen_Polynomial compose(const Gen_Polynomial &q) const
Composition .
Coefficient sparse_eval(const Coefficient &x) const
Evaluate using sparse evaluation.
static constexpr Coefficient epsilon() noexcept
Tolerance threshold for floating-point zero detection.
Coefficient definite_integral(const Coefficient &a, const Coefficient &b) const
Definite integral .
bool is_zero() const noexcept
True if this is the zero polynomial.
static bool try_exact_candidate_division(const Gen_Polynomial &f, const Gen_Polynomial &candidate, Gen_Polynomial &quotient)
Try exact division but treat inexact integral division as a rejected candidate.
Gen_Polynomial operator+(const Gen_Polynomial &q) const
Polynomial addition.
size_t count_all_real_roots() const
Total number of distinct real roots.
static size_t sturm_sign_changes(const DynList< Gen_Polynomial > &chain, const Coefficient &x)
Count sign changes in a Sturm chain at a given point.
static Gen_Polynomial _integer_exact_quot(const Gen_Polynomial &a, const Gen_Polynomial &b)
Integer-safe exact quotient using pseudo-division.
Gen_Polynomial(const DynList< Coefficient > &l)
Dense construction from DynList.
Coefficient bisect_root(Coefficient a, Coefficient b, Coefficient tol=Coefficient(1e-12), size_t max_iter=200) const
Find a root by bisection in .
void for_each_term_desc(Op &&op) const
Iterate over non-zero terms in descending exponent order.
Gen_Polynomial(const Coefficient &c)
Constant polynomial .
size_t degree() const noexcept
Degree of the polynomial.
DynList< SfdTerm > factorize() const
Main factorization over integers.
Gen_Polynomial shift_down(size_t k) const
Divide by (shift exponents down).
static DynList< Gen_Polynomial > hensel_lift(const Gen_Polynomial &f, DynList< Gen_Polynomial > factors, Coefficient p, size_t levels)
Hensel lifting of modular factors.
DynList< std::pair< size_t, Coefficient > > terms_list() const
All non-zero terms as a sorted list of (exponent, coefficient).
std::pair< Gen_Polynomial, Gen_Polynomial > divmod(const Gen_Polynomial &d) const
Polynomial long division: returns (quotient, remainder).
static bool try_extract_primitive_quadratic_factor(const Gen_Polynomial &f, Gen_Polynomial &factor, Gen_Polynomial &quotient)
Try to extract an exact primitive quadratic factor over .
Gen_Polynomial & operator/=(const Coefficient &s)
In-place scalar division.
static Gen_Polynomial lcm(const Gen_Polynomial &a, const Gen_Polynomial &b)
Least common multiple.
static uint64_t eval_mod_u64(const Gen_Polynomial &f, uint64_t x, uint64_t mod)
Array< Coefficient > to_dense() const
Dense coefficient vector.
Gen_Polynomial shift_up(size_t k) const
Multiply by (shift exponents up).
DynMapTree< size_t, Coefficient > coeffs
Gen_Polynomial shift(const Coefficient &k) const
Taylor shift: .
static Gen_Polynomial gcd(Gen_Polynomial a, Gen_Polynomial b)
Greatest common divisor (Euclidean algorithm).
Gen_Polynomial square_free() const
Square-free part: .
Gen_Polynomial derivative() const
Formal derivative .
DynList< Coefficient > multi_eval(const DynList< Coefficient > &points) const
Evaluate at multiple points.
std::pair< Gen_Polynomial, Gen_Polynomial > pseudo_divmod(const Gen_Polynomial &d) const
Pseudo-division for non-field coefficient types.
Gen_Polynomial & operator*=(const Gen_Polynomial &q)
In-place multiplication.
Gen_Polynomial integral(const Coefficient &C=Coefficient{}) const
Formal indefinite integral with constant of integration.
Gen_Polynomial operator-() const
Unary negation.
static bool coeff_is_zero(const Coefficient &c) noexcept
Test whether a coefficient is (approximately) zero.
static Gen_Polynomial x_to(size_t n)
The monomial .
static bool try_divide_by_linear_factor(const Gen_Polynomial &f, Coefficient a, Coefficient b, Gen_Polynomial &quotient)
bool operator!=(const Gen_Polynomial &q) const noexcept
Inequality comparison.
Gen_Polynomial()=default
Default constructor: the zero polynomial.
Gen_Polynomial multiply_by_monic_linear(const Coefficient &c) const
Specialized multiplication by a monic linear factor .
static bool try_extract_primitive_cubic_factor(const Gen_Polynomial &f, Gen_Polynomial &factor, Gen_Polynomial &quotient)
Try to extract an exact primitive cubic factor over .
bool operator==(const Gen_Polynomial &q) const noexcept
Equality comparison.
Coefficient leading_coeff() const noexcept
Leading coefficient (of the highest-degree term).
Gen_Polynomial to_monic() const
Make monic: divide by leading coefficient.
Gen_Polynomial & operator%=(const Gen_Polynomial &d)
In-place polynomial remainder.
Coefficient newton_root(Coefficient x0, Coefficient tol=Coefficient(1e-12), size_t max_iter=100) const
Find a root by Newton-Raphson iteration.
bool all_coefficients_finite() const noexcept
True if every coefficient is finite; always, for a type that is not floating.
Gen_Polynomial(std::initializer_list< Coefficient > il)
Dense construction from initializer list.
Gen_Polynomial operator%(const Gen_Polynomial &d) const
Polynomial remainder.
Coefficient operator()(const Coefficient &x) const
Syntactic sugar: p(x) calls eval.
static Gen_Polynomial reduce_coeffs_mod(const Gen_Polynomial &f, Coefficient mod)
void set_coeff(size_t exp, const Coefficient &c)
Set coefficient at exponent; removes entry if zero.
Gen_Polynomial reverse() const
Reciprocal polynomial: .
DynList< Coefficient > coefficients() const
All non-zero coefficients in ascending exponent order.
Gen_Polynomial(const Coefficient &c, size_t exp)
Monomial .
static DynList< Coefficient > positive_divisors(Coefficient value)
Coefficient get_coeff(size_t exp) const noexcept
Coefficient accessor (read-only at exponent).
constexpr bool is_empty() const noexcept
Definition htlist.H:434
void for_each(Operation &operation) const
Traverse all the container and performs an operation on each element.
Definition ah-dry.H:1475
auto get_it()
Return a properly initialized iterator positioned at the first item on the container.
Definition ah-dry.H:663
static Tree_Node< int > * chain(size_t n)
__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< T, __gmp_binary_expr< __gmp_expr< T, U >, unsigned long int, __gmp_root_function > > root(const __gmp_expr< T, U > &expr, unsigned long int l)
Definition gmpfrxx.h:4138
Singly linked list implementations with head-tail access.
Safe modular arithmetic, extended Euclidean algorithm, and Chinese Remainder Theorem.
C power(C base, size_t exp)
Fast exponentiation by squaring.
uint64_t normalize_mod_u64(Int value, const uint64_t modulus) noexcept
uint64_t abs_to_u64(Int value) noexcept
Int centered_from_mod_u64(const uint64_t value, const uint64_t modulus) noexcept
Main namespace for Aleph-w library functions.
Gen_MultiPolynomial< C, M > operator+(const C &s, const Gen_MultiPolynomial< C, M > &p)
Scalar + polynomial (commutative).
uint64_t mod_inv(const uint64_t a, const uint64_t m)
Modular Inverse.
Gen_MultiPolynomial< C, M > operator-(const C &s, const Gen_MultiPolynomial< C, M > &p)
Scalar - polynomial.
and
Check uniqueness with explicit hash + equality functors.
uint64_t mod_exp(uint64_t base, uint64_t exp, const uint64_t m)
Modular exponentiation.
Matrix< Trow, Tcol, NumType > operator*(const NumType &scalar, const Matrix< Trow, Tcol, NumType > &m)
Scalar-matrix multiplication (scalar * matrix).
Definition al-matrix.H:1228
uint64_t mod_mul(uint64_t a, uint64_t b, uint64_t m)
Safe 64-bit modular multiplication.
void next()
Advance all underlying iterators (bounds-checked).
Definition ah-zip.H:236
std::ostream & operator<<(std::ostream &osObject, const Field< T > &rightOp)
Definition ahField.H:121
Itor::difference_type count(const Itor &beg, const Itor &end, const T &value)
Count elements equal to a value.
Definition ahAlgo.H:127
STL namespace.
Square-free decomposition term: factor and multiplicity.
Extended GCD: computes g, s, t such that .
Gen_Polynomial t
Bezout coefficient for the second argument.
Gen_Polynomial s
Bezout coefficient for the first argument.
Gen_Polynomial g
Greatest common divisor (monic).
Aleph::DynList< T > keys() const
See items().
Definition ah-dry.H:2916
static int * k
Gsl_Compatible_Rng r
Dynamic array container with automatic resizing.
Dynamic key-value map based on balanced binary search trees.
DynList< int > l