57#ifndef TPL_POLYNOMIAL_H
58#define TPL_POLYNOMIAL_H
61#include <initializer_list>
79namespace polynomial_detail {
93 result = result * base;
100template <
typename Int>
101 requires std::is_integral_v<Int>
104 if constexpr (std::is_signed_v<Int>)
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);
112 return static_cast<uint64_t
>(
value);
115template <
typename Int>
116 requires std::is_integral_v<Int>
122 if constexpr (std::is_signed_v<Int>)
124 const auto mod_i64 =
static_cast<int64_t
>(
modulus);
125 auto rem =
static_cast<int64_t
>(
value %
static_cast<Int
>(mod_i64));
128 return static_cast<uint64_t
>(rem);
131 return static_cast<uint64_t
>(
value %
static_cast<Int
>(
modulus));
134template <
typename Int>
135 requires std::is_integral_v<Int>
138 if constexpr (std::is_signed_v<Int>)
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);
165template <
typename Coefficient =
double>
172 using Term = std::pair<size_t, Coefficient>;
182 static constexpr Coefficient
epsilon() noexcept
184 if constexpr (std::is_floating_point_v<Coefficient>)
185 return Coefficient(128) * std::numeric_limits<Coefficient>::epsilon();
187 return Coefficient{};
197 if constexpr (std::is_floating_point_v<Coefficient>)
198 return std::abs(c) <=
epsilon();
200 return c == Coefficient{};
207 for (
auto it =
coeffs.get_it(); it.has_curr(); it.next_ne())
209 auto &p = it.get_curr();
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))
235 return p !=
nullptr ? p->second : Coefficient{};
242 return p !=
nullptr ? &p->second :
nullptr;
249 return p !=
nullptr ? &p->second :
nullptr;
260 *slot = *slot + delta;
292 if (s == Coefficient(1))
296 for (
auto it =
coeffs.get_it(); it.has_curr(); it.next_ne())
298 auto &p = it.get_curr();
299 p.second = p.second * s;
318 if (s == Coefficient(1))
322 for (
auto it =
coeffs.get_it(); it.has_curr(); it.next_ne())
324 auto &p = it.get_curr();
325 p.second = p.second / s;
341 for (
auto it =
coeffs.get_it(); it.has_curr(); it.next_ne())
343 const auto &p = it.get_curr();
344 desc_terms.append(&p);
347 for (
size_t i = desc_terms.size(); i > 0; --i)
349 const Term &term = *desc_terms(i - 1);
350 op(term.first, term.second);
361 for (
auto it =
coeffs.get_it(); it.has_curr(); it.next_ne())
363 auto &p = it.get_curr();
441 term_list.for_each([
this](
const Term &t)
484 roots.
for_each([&result](
const Coefficient &
r)
506 const DynList<std::pair<Coefficient, Coefficient>> &points)
510 const size_t n = points.size();
517 points.for_each([&](
const std::pair<Coefficient, Coefficient> &pt)
524 for (
size_t i = 0; i < n; ++i)
525 for (
size_t j = i + 1; j < n; ++j)
528 for (
size_t order = 1; order < n; ++order)
529 for (
size_t i = n - 1; i >= order; --i)
531 Coefficient denom = xs[i] - xs[i - order];
532 dd[i] = (dd[i] - dd[i - 1]) / denom;
539 for (
size_t i = 1; i < n; ++i)
564 [[nodiscard]]
size_t degree() const noexcept
568 return coeffs.max().first;
586 return coeffs.size() == 1;
611 return Coefficient{};
612 return coeffs.max().second;
637 return Coefficient{};
639 if (x == Coefficient{})
642 Coefficient result = Coefficient{};
677 Coefficient result = Coefficient{};
678 for (
auto it =
coeffs.get_it(); it.has_curr(); it.next_ne())
680 auto &p = it.get_curr();
694 [[nodiscard]] Coefficient
eval(
const Coefficient &x)
const
697 return Coefficient{};
699 if (x == Coefficient{})
709 [[nodiscard]] Coefficient
operator () (
const Coefficient &x)
const
726 points.
for_each([
this, &results](
const Coefficient &x)
741 for (
auto it =
coeffs.get_it(); it.has_curr(); it.next_ne())
743 auto &p = it.get_curr();
744 result.
coeffs[p.first] = -p.second;
766 for (
auto it = q.
coeffs.get_it(); it.has_curr(); it.next_ne())
768 auto &p = it.get_curr();
806 for (
auto it = q.
coeffs.get_it(); it.has_curr(); it.next_ne())
808 auto &p = it.get_curr();
849 for (
auto it1 = outer->
coeffs.get_it(); it1.has_curr(); it1.next_ne())
851 auto &t1 = it1.get_curr();
852 for (
auto it2 = inner->
coeffs.get_it(); it2.has_curr(); it2.next_ne())
854 auto &t2 = it2.get_curr();
855 result.
add_to_coeff(t1.first + t2.first, t1.second * t2.second);
874 for (
auto it =
coeffs.get_it(); it.has_curr(); it.next_ne())
876 auto &p = it.get_curr();
877 Coefficient prod = p.second * s;
879 result.
coeffs[p.first] = prod;
898 for (
auto it =
coeffs.get_it(); it.has_curr(); it.next_ne())
900 auto &p = it.get_curr();
901 Coefficient q = p.second / s;
903 result.
coeffs[p.first] = q;
940 const size_t d_degree = d.
degree();
943 while (not
r.is_zero())
945 const size_t r_degree =
r.degree();
946 if (r_degree < d_degree)
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.";
956 if constexpr (std::is_floating_point_v<Coefficient>)
958 <<
"divmod: the quotient coefficient " << scale <<
" is not finite";
959 const size_t shift = r_degree - d_degree;
962 r.add_scaled_shifted(d, -scale,
shift);
968 <<
"divmod: a coefficient of the quotient or of the remainder overflowed";
1010 for (
auto it =
coeffs.get_it(); it.has_curr(); it.next_ne())
1012 auto &p = it.get_curr();
1015 Coefficient dc = p.second * Coefficient(p.first);
1017 result.
coeffs[p.first - 1] = dc;
1036 for (
size_t i = 0; i < n
and not result.
is_zero(); ++i)
1056 for (
auto it =
coeffs.get_it(); it.has_curr(); it.next_ne())
1058 auto &p = it.get_curr();
1059 Coefficient ic = p.second / Coefficient(p.first + 1);
1061 result.
coeffs[p.first + 1] = ic;
1077 Coefficient result = Coefficient{};
1079 for (
auto it =
coeffs.get_it(); it.has_curr(); it.next_ne())
1081 auto &p = it.get_curr();
1082 const size_t next_exp = p.first + 1;
1083 const Coefficient scale = p.second / Coefficient(next_exp);
1113 size_t prev_exp = 0;
1126 const size_t gap = prev_exp -
exp;
1130 result *= q.
pow(gap);
1138 else if (prev_exp > 1)
1139 result *= q.
pow(prev_exp);
1272 const size_t d_degree = d.
degree();
1273 size_t delta =
degree() - d_degree + 1;
1278 while (not
r.is_zero())
1280 const size_t r_degree =
r.degree();
1281 if (r_degree < d_degree)
1284 const Coefficient lc_r =
r.leading_coeff();
1288 if constexpr (std::is_floating_point_v<Coefficient>)
1290 <<
"pseudo_divmod: a coefficient of the remainder overflowed (" << lc_r <<
")";
1291 const size_t exp = r_degree - d_degree;
1295 r.scale_inplace(lc_d);
1299 r.add_scaled_shifted(d, -lc_r,
exp);
1307 r.scale_inplace(scale);
1313 <<
"pseudo_divmod: a coefficient of the quotient or of the remainder overflowed";
1343 for (
auto it =
coeffs.get_it(); it.has_curr(); it.next_ne())
1345 auto &p = it.get_curr();
1346 result.
coeffs[d - p.first] = p.second;
1358 for (
auto it =
coeffs.get_it(); it.has_curr(); it.next_ne())
1360 auto &p = it.get_curr();
1361 result.
coeffs[p.first] = (p.first % 2 == 0) ? p.second : -p.second;
1391 for (
auto it =
coeffs.get_it(); it.has_curr(); it.next_ne())
1393 auto &p = it.get_curr();
1394 result.
coeffs[p.first +
k] = p.second;
1411 for (
auto it =
coeffs.get_it(); it.has_curr(); it.next_ne())
1413 auto &p = it.get_curr();
1415 result.
coeffs[p.first -
k] = p.second;
1430 for (
auto it =
coeffs.get_it(); it.has_curr(); it.next_ne())
1432 auto &p = it.get_curr();
1434 result.
coeffs[p.first] = p.second;
1451 for (
auto it =
coeffs.get_it(); it.has_curr(); it.next_ne())
1453 auto &p = it.get_curr();
1454 result(p.first) = p.second;
1495 return Coefficient{};
1497 const size_t d =
degree();
1499 if constexpr (std::is_floating_point_v<Coefficient>)
1501 Coefficient max_ratio = Coefficient{};
1502 for (
auto it =
coeffs.get_it(); it.has_curr(); it.next_ne())
1504 auto &p = it.get_curr();
1507 const Coefficient ratio = std::abs(p.second / lc);
1508 if (ratio > max_ratio)
1511 return Coefficient(1) + max_ratio;
1515 long double max_ratio_ld = 0.0L;
1516 for (
auto it =
coeffs.get_it(); it.has_curr(); it.next_ne())
1518 auto &p = it.get_curr();
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;
1526 return Coefficient(1) +
static_cast<Coefficient
>(std::ceil(max_ratio_ld));
1544 bool have_prev =
false;
1545 bool prev_positive =
false;
1547 for (
auto it =
coeffs.get_it(); it.has_curr(); it.next_ne())
1549 auto &p = it.get_curr();
1551 if constexpr (std::is_floating_point_v<Coefficient>)
1552 positive = p.second >
epsilon();
1554 positive = p.second > Coefficient{};
1557 if constexpr (std::is_floating_point_v<Coefficient>)
1558 is_neg = p.second < -
epsilon();
1560 is_neg = p.second < Coefficient{};
1562 if (not positive
and not is_neg)
1565 if (have_prev
and positive != prev_positive)
1567 prev_positive = positive;
1586 chain.append(*
this);
1614 const Coefficient &x)
1617 bool have_prev =
false;
1618 bool prev_positive =
false;
1622 Coefficient val = p(x);
1626 bool positive = val > Coefficient{};
1627 if (have_prev
and positive != prev_positive)
1629 prev_positive = positive;
1660 size_t count = sa > sb ? sa - sb : 0;
1697 Coefficient tol = Coefficient(1e-12),
1698 size_t max_iter = 200)
const
1703 Coefficient fa =
eval(a), fb =
eval(b);
1711 <<
"bisect_root: f(a) and f(b) must have opposite signs";
1713 for (
size_t i = 0; i < max_iter; ++i)
1715 Coefficient mid = (a + b) / Coefficient(2);
1718 Coefficient fm =
eval(mid);
1721 if (fa > Coefficient{} == fm > Coefficient{})
1732 return (a + b) / Coefficient(2);
1745 Coefficient tol = Coefficient(1e-12),
1746 size_t max_iter = 100) const
1747 requires
std::is_floating_point_v<Coefficient>
1751 for (
size_t i = 0; i < max_iter; ++i)
1753 Coefficient fx =
eval(x0);
1756 Coefficient dfx = dp.
eval(x0);
1758 Coefficient x1 = x0 - fx / dfx;
1759 Coefficient delta = x1 - x0;
1760 if constexpr (std::is_floating_point_v<Coefficient>)
1762 if (std::abs(delta) < tol)
1767 if (delta == Coefficient{})
1789 auto it1 =
coeffs.get_it();
1790 auto it2 = q.coeffs.get_it();
1792 while (it1.has_curr()
and it2.has_curr())
1794 auto &lhs = it1.get_curr();
1795 auto &rhs = it2.get_curr();
1797 if (lhs.first == rhs.first)
1806 if (lhs.first < rhs.first)
1819 while (it1.has_curr())
1826 while (it2.has_curr())
1839 return not (*
this == q);
1853 for (
auto it =
coeffs.get_it(); it.has_curr(); it.next_ne())
1855 auto &p = it.get_curr();
1856 op(p.first, p.second);
1864 for (
auto it =
coeffs.get_it(); it.has_curr(); it.next_ne())
1866 auto &p = it.get_curr();
1867 result.
append({p.first, p.second});
1895 [[nodiscard]] std::string
to_str(
const std::string &var =
"x")
const
1900 std::ostringstream oss;
1905 bool negative =
false;
1906 if constexpr (
requires { c < Coefficient{}; })
1907 negative = c < Coefficient{};
1909 Coefficient ac = negative ? -c : c;
1918 oss << (negative ?
" - " :
" + ");
1925 if (not (ac == Coefficient(1)))
1993 requires
std::is_integral_v<Coefficient>
1996 return Coefficient{};
1998 Coefficient result = Coefficient{};
1999 for (
auto it =
coeffs.get_it(); it.has_curr(); it.next_ne())
2001 auto &p = it.get_curr();
2002 result = std::gcd(result, p.second);
2007 if (lc < Coefficient{}
and result > Coefficient{})
2022 requires
std::is_integral_v<Coefficient>
2028 if (c == Coefficient{} or c == Coefficient(1) or c == Coefficient(-1))
2038 for (
auto it =
coeffs.get_it(); it.has_curr(); it.next_ne())
2040 auto &p = it.get_curr();
2041 result.
coeffs.insert(p.first, p.second / c);
2064 requires std::is_integral_v<Coefficient>
2074 while (not b.is_zero())
2078 b = rem.is_zero() ? rem : rem.primitive_part();
2081 return a.primitive_part();
2100 requires
std::is_integral_v<Coefficient>
2113 size_t multiplicity = 1;
2115 while (not
h.is_constant())
2121 if (not
w.is_constant())
2146 requires std::is_integral_v<Coefficient>
2149 if (b.is_constant())
2153 for (
auto it = a.coeffs.get_it(); it.has_curr(); it.next_ne())
2155 auto &p = it.get_curr();
2157 <<
"_integer_exact_quot: inexact constant division for coefficient " << p.second
2158 <<
" and divisor " << d;
2159 r.coeffs.insert(p.first, p.second / d);
2163 auto [q, rem] = a.pseudo_divmod(b);
2165 <<
"_integer_exact_quot: divisor does not divide dividend exactly";
2166 return q.is_zero() ? q : q.primitive_part();
2170 requires std::is_integral_v<Coefficient>
2175 Coefficient c = coeff % mod;
2176 if (c < Coefficient{})
2178 if (c != Coefficient{})
2185 requires std::is_integral_v<Coefficient>
2187 if (mod == 0 or mod == 1)
2190 uint64_t result = 0;
2195 const uint64_t term =
mod_mul(c, xpow, mod);
2196 result = (result + term) % mod;
2204 requires std::is_integral_v<Coefficient>
2207 <<
"divide_by_monic_linear_mod: constant polynomial is not divisible by x - r";
2212 synthetic(
degree) = ((f.get_coeff(
degree) % mod) + mod) % mod;
2214 for (
size_t idx =
degree; idx-- > 0;)
2216 Coefficient term = (f.get_coeff(idx) % mod + mod) % mod;
2217 Coefficient
next = (term + (synthetic(idx + 1) *
root) % mod) % mod;
2218 synthetic(idx) =
next;
2222 <<
"divide_by_monic_linear_mod: x - r does not divide polynomial modulo p";
2226 if (synthetic(
exp + 1) != Coefficient{})
2233 requires std::is_integral_v<Coefficient>
2241 for (uint64_t d = 1; d * d <= abs_value; ++d)
2242 if (abs_value % d == 0)
2244 result.
append(
static_cast<Coefficient
>(d));
2245 const uint64_t other = abs_value / d;
2247 result.
append(
static_cast<Coefficient
>(other));
2263 requires std::is_integral_v<Coefficient>
2267 auto [q,
r] = f.divmod(candidate);
2268 if (not
r.is_zero())
2270 quotient = std::move(q);
2273 catch (
const std::domain_error &)
2283 requires std::is_integral_v<Coefficient>
2285 if (f.is_zero() or f.degree() == 0)
2288 if (a == Coefficient{})
2291 const size_t degree = f.degree();
2294 const Coefficient leading = f.get_coeff(
degree);
2295 if (leading % a != Coefficient{})
2298 q_coeffs(
degree - 1) = leading / a;
2302 const Coefficient numerator = f.get_coeff(
k) - b * q_coeffs(
k);
2303 if (numerator % a != Coefficient{})
2305 q_coeffs(
k - 1) = numerator / a;
2308 if (f.get_coeff(0) - b * q_coeffs(0) != Coefficient{})
2313 if (q_coeffs(
exp) != Coefficient{})
2314 quotient.set_coeff(
exp, q_coeffs(
exp));
2322 requires std::is_integral_v<Coefficient>
2324 if (f.is_zero() or f.degree() == 0)
2327 if (f.get_coeff(0) == Coefficient{})
2340 for (
auto den_it = denominator_divs.
get_it(); den_it.has_curr(); den_it.next_ne())
2342 const Coefficient den = den_it.get_curr();
2344 for (
auto num_it = numerator_divs.
get_it(); num_it.has_curr(); num_it.next_ne())
2346 const Coefficient num_abs = num_it.get_curr();
2348 for (Coefficient sign : {Coefficient(1), Coefficient(-1)})
2350 const Coefficient num = sign * num_abs;
2358 factor.set_coeff(0, -num);
2359 factor.set_coeff(1, den);
2380 requires std::is_integral_v<Coefficient>
2382 if (f.is_zero() or f.degree() < 2)
2385 if (f.get_coeff(0) == Coefficient{})
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())
2397 const auto &term = it.get_curr();
2398 if (term.first == f.degree())
2400 if (
const double ratio = std::abs(
static_cast<double>(term.second)) / abs_lc;
2405 const double root_bound = 1.0 + max_ratio;
2407 for (
auto a_it = leading_divs.
get_it(); a_it.has_curr(); a_it.next_ne())
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));
2413 for (
auto c_it = constant_divs.
get_it(); c_it.has_curr(); c_it.next_ne())
2415 const Coefficient c_abs = c_it.get_curr();
2417 for (Coefficient sign : {Coefficient(1), Coefficient(-1)})
2419 const Coefficient c = sign * c_abs;
2421 for (int64_t b_i = -b_bound; b_i <= b_bound; ++b_i)
2423 const Coefficient b =
static_cast<Coefficient
>(b_i);
2424 const uint64_t gcd_ab =
2431 if (b != Coefficient{})
2461 requires std::is_integral_v<Coefficient>
2463 if (f.is_zero() or f.degree() < 3)
2466 if (f.get_coeff(0) == Coefficient{})
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())
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;
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)
2487 for (
auto a_it = leading_divs.
get_it(); a_it.has_curr(); a_it.next_ne())
2489 const Coefficient a = a_it.get_curr();
2493 for (
auto d_it = constant_divs.
get_it(); d_it.has_curr(); d_it.next_ne())
2495 const Coefficient d_abs = d_it.get_curr();
2499 for (Coefficient sign : {Coefficient(1), Coefficient(-1)})
2501 const Coefficient d = sign * d_abs;
2503 for (int64_t b_i = -coeff_bound; b_i <= coeff_bound; ++b_i)
2505 const Coefficient b =
static_cast<Coefficient
>(b_i);
2506 const uint64_t gcd_ab =
2509 for (int64_t c_i = -coeff_bound; c_i <= coeff_bound; ++c_i)
2511 const Coefficient c =
static_cast<Coefficient
>(c_i);
2518 if (c != Coefficient{})
2520 if (b != Coefficient{})
2558 requires std::is_integral_v<Coefficient>
2560 ah_domain_error_if(p <= Coefficient(1)) <<
"factor_mod_p: modulus p must be > 1, got " << p;
2564 if (f.is_zero() or f.is_constant())
2569 for (Coefficient
r = Coefficient{};
r < p;
r =
r + Coefficient(1))
2585 result.
append(remaining);
2602 requires
std::is_integral_v<Coefficient>
2607 const size_t d =
degree();
2611 Coefficient max_coeff = Coefficient{};
2612 for (
auto it =
coeffs.get_it(); it.has_curr(); it.next_ne())
2614 auto &p = it.get_curr();
2615 Coefficient abs_c = p.second < Coefficient{} ? -p.second : p.second;
2616 if (abs_c > max_coeff)
2620 const auto d_real =
static_cast<double>(d);
2621 const auto max_real =
static_cast<double>(max_coeff);
2624 return std::sqrt(d_real + 1.0) * two_pow_d * max_real;
2652 requires std::is_integral_v<Coefficient>
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;
2657 <<
"hensel_lift: levels must be <= 30 to avoid overflow, got " << levels;
2659 if (factors.is_empty())
2662 const size_t target_steps =
static_cast<size_t>(1) << levels;
2664 const auto checked_mul_u64 = [](uint64_t lhs, uint64_t rhs,
const char *name) -> uint64_t
2667 <<
"hensel_lift: overflow computing " << name <<
" (" << lhs <<
" * " << rhs <<
")";
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");
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);
2681 for (
auto it = factors.get_it(); it.has_curr(); it.next_ne())
2684 bool lifted_linear_factor =
false;
2692 for (
size_t step = 1; step < target_steps; ++step)
2694 const uint64_t next_mod = checked_mul_u64(
modulus, p_u64,
"next_mod");
2698 if (f_val %
modulus != 0 or std::gcd(deriv_modp, p_u64) != 1)
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;
2708 const uint64_t increment = checked_mul_u64(
modulus, t,
"root increment");
2709#if defined(_MSC_VER) or defined(_WIN32)
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);
2719 root =
static_cast<uint64_t
>((
static_cast<unsigned __int128
>(
root) + increment) %
2729 polynomial_detail::centered_from_mod_u64<Coefficient>(
2730 (target_u64 - (
root % target_u64)) % target_u64, target_u64));
2733 lifted_linear_factor =
true;
2737 if (lifted_linear_factor)
2741 factor.
for_each_term([&normalized, p_power](
size_t exp,
const Coefficient &coeff)
2743 Coefficient canonical = coeff % p_power;
2744 if (canonical < Coefficient{})
2745 canonical += p_power;
2746 if (canonical != Coefficient{})
2749 result.
append(normalized);
2786 requires
std::is_integral_v<Coefficient>
2793 const Coefficient c =
content();
2794 if (c != Coefficient(1))
2807 for (
auto it = sfd_terms.
get_it(); it.has_curr(); it.next_ne())
2809 auto &sfd_term = it.get_curr();
2811 size_t mult = sfd_term.multiplicity;
2814 while (remaining.
degree() > 0)
2824 while (remaining.
degree() > 1)
2834 while (remaining.
degree() > 2)
2848 for (Coefficient p : {Coefficient(3), Coefficient(5), Coefficient(7), Coefficient(11)})
2854 if (mod_factors.size() <= 1)
2857 auto lifted =
hensel_lift(remaining, mod_factors, p, 2);
2859 bool changed =
false;
2860 for (
auto jt = lifted.get_it(); jt.has_curr(); jt.next_ne())
2899template <
typename C>
2906template <
typename C>
2913template <
typename C>
2920template <
typename C>
Exception handling system with formatted messages for Aleph-w.
#define ah_domain_error_if(C)
Throws std::domain_error if condition holds.
size_t size_t int32_t value
size_t size_t int32_t * out
Simple dynamic array with automatic resizing and functional operations.
static Array create_reserved(const size_t cap)
Build an empty array with room for at least cap items.
void putn(const size_t n)
Reserve n additional logical slots in the array without value-initializing them.
Doubly-linked list (defined in tpl_dynList.H).
T & append(const T &item)
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 "ient)
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 "ient)
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 "ient)
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 "ient)
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 "ient)
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
void for_each(Operation &operation) const
Traverse all the container and performs an operation on each element.
auto get_it()
Return a properly initialized iterator positioned at the first item on the container.
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)
__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)
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).
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).
std::ostream & operator<<(std::ostream &osObject, const Field< T > &rightOp)
Itor::difference_type count(const Itor &beg, const Itor &end, const T &value)
Count elements equal to a value.
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().
Dynamic array container with automatic resizing.
Dynamic key-value map based on balanced binary search trees.