3 * This file implements several functions that work on univariate and
4 * multivariate polynomials and rational functions.
5 * These functions include polynomial quotient and remainder, GCD and LCM
6 * computation, square-free factorization and rational function normalization.
9 * GiNaC Copyright (C) 1999 Johannes Gutenberg University Mainz, Germany
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
21 * You should have received a copy of the GNU General Public License
22 * along with this program; if not, write to the Free Software
23 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
33 #include "expairseq.h"
42 #include "relational.h"
46 // If comparing expressions (ex::compare()) is fast, you can set this to 1.
47 // Some routines like quo(), rem() and gcd() will then return a quick answer
48 // when they are called with two identical arguments.
49 #define FAST_COMPARE 1
51 // Set this if you want divide_in_z() to use remembering
52 #define USE_REMEMBER 1
55 /** Return pointer to first symbol found in expression. Due to GiNaCĀ“s
56 * internal ordering of terms, it may not be obvious which symbol this
57 * function returns for a given expression.
59 * @param e expression to search
60 * @param x pointer to first symbol found (returned)
61 * @return "false" if no symbol was found, "true" otherwise */
63 static bool get_first_symbol(const ex &e, const symbol *&x)
65 if (is_ex_exactly_of_type(e, symbol)) {
66 x = static_cast<symbol *>(e.bp);
68 } else if (is_ex_exactly_of_type(e, add) || is_ex_exactly_of_type(e, mul)) {
69 for (int i=0; i<e.nops(); i++)
70 if (get_first_symbol(e.op(i), x))
72 } else if (is_ex_exactly_of_type(e, power)) {
73 if (get_first_symbol(e.op(0), x))
81 * Statistical information about symbols in polynomials
86 /** This structure holds information about the highest and lowest degrees
87 * in which a symbol appears in two multivariate polynomials "a" and "b".
88 * A vector of these structures with information about all symbols in
89 * two polynomials can be created with the function get_symbol_stats().
91 * @see get_symbol_stats */
93 /** Pointer to symbol */
96 /** Highest degree of symbol in polynomial "a" */
99 /** Highest degree of symbol in polynomial "b" */
102 /** Lowest degree of symbol in polynomial "a" */
105 /** Lowest degree of symbol in polynomial "b" */
108 /** Minimum of ldeg_a and ldeg_b (Used for sorting) */
111 /** Commparison operator for sorting */
112 bool operator<(const sym_desc &x) const {return min_deg < x.min_deg;}
115 // Vector of sym_desc structures
116 typedef vector<sym_desc> sym_desc_vec;
118 // Add symbol the sym_desc_vec (used internally by get_symbol_stats())
119 static void add_symbol(const symbol *s, sym_desc_vec &v)
121 sym_desc_vec::iterator it = v.begin(), itend = v.end();
122 while (it != itend) {
123 if (it->sym->compare(*s) == 0) // If it's already in there, don't add it a second time
132 // Collect all symbols of an expression (used internally by get_symbol_stats())
133 static void collect_symbols(const ex &e, sym_desc_vec &v)
135 if (is_ex_exactly_of_type(e, symbol)) {
136 add_symbol(static_cast<symbol *>(e.bp), v);
137 } else if (is_ex_exactly_of_type(e, add) || is_ex_exactly_of_type(e, mul)) {
138 for (int i=0; i<e.nops(); i++)
139 collect_symbols(e.op(i), v);
140 } else if (is_ex_exactly_of_type(e, power)) {
141 collect_symbols(e.op(0), v);
145 /** Collect statistical information about symbols in polynomials.
146 * This function fills in a vector of "sym_desc" structs which contain
147 * information about the highest and lowest degrees of all symbols that
148 * appear in two polynomials. The vector is then sorted by minimum
149 * degree (lowest to highest). The information gathered by this
150 * function is used by the GCD routines to identify trivial factors
151 * and to determine which variable to choose as the main variable
152 * for GCD computation.
154 * @param a first multivariate polynomial
155 * @param b second multivariate polynomial
156 * @param v vector of sym_desc structs (filled in) */
158 static void get_symbol_stats(const ex &a, const ex &b, sym_desc_vec &v)
160 collect_symbols(a.eval(), v); // eval() to expand assigned symbols
161 collect_symbols(b.eval(), v);
162 sym_desc_vec::iterator it = v.begin(), itend = v.end();
163 while (it != itend) {
164 int deg_a = a.degree(*(it->sym));
165 int deg_b = b.degree(*(it->sym));
168 it->min_deg = min(deg_a, deg_b);
169 it->ldeg_a = a.ldegree(*(it->sym));
170 it->ldeg_b = b.ldegree(*(it->sym));
173 sort(v.begin(), v.end());
178 * Computation of LCM of denominators of coefficients of a polynomial
181 // Compute LCM of denominators of coefficients by going through the
182 // expression recursively (used internally by lcm_of_coefficients_denominators())
183 static numeric lcmcoeff(const ex &e, const numeric &l)
185 if (e.info(info_flags::rational))
186 return lcm(ex_to_numeric(e).denom(), l);
187 else if (is_ex_exactly_of_type(e, add) || is_ex_exactly_of_type(e, mul)) {
188 numeric c = numONE();
189 for (int i=0; i<e.nops(); i++) {
190 c = lcmcoeff(e.op(i), c);
193 } else if (is_ex_exactly_of_type(e, power))
194 return lcmcoeff(e.op(0), l);
198 /** Compute LCM of denominators of coefficients of a polynomial.
199 * Given a polynomial with rational coefficients, this function computes
200 * the LCM of the denominators of all coefficients. This can be used
201 * To bring a polynomial from Q[X] to Z[X].
203 * @param e multivariate polynomial
204 * @return LCM of denominators of coefficients */
206 static numeric lcm_of_coefficients_denominators(const ex &e)
208 return lcmcoeff(e.expand(), numONE());
212 /** Compute the integer content (= GCD of all numeric coefficients) of an
213 * expanded polynomial.
215 * @param e expanded polynomial
216 * @return integer content */
218 numeric ex::integer_content(void) const
221 return bp->integer_content();
224 numeric basic::integer_content(void) const
229 numeric numeric::integer_content(void) const
234 numeric add::integer_content(void) const
236 epvector::const_iterator it = seq.begin();
237 epvector::const_iterator itend = seq.end();
238 numeric c = numZERO();
239 while (it != itend) {
240 ASSERT(!is_ex_exactly_of_type(it->rest,numeric));
241 ASSERT(is_ex_exactly_of_type(it->coeff,numeric));
242 c = gcd(ex_to_numeric(it->coeff), c);
245 ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
246 c = gcd(ex_to_numeric(overall_coeff),c);
250 numeric mul::integer_content(void) const
253 epvector::const_iterator it = seq.begin();
254 epvector::const_iterator itend = seq.end();
255 while (it != itend) {
256 ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*it),numeric));
259 #endif // def DOASSERT
260 ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
261 return abs(ex_to_numeric(overall_coeff));
266 * Polynomial quotients and remainders
269 /** Quotient q(x) of polynomials a(x) and b(x) in Q[x].
270 * It satisfies a(x)=b(x)*q(x)+r(x).
272 * @param a first polynomial in x (dividend)
273 * @param b second polynomial in x (divisor)
274 * @param x a and b are polynomials in x
275 * @param check_args check whether a and b are polynomials with rational
276 * coefficients (defaults to "true")
277 * @return quotient of a and b in Q[x] */
279 ex quo(const ex &a, const ex &b, const symbol &x, bool check_args)
282 throw(std::overflow_error("quo: division by zero"));
283 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric))
289 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
290 throw(std::invalid_argument("quo: arguments must be polynomials over the rationals"));
292 // Polynomial long division
297 int bdeg = b.degree(x);
298 int rdeg = r.degree(x);
299 ex blcoeff = b.expand().coeff(x, bdeg);
300 bool blcoeff_is_numeric = is_ex_exactly_of_type(blcoeff, numeric);
301 while (rdeg >= bdeg) {
302 ex term, rcoeff = r.coeff(x, rdeg);
303 if (blcoeff_is_numeric)
304 term = rcoeff / blcoeff;
306 if (!divide(rcoeff, blcoeff, term, false))
307 return *new ex(fail());
309 term *= power(x, rdeg - bdeg);
311 r -= (term * b).expand();
320 /** Remainder r(x) of polynomials a(x) and b(x) in Q[x].
321 * It satisfies a(x)=b(x)*q(x)+r(x).
323 * @param a first polynomial in x (dividend)
324 * @param b second polynomial in x (divisor)
325 * @param x a and b are polynomials in x
326 * @param check_args check whether a and b are polynomials with rational
327 * coefficients (defaults to "true")
328 * @return remainder of a(x) and b(x) in Q[x] */
330 ex rem(const ex &a, const ex &b, const symbol &x, bool check_args)
333 throw(std::overflow_error("rem: division by zero"));
334 if (is_ex_exactly_of_type(a, numeric)) {
335 if (is_ex_exactly_of_type(b, numeric))
344 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
345 throw(std::invalid_argument("rem: arguments must be polynomials over the rationals"));
347 // Polynomial long division
351 int bdeg = b.degree(x);
352 int rdeg = r.degree(x);
353 ex blcoeff = b.expand().coeff(x, bdeg);
354 bool blcoeff_is_numeric = is_ex_exactly_of_type(blcoeff, numeric);
355 while (rdeg >= bdeg) {
356 ex term, rcoeff = r.coeff(x, rdeg);
357 if (blcoeff_is_numeric)
358 term = rcoeff / blcoeff;
360 if (!divide(rcoeff, blcoeff, term, false))
361 return *new ex(fail());
363 term *= power(x, rdeg - bdeg);
364 r -= (term * b).expand();
373 /** Pseudo-remainder of polynomials a(x) and b(x) in Z[x].
375 * @param a first polynomial in x (dividend)
376 * @param b second polynomial in x (divisor)
377 * @param x a and b are polynomials in x
378 * @param check_args check whether a and b are polynomials with rational
379 * coefficients (defaults to "true")
380 * @return pseudo-remainder of a(x) and b(x) in Z[x] */
382 ex prem(const ex &a, const ex &b, const symbol &x, bool check_args)
385 throw(std::overflow_error("prem: division by zero"));
386 if (is_ex_exactly_of_type(a, numeric)) {
387 if (is_ex_exactly_of_type(b, numeric))
392 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
393 throw(std::invalid_argument("prem: arguments must be polynomials over the rationals"));
395 // Polynomial long division
398 int rdeg = r.degree(x);
399 int bdeg = eb.degree(x);
402 blcoeff = eb.coeff(x, bdeg);
406 eb -= blcoeff * power(x, bdeg);
410 int delta = rdeg - bdeg + 1, i = 0;
411 while (rdeg >= bdeg && !r.is_zero()) {
412 ex rlcoeff = r.coeff(x, rdeg);
413 ex term = (power(x, rdeg - bdeg) * eb * rlcoeff).expand();
417 r -= rlcoeff * power(x, rdeg);
418 r = (blcoeff * r).expand() - term;
422 return power(blcoeff, delta - i) * r;
426 /** Exact polynomial division of a(X) by b(X) in Q[X].
428 * @param a first multivariate polynomial (dividend)
429 * @param b second multivariate polynomial (divisor)
430 * @param q quotient (returned)
431 * @param check_args check whether a and b are polynomials with rational
432 * coefficients (defaults to "true")
433 * @return "true" when exact division succeeds (quotient returned in q),
434 * "false" otherwise */
436 bool divide(const ex &a, const ex &b, ex &q, bool check_args)
440 throw(std::overflow_error("divide: division by zero"));
441 if (is_ex_exactly_of_type(b, numeric)) {
444 } else if (is_ex_exactly_of_type(a, numeric))
452 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
453 throw(std::invalid_argument("divide: arguments must be polynomials over the rationals"));
457 if (!get_first_symbol(a, x) && !get_first_symbol(b, x))
458 throw(std::invalid_argument("invalid expression in divide()"));
460 // Polynomial long division (recursive)
464 int bdeg = b.degree(*x);
465 int rdeg = r.degree(*x);
466 ex blcoeff = b.expand().coeff(*x, bdeg);
467 bool blcoeff_is_numeric = is_ex_exactly_of_type(blcoeff, numeric);
468 while (rdeg >= bdeg) {
469 ex term, rcoeff = r.coeff(*x, rdeg);
470 if (blcoeff_is_numeric)
471 term = rcoeff / blcoeff;
473 if (!divide(rcoeff, blcoeff, term, false))
475 term *= power(*x, rdeg - bdeg);
477 r -= (term * b).expand();
493 typedef pair<ex, ex> ex2;
494 typedef pair<ex, bool> exbool;
497 bool operator() (const ex2 p, const ex2 q) const
499 return p.first.compare(q.first) < 0 || (!(q.first.compare(p.first) < 0) && p.second.compare(q.second) < 0);
503 typedef map<ex2, exbool, ex2_less> ex2_exbool_remember;
507 /** Exact polynomial division of a(X) by b(X) in Z[X].
508 * This functions works like divide() but the input and output polynomials are
509 * in Z[X] instead of Q[X] (i.e. they have integer coefficients). Unlike
510 * divide(), it doesnĀ“t check whether the input polynomials really are integer
511 * polynomials, so be careful of what you pass in. Also, you have to run
512 * get_symbol_stats() over the input polynomials before calling this function
513 * and pass an iterator to the first element of the sym_desc vector. This
514 * function is used internally by the heur_gcd().
516 * @param a first multivariate polynomial (dividend)
517 * @param b second multivariate polynomial (divisor)
518 * @param q quotient (returned)
519 * @param var iterator to first element of vector of sym_desc structs
520 * @return "true" when exact division succeeds (the quotient is returned in
521 * q), "false" otherwise.
522 * @see get_symbol_stats, heur_gcd */
523 static bool divide_in_z(const ex &a, const ex &b, ex &q, sym_desc_vec::const_iterator var)
527 throw(std::overflow_error("divide_in_z: division by zero"));
528 if (b.is_equal(exONE())) {
532 if (is_ex_exactly_of_type(a, numeric)) {
533 if (is_ex_exactly_of_type(b, numeric)) {
535 return q.info(info_flags::integer);
548 static ex2_exbool_remember dr_remember;
549 ex2_exbool_remember::const_iterator remembered = dr_remember.find(ex2(a, b));
550 if (remembered != dr_remember.end()) {
551 q = remembered->second.first;
552 return remembered->second.second;
557 const symbol *x = var->sym;
560 int adeg = a.degree(*x), bdeg = b.degree(*x);
566 // Polynomial long division (recursive)
572 ex blcoeff = eb.coeff(*x, bdeg);
573 while (rdeg >= bdeg) {
574 ex term, rcoeff = r.coeff(*x, rdeg);
575 if (!divide_in_z(rcoeff, blcoeff, term, var+1))
577 term = (term * power(*x, rdeg - bdeg)).expand();
579 r -= (term * eb).expand();
582 dr_remember[ex2(a, b)] = exbool(q, true);
589 dr_remember[ex2(a, b)] = exbool(q, false);
595 // Trial division using polynomial interpolation
598 // Compute values at evaluation points 0..adeg
599 vector<numeric> alpha; alpha.reserve(adeg + 1);
600 exvector u; u.reserve(adeg + 1);
601 numeric point = numZERO();
603 for (i=0; i<=adeg; i++) {
604 ex bs = b.subs(*x == point);
605 while (bs.is_zero()) {
607 bs = b.subs(*x == point);
609 if (!divide_in_z(a.subs(*x == point), bs, c, var+1))
611 alpha.push_back(point);
617 vector<numeric> rcp; rcp.reserve(adeg + 1);
619 for (k=1; k<=adeg; k++) {
620 numeric product = alpha[k] - alpha[0];
622 product *= alpha[k] - alpha[i];
623 rcp.push_back(product.inverse());
626 // Compute Newton coefficients
627 exvector v; v.reserve(adeg + 1);
629 for (k=1; k<=adeg; k++) {
631 for (i=k-2; i>=0; i--)
632 temp = temp * (alpha[k] - alpha[i]) + v[i];
633 v.push_back((u[k] - temp) * rcp[k]);
636 // Convert from Newton form to standard form
638 for (k=adeg-1; k>=0; k--)
639 c = c * (*x - alpha[k]) + v[k];
641 if (c.degree(*x) == (adeg - bdeg)) {
651 * Separation of unit part, content part and primitive part of polynomials
654 /** Compute unit part (= sign of leading coefficient) of a multivariate
655 * polynomial in Z[x]. The product of unit part, content part, and primitive
656 * part is the polynomial itself.
658 * @param x variable in which to compute the unit part
660 * @see ex::content, ex::primpart */
661 ex ex::unit(const symbol &x) const
663 ex c = expand().lcoeff(x);
664 if (is_ex_exactly_of_type(c, numeric))
665 return c < exZERO() ? exMINUSONE() : exONE();
668 if (get_first_symbol(c, y))
671 throw(std::invalid_argument("invalid expression in unit()"));
676 /** Compute content part (= unit normal GCD of all coefficients) of a
677 * multivariate polynomial in Z[x]. The product of unit part, content part,
678 * and primitive part is the polynomial itself.
680 * @param x variable in which to compute the content part
681 * @return content part
682 * @see ex::unit, ex::primpart */
683 ex ex::content(const symbol &x) const
687 if (is_ex_exactly_of_type(*this, numeric))
688 return info(info_flags::negative) ? -*this : *this;
693 // First, try the integer content
694 ex c = e.integer_content();
696 ex lcoeff = r.lcoeff(x);
697 if (lcoeff.info(info_flags::integer))
700 // GCD of all coefficients
701 int deg = e.degree(x);
702 int ldeg = e.ldegree(x);
704 return e.lcoeff(x) / e.unit(x);
706 for (int i=ldeg; i<=deg; i++)
707 c = gcd(e.coeff(x, i), c, NULL, NULL, false);
712 /** Compute primitive part of a multivariate polynomial in Z[x].
713 * The product of unit part, content part, and primitive part is the
716 * @param x variable in which to compute the primitive part
717 * @return primitive part
718 * @see ex::unit, ex::content */
719 ex ex::primpart(const symbol &x) const
723 if (is_ex_exactly_of_type(*this, numeric))
730 if (is_ex_exactly_of_type(c, numeric))
731 return *this / (c * u);
733 return quo(*this, c * u, x, false);
737 /** Compute primitive part of a multivariate polynomial in Z[x] when the
738 * content part is already known. This function is faster in computing the
739 * primitive part than the previous function.
741 * @param x variable in which to compute the primitive part
742 * @param c previously computed content part
743 * @return primitive part */
745 ex ex::primpart(const symbol &x, const ex &c) const
751 if (is_ex_exactly_of_type(*this, numeric))
755 if (is_ex_exactly_of_type(c, numeric))
756 return *this / (c * u);
758 return quo(*this, c * u, x, false);
763 * GCD of multivariate polynomials
766 /** Compute GCD of multivariate polynomials using the subresultant PRS
767 * algorithm. This function is used internally gy gcd().
769 * @param a first multivariate polynomial
770 * @param b second multivariate polynomial
771 * @param x pointer to symbol (main variable) in which to compute the GCD in
772 * @return the GCD as a new expression
775 static ex sr_gcd(const ex &a, const ex &b, const symbol *x)
777 // Sort c and d so that c has higher degree
779 int adeg = a.degree(*x), bdeg = b.degree(*x);
793 // Remove content from c and d, to be attached to GCD later
794 ex cont_c = c.content(*x);
795 ex cont_d = d.content(*x);
796 ex gamma = gcd(cont_c, cont_d, NULL, NULL, false);
799 c = c.primpart(*x, cont_c);
800 d = d.primpart(*x, cont_d);
802 // First element of subresultant sequence
803 ex r = exZERO(), ri = exONE(), psi = exONE();
804 int delta = cdeg - ddeg;
807 // Calculate polynomial pseudo-remainder
808 r = prem(c, d, *x, false);
810 return gamma * d.primpart(*x);
813 if (!divide(r, ri * power(psi, delta), d, false))
814 throw(std::runtime_error("invalid expression in sr_gcd(), division failed"));
817 if (is_ex_exactly_of_type(r, numeric))
820 return gamma * r.primpart(*x);
823 // Next element of subresultant sequence
824 ri = c.expand().lcoeff(*x);
828 divide(power(ri, delta), power(psi, delta-1), psi, false);
834 /** Return maximum (absolute value) coefficient of a polynomial.
835 * This function is used internally by heur_gcd().
837 * @param e expanded multivariate polynomial
838 * @return maximum coefficient
841 numeric ex::max_coefficient(void) const
844 return bp->max_coefficient();
847 numeric basic::max_coefficient(void) const
852 numeric numeric::max_coefficient(void) const
857 numeric add::max_coefficient(void) const
859 epvector::const_iterator it = seq.begin();
860 epvector::const_iterator itend = seq.end();
861 ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
862 numeric cur_max = abs(ex_to_numeric(overall_coeff));
863 while (it != itend) {
865 ASSERT(!is_ex_exactly_of_type(it->rest,numeric));
866 a = abs(ex_to_numeric(it->coeff));
874 numeric mul::max_coefficient(void) const
877 epvector::const_iterator it = seq.begin();
878 epvector::const_iterator itend = seq.end();
879 while (it != itend) {
880 ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*it),numeric));
883 #endif // def DOASSERT
884 ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
885 return abs(ex_to_numeric(overall_coeff));
889 /** Apply symmetric modular homomorphism to a multivariate polynomial.
890 * This function is used internally by heur_gcd().
892 * @param e expanded multivariate polynomial
894 * @return mapped polynomial
897 ex ex::smod(const numeric &xi) const
903 ex basic::smod(const numeric &xi) const
908 ex numeric::smod(const numeric &xi) const
910 return ::smod(*this, xi);
913 ex add::smod(const numeric &xi) const
916 newseq.reserve(seq.size()+1);
917 epvector::const_iterator it = seq.begin();
918 epvector::const_iterator itend = seq.end();
919 while (it != itend) {
920 ASSERT(!is_ex_exactly_of_type(it->rest,numeric));
921 numeric coeff = ::smod(ex_to_numeric(it->coeff), xi);
922 if (!coeff.is_zero())
923 newseq.push_back(expair(it->rest, coeff));
926 ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
927 numeric coeff = ::smod(ex_to_numeric(overall_coeff), xi);
928 return (new add(newseq,coeff))->setflag(status_flags::dynallocated);
931 ex mul::smod(const numeric &xi) const
934 epvector::const_iterator it = seq.begin();
935 epvector::const_iterator itend = seq.end();
936 while (it != itend) {
937 ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*it),numeric));
940 #endif // def DOASSERT
941 mul * mulcopyp=new mul(*this);
942 ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
943 mulcopyp->overall_coeff=::smod(ex_to_numeric(overall_coeff),xi);
944 mulcopyp->clearflag(status_flags::evaluated);
945 mulcopyp->clearflag(status_flags::hash_calculated);
946 return mulcopyp->setflag(status_flags::dynallocated);
950 /** Exception thrown by heur_gcd() to signal failure */
951 class gcdheu_failed {};
953 /** Compute GCD of multivariate polynomials using the heuristic GCD algorithm.
954 * get_symbol_stats() must have been called previously with the input
955 * polynomials and an iterator to the first element of the sym_desc vector
956 * passed in. This function is used internally by gcd().
958 * @param a first multivariate polynomial (expanded)
959 * @param b second multivariate polynomial (expanded)
960 * @param ca cofactor of polynomial a (returned), NULL to suppress
961 * calculation of cofactor
962 * @param cb cofactor of polynomial b (returned), NULL to suppress
963 * calculation of cofactor
964 * @param var iterator to first element of vector of sym_desc structs
965 * @return the GCD as a new expression
967 * @exception gcdheu_failed() */
969 static ex heur_gcd(const ex &a, const ex &b, ex *ca, ex *cb, sym_desc_vec::const_iterator var)
971 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric)) {
972 numeric g = gcd(ex_to_numeric(a), ex_to_numeric(b));
977 *ca = ex_to_numeric(a).mul(rg);
979 *cb = ex_to_numeric(b).mul(rg);
983 // The first symbol is our main variable
984 const symbol *x = var->sym;
986 // Remove integer content
987 numeric gc = gcd(a.integer_content(), b.integer_content());
988 numeric rgc = gc.inverse();
991 int maxdeg = max(p.degree(*x), q.degree(*x));
993 // Find evaluation point
994 numeric mp = p.max_coefficient(), mq = q.max_coefficient();
997 xi = mq * numTWO() + numTWO();
999 xi = mp * numTWO() + numTWO();
1002 for (int t=0; t<6; t++) {
1003 if (xi.int_length() * maxdeg > 50000)
1004 throw gcdheu_failed();
1006 // Apply evaluation homomorphism and calculate GCD
1007 ex gamma = heur_gcd(p.subs(*x == xi), q.subs(*x == xi), NULL, NULL, var+1).expand();
1008 if (!is_ex_exactly_of_type(gamma, fail)) {
1010 // Reconstruct polynomial from GCD of mapped polynomials
1012 numeric rxi = xi.inverse();
1013 for (int i=0; !gamma.is_zero(); i++) {
1014 ex gi = gamma.smod(xi);
1015 g += gi * power(*x, i);
1016 gamma = (gamma - gi) * rxi;
1018 // Remove integer content
1019 g /= g.integer_content();
1021 // If the calculated polynomial divides both a and b, this is the GCD
1023 if (divide_in_z(p, g, ca ? *ca : dummy, var) && divide_in_z(q, g, cb ? *cb : dummy, var)) {
1025 ex lc = g.lcoeff(*x);
1026 if (is_ex_exactly_of_type(lc, numeric) && lc.compare(exZERO()) < 0)
1033 // Next evaluation point
1034 xi = iquo(xi * isqrt(isqrt(xi)) * numeric(73794), numeric(27011));
1036 return *new ex(fail());
1040 /** Compute GCD (Greatest Common Divisor) of multivariate polynomials a(X)
1043 * @param a first multivariate polynomial
1044 * @param b second multivariate polynomial
1045 * @param check_args check whether a and b are polynomials with rational
1046 * coefficients (defaults to "true")
1047 * @return the GCD as a new expression */
1049 ex gcd(const ex &a, const ex &b, ex *ca, ex *cb, bool check_args)
1051 // Some trivial cases
1066 if (a.is_equal(exONE()) || b.is_equal(exONE())) {
1074 if (a.is_equal(b)) {
1082 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric)) {
1083 numeric g = gcd(ex_to_numeric(a), ex_to_numeric(b));
1085 *ca = ex_to_numeric(a) / g;
1087 *cb = ex_to_numeric(b) / g;
1090 if (check_args && !a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)) {
1091 cerr << "a=" << a << endl;
1092 cerr << "b=" << b << endl;
1093 throw(std::invalid_argument("gcd: arguments must be polynomials over the rationals"));
1096 // Gather symbol statistics
1097 sym_desc_vec sym_stats;
1098 get_symbol_stats(a, b, sym_stats);
1100 // The symbol with least degree is our main variable
1101 sym_desc_vec::const_iterator var = sym_stats.begin();
1102 const symbol *x = var->sym;
1104 // Cancel trivial common factor
1105 int ldeg_a = var->ldeg_a;
1106 int ldeg_b = var->ldeg_b;
1107 int min_ldeg = min(ldeg_a, ldeg_b);
1109 ex common = power(*x, min_ldeg);
1110 //clog << "trivial common factor " << common << endl;
1111 return gcd((a / common).expand(), (b / common).expand(), ca, cb, false) * common;
1114 // Try to eliminate variables
1115 if (var->deg_a == 0) {
1116 //clog << "eliminating variable " << *x << " from b" << endl;
1117 ex c = b.content(*x);
1118 ex g = gcd(a, c, ca, cb, false);
1120 *cb *= b.unit(*x) * b.primpart(*x, c);
1122 } else if (var->deg_b == 0) {
1123 //clog << "eliminating variable " << *x << " from a" << endl;
1124 ex c = a.content(*x);
1125 ex g = gcd(c, b, ca, cb, false);
1127 *ca *= a.unit(*x) * a.primpart(*x, c);
1131 // Try heuristic algorithm first, fall back to PRS if that failed
1134 g = heur_gcd(a.expand(), b.expand(), ca, cb, var);
1135 } catch (gcdheu_failed) {
1136 g = *new ex(fail());
1138 if (is_ex_exactly_of_type(g, fail)) {
1139 //clog << "heuristics failed\n";
1140 g = sr_gcd(a, b, x);
1142 divide(a, g, *ca, false);
1144 divide(b, g, *cb, false);
1150 /** Compute LCM (Least Common Multiple) of multivariate polynomials in Z[X].
1152 * @param a first multivariate polynomial
1153 * @param b second multivariate polynomial
1154 * @param check_args check whether a and b are polynomials with rational
1155 * coefficients (defaults to "true")
1156 * @return the LCM as a new expression */
1157 ex lcm(const ex &a, const ex &b, bool check_args)
1159 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric))
1160 return gcd(ex_to_numeric(a), ex_to_numeric(b));
1161 if (check_args && !a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial))
1162 throw(std::invalid_argument("lcm: arguments must be polynomials over the rationals"));
1165 ex g = gcd(a, b, &ca, &cb, false);
1171 * Square-free factorization
1174 // Univariate GCD of polynomials in Q[x] (used internally by sqrfree()).
1175 // a and b can be multivariate polynomials but they are treated as univariate polynomials in x.
1176 static ex univariate_gcd(const ex &a, const ex &b, const symbol &x)
1182 if (a.is_equal(exONE()) || b.is_equal(exONE()))
1184 if (is_ex_of_type(a, numeric) && is_ex_of_type(b, numeric))
1185 return gcd(ex_to_numeric(a), ex_to_numeric(b));
1186 if (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial))
1187 throw(std::invalid_argument("univariate_gcd: arguments must be polynomials over the rationals"));
1189 // Euclidean algorithm
1191 if (a.degree(x) >= b.degree(x)) {
1199 r = rem(c, d, x, false);
1205 return d / d.lcoeff(x);
1209 /** Compute square-free factorization of multivariate polynomial a(x) using
1212 * @param a multivariate polynomial
1213 * @param x variable to factor in
1214 * @return factored polynomial */
1215 ex sqrfree(const ex &a, const symbol &x)
1220 ex c = univariate_gcd(a, b, x);
1222 if (c.is_equal(exONE())) {
1226 ex y = quo(b, c, x);
1227 ex z = y - w.diff(x);
1228 while (!z.is_zero()) {
1229 ex g = univariate_gcd(w, z, x);
1237 return res * power(w, i);
1242 * Normal form of rational functions
1245 // Create a symbol for replacing the expression "e" (or return a previously
1246 // assigned symbol). The symbol is appended to sym_list and returned, the
1247 // expression is appended to repl_list.
1248 static ex replace_with_symbol(const ex &e, lst &sym_lst, lst &repl_lst)
1250 // Expression already in repl_lst? Then return the assigned symbol
1251 for (int i=0; i<repl_lst.nops(); i++)
1252 if (repl_lst.op(i).is_equal(e))
1253 return sym_lst.op(i);
1255 // Otherwise create new symbol and add to list, taking care that the
1256 // replacement expression doesn't contain symbols from the sym_lst
1257 // because subs() is not recursive
1260 ex e_replaced = e.subs(sym_lst, repl_lst);
1262 repl_lst.append(e_replaced);
1267 /** Default implementation of ex::normal(). It replaces the object with a
1269 * @see ex::normal */
1270 ex basic::normal(lst &sym_lst, lst &repl_lst, int level) const
1272 return replace_with_symbol(*this, sym_lst, repl_lst);
1276 /** Implementation of ex::normal() for symbols. This returns the unmodifies symbol.
1277 * @see ex::normal */
1278 ex symbol::normal(lst &sym_lst, lst &repl_lst, int level) const
1284 /** Implementation of ex::normal() for a numeric. It splits complex numbers
1285 * into re+I*im and replaces I and non-rational real numbers with a temporary
1287 * @see ex::normal */
1288 ex numeric::normal(lst &sym_lst, lst &repl_lst, int level) const
1294 return replace_with_symbol(*this, sym_lst, repl_lst);
1296 numeric re = real(), im = imag();
1297 ex re_ex = re.is_rational() ? re : replace_with_symbol(re, sym_lst, repl_lst);
1298 ex im_ex = im.is_rational() ? im : replace_with_symbol(im, sym_lst, repl_lst);
1299 return re_ex + im_ex * replace_with_symbol(I, sym_lst, repl_lst);
1305 * Helper function for fraction cancellation (returns cancelled fraction n/d)
1308 static ex frac_cancel(const ex &n, const ex &d)
1312 ex pre_factor = exONE();
1314 // Handle special cases where numerator or denominator is 0
1317 if (den.expand().is_zero())
1318 throw(std::overflow_error("frac_cancel: division by zero in frac_cancel"));
1320 // More special cases
1321 if (is_ex_exactly_of_type(den, numeric))
1326 // Bring numerator and denominator to Z[X] by multiplying with
1327 // LCM of all coefficients' denominators
1328 ex num_lcm = lcm_of_coefficients_denominators(num);
1329 ex den_lcm = lcm_of_coefficients_denominators(den);
1332 pre_factor = den_lcm / num_lcm;
1334 // Cancel GCD from numerator and denominator
1336 if (gcd(num, den, &cnum, &cden, false) != exONE()) {
1341 // Make denominator unit normal (i.e. coefficient of first symbol
1342 // as defined by get_first_symbol() is made positive)
1344 if (get_first_symbol(den, x)) {
1345 if (den.unit(*x).compare(exZERO()) < 0) {
1346 num *= exMINUSONE();
1347 den *= exMINUSONE();
1350 return pre_factor * num / den;
1354 /** Implementation of ex::normal() for a sum. It expands terms and performs
1355 * fractional addition.
1356 * @see ex::normal */
1357 ex add::normal(lst &sym_lst, lst &repl_lst, int level) const
1359 // Normalize and expand children
1361 o.reserve(seq.size()+1);
1362 epvector::const_iterator it = seq.begin(), itend = seq.end();
1363 while (it != itend) {
1364 ex n = recombine_pair_to_ex(*it).bp->normal(sym_lst, repl_lst, level-1).expand();
1365 if (is_ex_exactly_of_type(n, add)) {
1366 epvector::const_iterator bit = (static_cast<add *>(n.bp))->seq.begin(), bitend = (static_cast<add *>(n.bp))->seq.end();
1367 while (bit != bitend) {
1368 o.push_back(recombine_pair_to_ex(*bit));
1371 o.push_back((static_cast<add *>(n.bp))->overall_coeff);
1376 o.push_back(overall_coeff.bp->normal(sym_lst, repl_lst, level-1));
1378 // Determine common denominator
1380 exvector::const_iterator ait = o.begin(), aitend = o.end();
1381 while (ait != aitend) {
1382 den = lcm((*ait).denom(false), den, false);
1387 if (den.is_equal(exONE()))
1388 return (new add(o))->setflag(status_flags::dynallocated);
1391 for (ait=o.begin(); ait!=aitend; ait++) {
1393 if (!divide(den, (*ait).denom(false), q, false)) {
1394 // should not happen
1395 throw(std::runtime_error("invalid expression in add::normal, division failed"));
1397 num_seq.push_back((*ait).numer(false) * q);
1399 ex num = add(num_seq);
1401 // Cancel common factors from num/den
1402 return frac_cancel(num, den);
1407 /** Implementation of ex::normal() for a product. It cancels common factors
1409 * @see ex::normal() */
1410 ex mul::normal(lst &sym_lst, lst &repl_lst, int level) const
1412 // Normalize children
1414 o.reserve(seq.size()+1);
1415 epvector::const_iterator it = seq.begin(), itend = seq.end();
1416 while (it != itend) {
1417 o.push_back(recombine_pair_to_ex(*it).bp->normal(sym_lst, repl_lst, level-1));
1420 o.push_back(overall_coeff.bp->normal(sym_lst, repl_lst, level-1));
1421 ex n = (new mul(o))->setflag(status_flags::dynallocated);
1422 return frac_cancel(n.numer(false), n.denom(false));
1426 /** Implementation of ex::normal() for powers. It normalizes the basis,
1427 * distributes integer exponents to numerator and denominator, and replaces
1428 * non-integer powers by temporary symbols.
1429 * @see ex::normal */
1430 ex power::normal(lst &sym_lst, lst &repl_lst, int level) const
1432 if (exponent.info(info_flags::integer)) {
1433 // Integer powers are distributed
1434 ex n = basis.bp->normal(sym_lst, repl_lst, level-1);
1435 ex num = n.numer(false);
1436 ex den = n.denom(false);
1437 return power(num, exponent) / power(den, exponent);
1439 // Non-integer powers are replaced by temporary symbol (after normalizing basis)
1440 ex n = power(basis.bp->normal(sym_lst, repl_lst, level-1), exponent);
1441 return replace_with_symbol(n, sym_lst, repl_lst);
1446 /** Implementation of ex::normal() for series. It normalizes each coefficient and
1447 * replaces the series by a temporary symbol.
1448 * @see ex::normal */
1449 ex series::normal(lst &sym_lst, lst &repl_lst, int level) const
1452 new_seq.reserve(seq.size());
1454 epvector::const_iterator it = seq.begin(), itend = seq.end();
1455 while (it != itend) {
1456 new_seq.push_back(expair(it->rest.normal(), it->coeff));
1460 ex n = series(var, point, new_seq);
1461 return replace_with_symbol(n, sym_lst, repl_lst);
1465 /** Normalization of rational functions.
1466 * This function converts an expression to its normal form
1467 * "numerator/denominator", where numerator and denominator are (relatively
1468 * prime) polynomials. Any subexpressions which are not rational functions
1469 * (like non-rational numbers, non-integer powers or functions like Sin(),
1470 * Cos() etc.) are replaced by temporary symbols which are re-substituted by
1471 * the (normalized) subexpressions before normal() returns (this way, any
1472 * expression can be treated as a rational function). normal() is applied
1473 * recursively to arguments of functions etc.
1475 * @param level maximum depth of recursion
1476 * @return normalized expression */
1477 ex ex::normal(int level) const
1479 lst sym_lst, repl_lst;
1480 ex e = bp->normal(sym_lst, repl_lst, level);
1481 if (sym_lst.nops() > 0)
1482 return e.subs(sym_lst, repl_lst);