3 * Functions calculating remainders. */
6 * GiNaC Copyright (C) 1999-2022 Johannes Gutenberg University Mainz, Germany
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
23 #include "remainder.h"
24 #include "ring_traits.h"
31 * @brief Polynomial remainder for univariate polynomials over fields
33 * Given two univariate polynomials \f$a, b \in F[x]\f$, where F is
34 * a finite field (presumably Z/p) computes the remainder @a r, which is
35 * defined as \f$a = b q + r\f$. Returns true if the remainder is zero
36 * and false otherwise.
39 remainder_in_field(umodpoly& r, const umodpoly& a, const umodpoly& b)
41 typedef cln::cl_MI field_t;
43 if (degree(a) < degree(b)) {
47 // The coefficient ring is a field, so any 0 degree polynomial
48 // divides any other polynomial.
55 const field_t b_lcoeff = lcoeff(b);
56 for (std::size_t k = a.size(); k-- >= b.size(); ) {
58 // r -= r_k/b_n x^{k - n} b(x)
62 field_t qk = div(r[k], b_lcoeff);
63 bug_on(zerop(qk), "division in a field yield zero: "
64 << r[k] << '/' << b_lcoeff);
66 // Why C++ is so off-by-one prone?
67 for (std::size_t j = k, i = b.size(); i-- != 0; --j) {
70 r[j] = r[j] - qk*b[i];
72 bug_on(!zerop(r[k]), "polynomial division in field failed: " <<
73 "r[" << k << "] = " << r[k] << ", " <<
74 "r = " << r << ", b = " << b);
78 // Canonicalize the remainder: remove leading zeros. Give a hint
79 // to canonicalize(): we know degree(remainder) < degree(b)
80 // (because the coefficient ring is a field), so
81 // c_{degree(b)} \ldots c_{degree(a)} are definitely zero.
82 std::size_t from = degree(b) - 1;
83 canonicalize(r, from);