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
30 // If comparing expressions (ex::compare()) is fast, you can set this to 1.
31 // Some routines like quo(), rem() and gcd() will then return a quick answer
32 // when they are called with two identical arguments.
33 #define FAST_COMPARE 1
35 // Set this if you want divide_in_z() to use remembering
36 #define USE_REMEMBER 1
39 /** Return pointer to first symbol found in expression. Due to GiNaCĀ“s
40 * internal ordering of terms, it may not be obvious which symbol this
41 * function returns for a given expression.
43 * @param e expression to search
44 * @param x pointer to first symbol found (returned)
45 * @return "false" if no symbol was found, "true" otherwise */
47 static bool get_first_symbol(const ex &e, const symbol *&x)
49 if (is_ex_exactly_of_type(e, symbol)) {
50 x = static_cast<symbol *>(e.bp);
52 } else if (is_ex_exactly_of_type(e, add) || is_ex_exactly_of_type(e, mul)) {
53 for (int i=0; i<e.nops(); i++)
54 if (get_first_symbol(e.op(i), x))
56 } else if (is_ex_exactly_of_type(e, power)) {
57 if (get_first_symbol(e.op(0), x))
65 * Statistical information about symbols in polynomials
70 /** This structure holds information about the highest and lowest degrees
71 * in which a symbol appears in two multivariate polynomials "a" and "b".
72 * A vector of these structures with information about all symbols in
73 * two polynomials can be created with the function get_symbol_stats().
75 * @see get_symbol_stats */
77 /** Pointer to symbol */
80 /** Highest degree of symbol in polynomial "a" */
83 /** Highest degree of symbol in polynomial "b" */
86 /** Lowest degree of symbol in polynomial "a" */
89 /** Lowest degree of symbol in polynomial "b" */
92 /** Minimum of ldeg_a and ldeg_b (Used for sorting) */
95 /** Commparison operator for sorting */
96 bool operator<(const sym_desc &x) const {return min_deg < x.min_deg;}
99 // Vector of sym_desc structures
100 typedef vector<sym_desc> sym_desc_vec;
102 // Add symbol the sym_desc_vec (used internally by get_symbol_stats())
103 static void add_symbol(const symbol *s, sym_desc_vec &v)
105 sym_desc_vec::iterator it = v.begin(), itend = v.end();
106 while (it != itend) {
107 if (it->sym->compare(*s) == 0) // If it's already in there, don't add it a second time
116 // Collect all symbols of an expression (used internally by get_symbol_stats())
117 static void collect_symbols(const ex &e, sym_desc_vec &v)
119 if (is_ex_exactly_of_type(e, symbol)) {
120 add_symbol(static_cast<symbol *>(e.bp), v);
121 } else if (is_ex_exactly_of_type(e, add) || is_ex_exactly_of_type(e, mul)) {
122 for (int i=0; i<e.nops(); i++)
123 collect_symbols(e.op(i), v);
124 } else if (is_ex_exactly_of_type(e, power)) {
125 collect_symbols(e.op(0), v);
129 /** Collect statistical information about symbols in polynomials.
130 * This function fills in a vector of "sym_desc" structs which contain
131 * information about the highest and lowest degrees of all symbols that
132 * appear in two polynomials. The vector is then sorted by minimum
133 * degree (lowest to highest). The information gathered by this
134 * function is used by the GCD routines to identify trivial factors
135 * and to determine which variable to choose as the main variable
136 * for GCD computation.
138 * @param a first multivariate polynomial
139 * @param b second multivariate polynomial
140 * @param v vector of sym_desc structs (filled in) */
142 static void get_symbol_stats(const ex &a, const ex &b, sym_desc_vec &v)
144 collect_symbols(a.eval(), v); // eval() to expand assigned symbols
145 collect_symbols(b.eval(), v);
146 sym_desc_vec::iterator it = v.begin(), itend = v.end();
147 while (it != itend) {
148 int deg_a = a.degree(*(it->sym));
149 int deg_b = b.degree(*(it->sym));
152 it->min_deg = min(deg_a, deg_b);
153 it->ldeg_a = a.ldegree(*(it->sym));
154 it->ldeg_b = b.ldegree(*(it->sym));
157 sort(v.begin(), v.end());
162 * Computation of LCM of denominators of coefficients of a polynomial
165 // Compute LCM of denominators of coefficients by going through the
166 // expression recursively (used internally by lcm_of_coefficients_denominators())
167 static numeric lcmcoeff(const ex &e, const numeric &l)
169 if (e.info(info_flags::rational))
170 return lcm(ex_to_numeric(e).denom(), l);
171 else if (is_ex_exactly_of_type(e, add) || is_ex_exactly_of_type(e, mul)) {
172 numeric c = numONE();
173 for (int i=0; i<e.nops(); i++) {
174 c = lcmcoeff(e.op(i), c);
177 } else if (is_ex_exactly_of_type(e, power))
178 return lcmcoeff(e.op(0), l);
182 /** Compute LCM of denominators of coefficients of a polynomial.
183 * Given a polynomial with rational coefficients, this function computes
184 * the LCM of the denominators of all coefficients. This can be used
185 * To bring a polynomial from Q[X] to Z[X].
187 * @param e multivariate polynomial
188 * @return LCM of denominators of coefficients */
190 static numeric lcm_of_coefficients_denominators(const ex &e)
192 return lcmcoeff(e.expand(), numONE());
196 /** Compute the integer content (= GCD of all numeric coefficients) of an
197 * expanded polynomial.
199 * @param e expanded polynomial
200 * @return integer content */
202 numeric ex::integer_content(void) const
205 return bp->integer_content();
208 numeric basic::integer_content(void) const
213 numeric numeric::integer_content(void) const
218 numeric add::integer_content(void) const
220 epvector::const_iterator it = seq.begin();
221 epvector::const_iterator itend = seq.end();
222 numeric c = numZERO();
223 while (it != itend) {
224 ASSERT(!is_ex_exactly_of_type(it->rest,numeric));
225 ASSERT(is_ex_exactly_of_type(it->coeff,numeric));
226 c = gcd(ex_to_numeric(it->coeff), c);
229 ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
230 c = gcd(ex_to_numeric(overall_coeff),c);
234 numeric mul::integer_content(void) const
237 epvector::const_iterator it = seq.begin();
238 epvector::const_iterator itend = seq.end();
239 while (it != itend) {
240 ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*it),numeric));
243 #endif // def DOASSERT
244 ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
245 return abs(ex_to_numeric(overall_coeff));
250 * Polynomial quotients and remainders
253 /** Quotient q(x) of polynomials a(x) and b(x) in Q[x].
254 * It satisfies a(x)=b(x)*q(x)+r(x).
256 * @param a first polynomial in x (dividend)
257 * @param b second polynomial in x (divisor)
258 * @param x a and b are polynomials in x
259 * @param check_args check whether a and b are polynomials with rational
260 * coefficients (defaults to "true")
261 * @return quotient of a and b in Q[x] */
263 ex quo(const ex &a, const ex &b, const symbol &x, bool check_args)
266 throw(std::overflow_error("quo: division by zero"));
267 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric))
273 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
274 throw(std::invalid_argument("quo: arguments must be polynomials over the rationals"));
276 // Polynomial long division
281 int bdeg = b.degree(x);
282 int rdeg = r.degree(x);
283 ex blcoeff = b.expand().coeff(x, bdeg);
284 bool blcoeff_is_numeric = is_ex_exactly_of_type(blcoeff, numeric);
285 while (rdeg >= bdeg) {
286 ex term, rcoeff = r.coeff(x, rdeg);
287 if (blcoeff_is_numeric)
288 term = rcoeff / blcoeff;
290 if (!divide(rcoeff, blcoeff, term, false))
291 return *new ex(fail());
293 term *= power(x, rdeg - bdeg);
295 r -= (term * b).expand();
304 /** Remainder r(x) of polynomials a(x) and b(x) in Q[x].
305 * It satisfies a(x)=b(x)*q(x)+r(x).
307 * @param a first polynomial in x (dividend)
308 * @param b second polynomial in x (divisor)
309 * @param x a and b are polynomials in x
310 * @param check_args check whether a and b are polynomials with rational
311 * coefficients (defaults to "true")
312 * @return remainder of a(x) and b(x) in Q[x] */
314 ex rem(const ex &a, const ex &b, const symbol &x, bool check_args)
317 throw(std::overflow_error("rem: division by zero"));
318 if (is_ex_exactly_of_type(a, numeric)) {
319 if (is_ex_exactly_of_type(b, numeric))
328 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
329 throw(std::invalid_argument("rem: arguments must be polynomials over the rationals"));
331 // Polynomial long division
335 int bdeg = b.degree(x);
336 int rdeg = r.degree(x);
337 ex blcoeff = b.expand().coeff(x, bdeg);
338 bool blcoeff_is_numeric = is_ex_exactly_of_type(blcoeff, numeric);
339 while (rdeg >= bdeg) {
340 ex term, rcoeff = r.coeff(x, rdeg);
341 if (blcoeff_is_numeric)
342 term = rcoeff / blcoeff;
344 if (!divide(rcoeff, blcoeff, term, false))
345 return *new ex(fail());
347 term *= power(x, rdeg - bdeg);
348 r -= (term * b).expand();
357 /** Pseudo-remainder of polynomials a(x) and b(x) in Z[x].
359 * @param a first polynomial in x (dividend)
360 * @param b second polynomial in x (divisor)
361 * @param x a and b are polynomials in x
362 * @param check_args check whether a and b are polynomials with rational
363 * coefficients (defaults to "true")
364 * @return pseudo-remainder of a(x) and b(x) in Z[x] */
366 ex prem(const ex &a, const ex &b, const symbol &x, bool check_args)
369 throw(std::overflow_error("prem: division by zero"));
370 if (is_ex_exactly_of_type(a, numeric)) {
371 if (is_ex_exactly_of_type(b, numeric))
376 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
377 throw(std::invalid_argument("prem: arguments must be polynomials over the rationals"));
379 // Polynomial long division
382 int rdeg = r.degree(x);
383 int bdeg = eb.degree(x);
386 blcoeff = eb.coeff(x, bdeg);
390 eb -= blcoeff * power(x, bdeg);
394 int delta = rdeg - bdeg + 1, i = 0;
395 while (rdeg >= bdeg && !r.is_zero()) {
396 ex rlcoeff = r.coeff(x, rdeg);
397 ex term = (power(x, rdeg - bdeg) * eb * rlcoeff).expand();
401 r -= rlcoeff * power(x, rdeg);
402 r = (blcoeff * r).expand() - term;
406 return power(blcoeff, delta - i) * r;
410 /** Exact polynomial division of a(X) by b(X) in Q[X].
412 * @param a first multivariate polynomial (dividend)
413 * @param b second multivariate polynomial (divisor)
414 * @param q quotient (returned)
415 * @param check_args check whether a and b are polynomials with rational
416 * coefficients (defaults to "true")
417 * @return "true" when exact division succeeds (quotient returned in q),
418 * "false" otherwise */
420 bool divide(const ex &a, const ex &b, ex &q, bool check_args)
424 throw(std::overflow_error("divide: division by zero"));
425 if (is_ex_exactly_of_type(b, numeric)) {
428 } else if (is_ex_exactly_of_type(a, numeric))
436 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
437 throw(std::invalid_argument("divide: arguments must be polynomials over the rationals"));
441 if (!get_first_symbol(a, x) && !get_first_symbol(b, x))
442 throw(std::invalid_argument("invalid expression in divide()"));
444 // Polynomial long division (recursive)
448 int bdeg = b.degree(*x);
449 int rdeg = r.degree(*x);
450 ex blcoeff = b.expand().coeff(*x, bdeg);
451 bool blcoeff_is_numeric = is_ex_exactly_of_type(blcoeff, numeric);
452 while (rdeg >= bdeg) {
453 ex term, rcoeff = r.coeff(*x, rdeg);
454 if (blcoeff_is_numeric)
455 term = rcoeff / blcoeff;
457 if (!divide(rcoeff, blcoeff, term, false))
459 term *= power(*x, rdeg - bdeg);
461 r -= (term * b).expand();
477 typedef pair<ex, ex> ex2;
478 typedef pair<ex, bool> exbool;
481 bool operator() (const ex2 p, const ex2 q) const
483 return p.first.compare(q.first) < 0 || (!(q.first.compare(p.first) < 0) && p.second.compare(q.second) < 0);
487 typedef map<ex2, exbool, ex2_less> ex2_exbool_remember;
491 /** Exact polynomial division of a(X) by b(X) in Z[X].
492 * This functions works like divide() but the input and output polynomials are
493 * in Z[X] instead of Q[X] (i.e. they have integer coefficients). Unlike
494 * divide(), it doesnĀ“t check whether the input polynomials really are integer
495 * polynomials, so be careful of what you pass in. Also, you have to run
496 * get_symbol_stats() over the input polynomials before calling this function
497 * and pass an iterator to the first element of the sym_desc vector. This
498 * function is used internally by the heur_gcd().
500 * @param a first multivariate polynomial (dividend)
501 * @param b second multivariate polynomial (divisor)
502 * @param q quotient (returned)
503 * @param var iterator to first element of vector of sym_desc structs
504 * @return "true" when exact division succeeds (the quotient is returned in
505 * q), "false" otherwise.
506 * @see get_symbol_stats, heur_gcd */
507 static bool divide_in_z(const ex &a, const ex &b, ex &q, sym_desc_vec::const_iterator var)
511 throw(std::overflow_error("divide_in_z: division by zero"));
512 if (b.is_equal(exONE())) {
516 if (is_ex_exactly_of_type(a, numeric)) {
517 if (is_ex_exactly_of_type(b, numeric)) {
519 return q.info(info_flags::integer);
532 static ex2_exbool_remember dr_remember;
533 ex2_exbool_remember::const_iterator remembered = dr_remember.find(ex2(a, b));
534 if (remembered != dr_remember.end()) {
535 q = remembered->second.first;
536 return remembered->second.second;
541 const symbol *x = var->sym;
544 int adeg = a.degree(*x), bdeg = b.degree(*x);
550 // Polynomial long division (recursive)
556 ex blcoeff = eb.coeff(*x, bdeg);
557 while (rdeg >= bdeg) {
558 ex term, rcoeff = r.coeff(*x, rdeg);
559 if (!divide_in_z(rcoeff, blcoeff, term, var+1))
561 term = (term * power(*x, rdeg - bdeg)).expand();
563 r -= (term * eb).expand();
566 dr_remember[ex2(a, b)] = exbool(q, true);
573 dr_remember[ex2(a, b)] = exbool(q, false);
579 // Trial division using polynomial interpolation
582 // Compute values at evaluation points 0..adeg
583 vector<numeric> alpha; alpha.reserve(adeg + 1);
584 exvector u; u.reserve(adeg + 1);
585 numeric point = numZERO();
587 for (i=0; i<=adeg; i++) {
588 ex bs = b.subs(*x == point);
589 while (bs.is_zero()) {
591 bs = b.subs(*x == point);
593 if (!divide_in_z(a.subs(*x == point), bs, c, var+1))
595 alpha.push_back(point);
601 vector<numeric> rcp; rcp.reserve(adeg + 1);
603 for (k=1; k<=adeg; k++) {
604 numeric product = alpha[k] - alpha[0];
606 product *= alpha[k] - alpha[i];
607 rcp.push_back(product.inverse());
610 // Compute Newton coefficients
611 exvector v; v.reserve(adeg + 1);
613 for (k=1; k<=adeg; k++) {
615 for (i=k-2; i>=0; i--)
616 temp = temp * (alpha[k] - alpha[i]) + v[i];
617 v.push_back((u[k] - temp) * rcp[k]);
620 // Convert from Newton form to standard form
622 for (k=adeg-1; k>=0; k--)
623 c = c * (*x - alpha[k]) + v[k];
625 if (c.degree(*x) == (adeg - bdeg)) {
635 * Separation of unit part, content part and primitive part of polynomials
638 /** Compute unit part (= sign of leading coefficient) of a multivariate
639 * polynomial in Z[x]. The product of unit part, content part, and primitive
640 * part is the polynomial itself.
642 * @param x variable in which to compute the unit part
644 * @see ex::content, ex::primpart */
645 ex ex::unit(const symbol &x) const
647 ex c = expand().lcoeff(x);
648 if (is_ex_exactly_of_type(c, numeric))
649 return c < exZERO() ? exMINUSONE() : exONE();
652 if (get_first_symbol(c, y))
655 throw(std::invalid_argument("invalid expression in unit()"));
660 /** Compute content part (= unit normal GCD of all coefficients) of a
661 * multivariate polynomial in Z[x]. The product of unit part, content part,
662 * and primitive part is the polynomial itself.
664 * @param x variable in which to compute the content part
665 * @return content part
666 * @see ex::unit, ex::primpart */
667 ex ex::content(const symbol &x) const
671 if (is_ex_exactly_of_type(*this, numeric))
672 return info(info_flags::negative) ? -*this : *this;
677 // First, try the integer content
678 ex c = e.integer_content();
680 ex lcoeff = r.lcoeff(x);
681 if (lcoeff.info(info_flags::integer))
684 // GCD of all coefficients
685 int deg = e.degree(x);
686 int ldeg = e.ldegree(x);
688 return e.lcoeff(x) / e.unit(x);
690 for (int i=ldeg; i<=deg; i++)
691 c = gcd(e.coeff(x, i), c, NULL, NULL, false);
696 /** Compute primitive part of a multivariate polynomial in Z[x].
697 * The product of unit part, content part, and primitive part is the
700 * @param x variable in which to compute the primitive part
701 * @return primitive part
702 * @see ex::unit, ex::content */
703 ex ex::primpart(const symbol &x) const
707 if (is_ex_exactly_of_type(*this, numeric))
714 if (is_ex_exactly_of_type(c, numeric))
715 return *this / (c * u);
717 return quo(*this, c * u, x, false);
721 /** Compute primitive part of a multivariate polynomial in Z[x] when the
722 * content part is already known. This function is faster in computing the
723 * primitive part than the previous function.
725 * @param x variable in which to compute the primitive part
726 * @param c previously computed content part
727 * @return primitive part */
729 ex ex::primpart(const symbol &x, const ex &c) const
735 if (is_ex_exactly_of_type(*this, numeric))
739 if (is_ex_exactly_of_type(c, numeric))
740 return *this / (c * u);
742 return quo(*this, c * u, x, false);
747 * GCD of multivariate polynomials
750 /** Compute GCD of multivariate polynomials using the subresultant PRS
751 * algorithm. This function is used internally gy gcd().
753 * @param a first multivariate polynomial
754 * @param b second multivariate polynomial
755 * @param x pointer to symbol (main variable) in which to compute the GCD in
756 * @return the GCD as a new expression
759 static ex sr_gcd(const ex &a, const ex &b, const symbol *x)
761 // Sort c and d so that c has higher degree
763 int adeg = a.degree(*x), bdeg = b.degree(*x);
777 // Remove content from c and d, to be attached to GCD later
778 ex cont_c = c.content(*x);
779 ex cont_d = d.content(*x);
780 ex gamma = gcd(cont_c, cont_d, NULL, NULL, false);
783 c = c.primpart(*x, cont_c);
784 d = d.primpart(*x, cont_d);
786 // First element of subresultant sequence
787 ex r = exZERO(), ri = exONE(), psi = exONE();
788 int delta = cdeg - ddeg;
791 // Calculate polynomial pseudo-remainder
792 r = prem(c, d, *x, false);
794 return gamma * d.primpart(*x);
797 if (!divide(r, ri * power(psi, delta), d, false))
798 throw(std::runtime_error("invalid expression in sr_gcd(), division failed"));
801 if (is_ex_exactly_of_type(r, numeric))
804 return gamma * r.primpart(*x);
807 // Next element of subresultant sequence
808 ri = c.expand().lcoeff(*x);
812 divide(power(ri, delta), power(psi, delta-1), psi, false);
818 /** Return maximum (absolute value) coefficient of a polynomial.
819 * This function is used internally by heur_gcd().
821 * @param e expanded multivariate polynomial
822 * @return maximum coefficient
825 numeric ex::max_coefficient(void) const
828 return bp->max_coefficient();
831 numeric basic::max_coefficient(void) const
836 numeric numeric::max_coefficient(void) const
841 numeric add::max_coefficient(void) const
843 epvector::const_iterator it = seq.begin();
844 epvector::const_iterator itend = seq.end();
845 ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
846 numeric cur_max = abs(ex_to_numeric(overall_coeff));
847 while (it != itend) {
849 ASSERT(!is_ex_exactly_of_type(it->rest,numeric));
850 a = abs(ex_to_numeric(it->coeff));
858 numeric mul::max_coefficient(void) const
861 epvector::const_iterator it = seq.begin();
862 epvector::const_iterator itend = seq.end();
863 while (it != itend) {
864 ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*it),numeric));
867 #endif // def DOASSERT
868 ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
869 return abs(ex_to_numeric(overall_coeff));
873 /** Apply symmetric modular homomorphism to a multivariate polynomial.
874 * This function is used internally by heur_gcd().
876 * @param e expanded multivariate polynomial
878 * @return mapped polynomial
881 ex ex::smod(const numeric &xi) const
887 ex basic::smod(const numeric &xi) const
892 ex numeric::smod(const numeric &xi) const
894 return ::smod(*this, xi);
897 ex add::smod(const numeric &xi) const
900 newseq.reserve(seq.size()+1);
901 epvector::const_iterator it = seq.begin();
902 epvector::const_iterator itend = seq.end();
903 while (it != itend) {
904 ASSERT(!is_ex_exactly_of_type(it->rest,numeric));
905 numeric coeff = ::smod(ex_to_numeric(it->coeff), xi);
906 if (!coeff.is_zero())
907 newseq.push_back(expair(it->rest, coeff));
910 ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
911 numeric coeff = ::smod(ex_to_numeric(overall_coeff), xi);
912 return (new add(newseq,coeff))->setflag(status_flags::dynallocated);
915 ex mul::smod(const numeric &xi) const
918 epvector::const_iterator it = seq.begin();
919 epvector::const_iterator itend = seq.end();
920 while (it != itend) {
921 ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*it),numeric));
924 #endif // def DOASSERT
925 mul * mulcopyp=new mul(*this);
926 ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
927 mulcopyp->overall_coeff=::smod(ex_to_numeric(overall_coeff),xi);
928 mulcopyp->clearflag(status_flags::evaluated);
929 mulcopyp->clearflag(status_flags::hash_calculated);
930 return mulcopyp->setflag(status_flags::dynallocated);
934 /** Exception thrown by heur_gcd() to signal failure */
935 class gcdheu_failed {};
937 /** Compute GCD of multivariate polynomials using the heuristic GCD algorithm.
938 * get_symbol_stats() must have been called previously with the input
939 * polynomials and an iterator to the first element of the sym_desc vector
940 * passed in. This function is used internally by gcd().
942 * @param a first multivariate polynomial (expanded)
943 * @param b second multivariate polynomial (expanded)
944 * @param ca cofactor of polynomial a (returned), NULL to suppress
945 * calculation of cofactor
946 * @param cb cofactor of polynomial b (returned), NULL to suppress
947 * calculation of cofactor
948 * @param var iterator to first element of vector of sym_desc structs
949 * @return the GCD as a new expression
951 * @exception gcdheu_failed() */
953 static ex heur_gcd(const ex &a, const ex &b, ex *ca, ex *cb, sym_desc_vec::const_iterator var)
955 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric)) {
956 numeric g = gcd(ex_to_numeric(a), ex_to_numeric(b));
961 *ca = ex_to_numeric(a).mul(rg);
963 *cb = ex_to_numeric(b).mul(rg);
967 // The first symbol is our main variable
968 const symbol *x = var->sym;
970 // Remove integer content
971 numeric gc = gcd(a.integer_content(), b.integer_content());
972 numeric rgc = gc.inverse();
975 int maxdeg = max(p.degree(*x), q.degree(*x));
977 // Find evaluation point
978 numeric mp = p.max_coefficient(), mq = q.max_coefficient();
981 xi = mq * numTWO() + numTWO();
983 xi = mp * numTWO() + numTWO();
986 for (int t=0; t<6; t++) {
987 if (xi.int_length() * maxdeg > 50000)
988 throw gcdheu_failed();
990 // Apply evaluation homomorphism and calculate GCD
991 ex gamma = heur_gcd(p.subs(*x == xi), q.subs(*x == xi), NULL, NULL, var+1).expand();
992 if (!is_ex_exactly_of_type(gamma, fail)) {
994 // Reconstruct polynomial from GCD of mapped polynomials
996 numeric rxi = xi.inverse();
997 for (int i=0; !gamma.is_zero(); i++) {
998 ex gi = gamma.smod(xi);
999 g += gi * power(*x, i);
1000 gamma = (gamma - gi) * rxi;
1002 // Remove integer content
1003 g /= g.integer_content();
1005 // If the calculated polynomial divides both a and b, this is the GCD
1007 if (divide_in_z(p, g, ca ? *ca : dummy, var) && divide_in_z(q, g, cb ? *cb : dummy, var)) {
1009 ex lc = g.lcoeff(*x);
1010 if (is_ex_exactly_of_type(lc, numeric) && lc.compare(exZERO()) < 0)
1017 // Next evaluation point
1018 xi = iquo(xi * isqrt(isqrt(xi)) * numeric(73794), numeric(27011));
1020 return *new ex(fail());
1024 /** Compute GCD (Greatest Common Divisor) of multivariate polynomials a(X)
1027 * @param a first multivariate polynomial
1028 * @param b second multivariate polynomial
1029 * @param check_args check whether a and b are polynomials with rational
1030 * coefficients (defaults to "true")
1031 * @return the GCD as a new expression */
1033 ex gcd(const ex &a, const ex &b, ex *ca, ex *cb, bool check_args)
1035 // Some trivial cases
1050 if (a.is_equal(exONE()) || b.is_equal(exONE())) {
1058 if (a.is_equal(b)) {
1066 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric)) {
1067 numeric g = gcd(ex_to_numeric(a), ex_to_numeric(b));
1069 *ca = ex_to_numeric(a) / g;
1071 *cb = ex_to_numeric(b) / g;
1074 if (check_args && !a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)) {
1075 cerr << "a=" << a << endl;
1076 cerr << "b=" << b << endl;
1077 throw(std::invalid_argument("gcd: arguments must be polynomials over the rationals"));
1080 // Gather symbol statistics
1081 sym_desc_vec sym_stats;
1082 get_symbol_stats(a, b, sym_stats);
1084 // The symbol with least degree is our main variable
1085 sym_desc_vec::const_iterator var = sym_stats.begin();
1086 const symbol *x = var->sym;
1088 // Cancel trivial common factor
1089 int ldeg_a = var->ldeg_a;
1090 int ldeg_b = var->ldeg_b;
1091 int min_ldeg = min(ldeg_a, ldeg_b);
1093 ex common = power(*x, min_ldeg);
1094 //clog << "trivial common factor " << common << endl;
1095 return gcd((a / common).expand(), (b / common).expand(), ca, cb, false) * common;
1098 // Try to eliminate variables
1099 if (var->deg_a == 0) {
1100 //clog << "eliminating variable " << *x << " from b" << endl;
1101 ex c = b.content(*x);
1102 ex g = gcd(a, c, ca, cb, false);
1104 *cb *= b.unit(*x) * b.primpart(*x, c);
1106 } else if (var->deg_b == 0) {
1107 //clog << "eliminating variable " << *x << " from a" << endl;
1108 ex c = a.content(*x);
1109 ex g = gcd(c, b, ca, cb, false);
1111 *ca *= a.unit(*x) * a.primpart(*x, c);
1115 // Try heuristic algorithm first, fall back to PRS if that failed
1118 g = heur_gcd(a.expand(), b.expand(), ca, cb, var);
1119 } catch (gcdheu_failed) {
1120 g = *new ex(fail());
1122 if (is_ex_exactly_of_type(g, fail)) {
1123 //clog << "heuristics failed\n";
1124 g = sr_gcd(a, b, x);
1126 divide(a, g, *ca, false);
1128 divide(b, g, *cb, false);
1134 /** Compute LCM (Least Common Multiple) of multivariate polynomials in Z[X].
1136 * @param a first multivariate polynomial
1137 * @param b second multivariate polynomial
1138 * @param check_args check whether a and b are polynomials with rational
1139 * coefficients (defaults to "true")
1140 * @return the LCM as a new expression */
1141 ex lcm(const ex &a, const ex &b, bool check_args)
1143 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric))
1144 return gcd(ex_to_numeric(a), ex_to_numeric(b));
1145 if (check_args && !a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial))
1146 throw(std::invalid_argument("lcm: arguments must be polynomials over the rationals"));
1149 ex g = gcd(a, b, &ca, &cb, false);
1155 * Square-free factorization
1158 // Univariate GCD of polynomials in Q[x] (used internally by sqrfree()).
1159 // a and b can be multivariate polynomials but they are treated as univariate polynomials in x.
1160 static ex univariate_gcd(const ex &a, const ex &b, const symbol &x)
1166 if (a.is_equal(exONE()) || b.is_equal(exONE()))
1168 if (is_ex_of_type(a, numeric) && is_ex_of_type(b, numeric))
1169 return gcd(ex_to_numeric(a), ex_to_numeric(b));
1170 if (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial))
1171 throw(std::invalid_argument("univariate_gcd: arguments must be polynomials over the rationals"));
1173 // Euclidean algorithm
1175 if (a.degree(x) >= b.degree(x)) {
1183 r = rem(c, d, x, false);
1189 return d / d.lcoeff(x);
1193 /** Compute square-free factorization of multivariate polynomial a(x) using
1196 * @param a multivariate polynomial
1197 * @param x variable to factor in
1198 * @return factored polynomial */
1199 ex sqrfree(const ex &a, const symbol &x)
1204 ex c = univariate_gcd(a, b, x);
1206 if (c.is_equal(exONE())) {
1210 ex y = quo(b, c, x);
1211 ex z = y - w.diff(x);
1212 while (!z.is_zero()) {
1213 ex g = univariate_gcd(w, z, x);
1221 return res * power(w, i);
1226 * Normal form of rational functions
1229 // Create a symbol for replacing the expression "e" (or return a previously
1230 // assigned symbol). The symbol is appended to sym_list and returned, the
1231 // expression is appended to repl_list.
1232 static ex replace_with_symbol(const ex &e, lst &sym_lst, lst &repl_lst)
1234 // Expression already in repl_lst? Then return the assigned symbol
1235 for (int i=0; i<repl_lst.nops(); i++)
1236 if (repl_lst.op(i).is_equal(e))
1237 return sym_lst.op(i);
1239 // Otherwise create new symbol and add to list, taking care that the
1240 // replacement expression doesn't contain symbols from the sym_lst
1241 // because subs() is not recursive
1244 ex e_replaced = e.subs(sym_lst, repl_lst);
1246 repl_lst.append(e_replaced);
1251 /** Default implementation of ex::normal(). It replaces the object with a
1253 * @see ex::normal */
1254 ex basic::normal(lst &sym_lst, lst &repl_lst, int level) const
1256 return replace_with_symbol(*this, sym_lst, repl_lst);
1260 /** Implementation of ex::normal() for symbols. This returns the unmodifies symbol.
1261 * @see ex::normal */
1262 ex symbol::normal(lst &sym_lst, lst &repl_lst, int level) const
1268 /** Implementation of ex::normal() for a numeric. It splits complex numbers
1269 * into re+I*im and replaces I and non-rational real numbers with a temporary
1271 * @see ex::normal */
1272 ex numeric::normal(lst &sym_lst, lst &repl_lst, int level) const
1278 return replace_with_symbol(*this, sym_lst, repl_lst);
1280 numeric re = real(), im = imag();
1281 ex re_ex = re.is_rational() ? re : replace_with_symbol(re, sym_lst, repl_lst);
1282 ex im_ex = im.is_rational() ? im : replace_with_symbol(im, sym_lst, repl_lst);
1283 return re_ex + im_ex * replace_with_symbol(I, sym_lst, repl_lst);
1289 * Helper function for fraction cancellation (returns cancelled fraction n/d)
1292 static ex frac_cancel(const ex &n, const ex &d)
1296 ex pre_factor = exONE();
1298 // Handle special cases where numerator or denominator is 0
1301 if (den.expand().is_zero())
1302 throw(std::overflow_error("frac_cancel: division by zero in frac_cancel"));
1304 // More special cases
1305 if (is_ex_exactly_of_type(den, numeric))
1310 // Bring numerator and denominator to Z[X] by multiplying with
1311 // LCM of all coefficients' denominators
1312 ex num_lcm = lcm_of_coefficients_denominators(num);
1313 ex den_lcm = lcm_of_coefficients_denominators(den);
1316 pre_factor = den_lcm / num_lcm;
1318 // Cancel GCD from numerator and denominator
1320 if (gcd(num, den, &cnum, &cden, false) != exONE()) {
1325 // Make denominator unit normal (i.e. coefficient of first symbol
1326 // as defined by get_first_symbol() is made positive)
1328 if (get_first_symbol(den, x)) {
1329 if (den.unit(*x).compare(exZERO()) < 0) {
1330 num *= exMINUSONE();
1331 den *= exMINUSONE();
1334 return pre_factor * num / den;
1338 /** Implementation of ex::normal() for a sum. It expands terms and performs
1339 * fractional addition.
1340 * @see ex::normal */
1341 ex add::normal(lst &sym_lst, lst &repl_lst, int level) const
1343 // Normalize and expand children
1345 o.reserve(seq.size()+1);
1346 epvector::const_iterator it = seq.begin(), itend = seq.end();
1347 while (it != itend) {
1348 ex n = recombine_pair_to_ex(*it).bp->normal(sym_lst, repl_lst, level-1).expand();
1349 if (is_ex_exactly_of_type(n, add)) {
1350 epvector::const_iterator bit = (static_cast<add *>(n.bp))->seq.begin(), bitend = (static_cast<add *>(n.bp))->seq.end();
1351 while (bit != bitend) {
1352 o.push_back(recombine_pair_to_ex(*bit));
1355 o.push_back((static_cast<add *>(n.bp))->overall_coeff);
1360 o.push_back(overall_coeff.bp->normal(sym_lst, repl_lst, level-1));
1362 // Determine common denominator
1364 exvector::const_iterator ait = o.begin(), aitend = o.end();
1365 while (ait != aitend) {
1366 den = lcm((*ait).denom(false), den, false);
1371 if (den.is_equal(exONE()))
1372 return (new add(o))->setflag(status_flags::dynallocated);
1375 for (ait=o.begin(); ait!=aitend; ait++) {
1377 if (!divide(den, (*ait).denom(false), q, false)) {
1378 // should not happen
1379 throw(std::runtime_error("invalid expression in add::normal, division failed"));
1381 num_seq.push_back((*ait).numer(false) * q);
1383 ex num = add(num_seq);
1385 // Cancel common factors from num/den
1386 return frac_cancel(num, den);
1391 /** Implementation of ex::normal() for a product. It cancels common factors
1393 * @see ex::normal() */
1394 ex mul::normal(lst &sym_lst, lst &repl_lst, int level) const
1396 // Normalize children
1398 o.reserve(seq.size()+1);
1399 epvector::const_iterator it = seq.begin(), itend = seq.end();
1400 while (it != itend) {
1401 o.push_back(recombine_pair_to_ex(*it).bp->normal(sym_lst, repl_lst, level-1));
1404 o.push_back(overall_coeff.bp->normal(sym_lst, repl_lst, level-1));
1405 ex n = (new mul(o))->setflag(status_flags::dynallocated);
1406 return frac_cancel(n.numer(false), n.denom(false));
1410 /** Implementation of ex::normal() for powers. It normalizes the basis,
1411 * distributes integer exponents to numerator and denominator, and replaces
1412 * non-integer powers by temporary symbols.
1413 * @see ex::normal */
1414 ex power::normal(lst &sym_lst, lst &repl_lst, int level) const
1416 if (exponent.info(info_flags::integer)) {
1417 // Integer powers are distributed
1418 ex n = basis.bp->normal(sym_lst, repl_lst, level-1);
1419 ex num = n.numer(false);
1420 ex den = n.denom(false);
1421 return power(num, exponent) / power(den, exponent);
1423 // Non-integer powers are replaced by temporary symbol (after normalizing basis)
1424 ex n = power(basis.bp->normal(sym_lst, repl_lst, level-1), exponent);
1425 return replace_with_symbol(n, sym_lst, repl_lst);
1430 /** Implementation of ex::normal() for series. It normalizes each coefficient and
1431 * replaces the series by a temporary symbol.
1432 * @see ex::normal */
1433 ex series::normal(lst &sym_lst, lst &repl_lst, int level) const
1436 new_seq.reserve(seq.size());
1438 epvector::const_iterator it = seq.begin(), itend = seq.end();
1439 while (it != itend) {
1440 new_seq.push_back(expair(it->rest.normal(), it->coeff));
1444 ex n = series(var, point, new_seq);
1445 return replace_with_symbol(n, sym_lst, repl_lst);
1449 /** Normalization of rational functions.
1450 * This function converts an expression to its normal form
1451 * "numerator/denominator", where numerator and denominator are (relatively
1452 * prime) polynomials. Any subexpressions which are not rational functions
1453 * (like non-rational numbers, non-integer powers or functions like Sin(),
1454 * Cos() etc.) are replaced by temporary symbols which are re-substituted by
1455 * the (normalized) subexpressions before normal() returns (this way, any
1456 * expression can be treated as a rational function). normal() is applied
1457 * recursively to arguments of functions etc.
1459 * @param level maximum depth of recursion
1460 * @return normalized expression */
1461 ex ex::normal(int level) const
1463 lst sym_lst, repl_lst;
1464 ex e = bp->normal(sym_lst, repl_lst, level);
1465 if (sym_lst.nops() > 0)
1466 return e.subs(sym_lst, repl_lst);