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.
10 * GiNaC Copyright (C) 1999 Johannes Gutenberg University Mainz, Germany
12 * This program is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 2 of the License, or
15 * (at your option) any later version.
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, write to the Free Software
24 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
36 #include "expairseq.h"
45 #include "relational.h"
51 // If comparing expressions (ex::compare()) is fast, you can set this to 1.
52 // Some routines like quo(), rem() and gcd() will then return a quick answer
53 // when they are called with two identical arguments.
54 #define FAST_COMPARE 1
56 // Set this if you want divide_in_z() to use remembering
57 #define USE_REMEMBER 1
60 /** Return pointer to first symbol found in expression. Due to GiNaCĀ“s
61 * internal ordering of terms, it may not be obvious which symbol this
62 * function returns for a given expression.
64 * @param e expression to search
65 * @param x pointer to first symbol found (returned)
66 * @return "false" if no symbol was found, "true" otherwise */
68 static bool get_first_symbol(const ex &e, const symbol *&x)
70 if (is_ex_exactly_of_type(e, symbol)) {
71 x = static_cast<symbol *>(e.bp);
73 } else if (is_ex_exactly_of_type(e, add) || is_ex_exactly_of_type(e, mul)) {
74 for (int i=0; i<e.nops(); i++)
75 if (get_first_symbol(e.op(i), x))
77 } else if (is_ex_exactly_of_type(e, power)) {
78 if (get_first_symbol(e.op(0), x))
86 * Statistical information about symbols in polynomials
89 /** This structure holds information about the highest and lowest degrees
90 * in which a symbol appears in two multivariate polynomials "a" and "b".
91 * A vector of these structures with information about all symbols in
92 * two polynomials can be created with the function get_symbol_stats().
94 * @see get_symbol_stats */
96 /** Pointer to symbol */
99 /** Highest degree of symbol in polynomial "a" */
102 /** Highest degree of symbol in polynomial "b" */
105 /** Lowest degree of symbol in polynomial "a" */
108 /** Lowest degree of symbol in polynomial "b" */
111 /** Minimum of ldeg_a and ldeg_b (Used for sorting) */
114 /** Commparison operator for sorting */
115 bool operator<(const sym_desc &x) const {return min_deg < x.min_deg;}
118 // Vector of sym_desc structures
119 typedef vector<sym_desc> sym_desc_vec;
121 // Add symbol the sym_desc_vec (used internally by get_symbol_stats())
122 static void add_symbol(const symbol *s, sym_desc_vec &v)
124 sym_desc_vec::iterator it = v.begin(), itend = v.end();
125 while (it != itend) {
126 if (it->sym->compare(*s) == 0) // If it's already in there, don't add it a second time
135 // Collect all symbols of an expression (used internally by get_symbol_stats())
136 static void collect_symbols(const ex &e, sym_desc_vec &v)
138 if (is_ex_exactly_of_type(e, symbol)) {
139 add_symbol(static_cast<symbol *>(e.bp), v);
140 } else if (is_ex_exactly_of_type(e, add) || is_ex_exactly_of_type(e, mul)) {
141 for (int i=0; i<e.nops(); i++)
142 collect_symbols(e.op(i), v);
143 } else if (is_ex_exactly_of_type(e, power)) {
144 collect_symbols(e.op(0), v);
148 /** Collect statistical information about symbols in polynomials.
149 * This function fills in a vector of "sym_desc" structs which contain
150 * information about the highest and lowest degrees of all symbols that
151 * appear in two polynomials. The vector is then sorted by minimum
152 * degree (lowest to highest). The information gathered by this
153 * function is used by the GCD routines to identify trivial factors
154 * and to determine which variable to choose as the main variable
155 * for GCD computation.
157 * @param a first multivariate polynomial
158 * @param b second multivariate polynomial
159 * @param v vector of sym_desc structs (filled in) */
161 static void get_symbol_stats(const ex &a, const ex &b, sym_desc_vec &v)
163 collect_symbols(a.eval(), v); // eval() to expand assigned symbols
164 collect_symbols(b.eval(), v);
165 sym_desc_vec::iterator it = v.begin(), itend = v.end();
166 while (it != itend) {
167 int deg_a = a.degree(*(it->sym));
168 int deg_b = b.degree(*(it->sym));
171 it->min_deg = min(deg_a, deg_b);
172 it->ldeg_a = a.ldegree(*(it->sym));
173 it->ldeg_b = b.ldegree(*(it->sym));
176 sort(v.begin(), v.end());
181 * Computation of LCM of denominators of coefficients of a polynomial
184 // Compute LCM of denominators of coefficients by going through the
185 // expression recursively (used internally by lcm_of_coefficients_denominators())
186 static numeric lcmcoeff(const ex &e, const numeric &l)
188 if (e.info(info_flags::rational))
189 return lcm(ex_to_numeric(e).denom(), l);
190 else if (is_ex_exactly_of_type(e, add) || is_ex_exactly_of_type(e, mul)) {
191 numeric c = numONE();
192 for (int i=0; i<e.nops(); i++) {
193 c = lcmcoeff(e.op(i), c);
196 } else if (is_ex_exactly_of_type(e, power))
197 return lcmcoeff(e.op(0), l);
201 /** Compute LCM of denominators of coefficients of a polynomial.
202 * Given a polynomial with rational coefficients, this function computes
203 * the LCM of the denominators of all coefficients. This can be used
204 * To bring a polynomial from Q[X] to Z[X].
206 * @param e multivariate polynomial
207 * @return LCM of denominators of coefficients */
209 static numeric lcm_of_coefficients_denominators(const ex &e)
211 return lcmcoeff(e.expand(), numONE());
215 /** Compute the integer content (= GCD of all numeric coefficients) of an
216 * expanded polynomial.
218 * @param e expanded polynomial
219 * @return integer content */
221 numeric ex::integer_content(void) const
224 return bp->integer_content();
227 numeric basic::integer_content(void) const
232 numeric numeric::integer_content(void) const
237 numeric add::integer_content(void) const
239 epvector::const_iterator it = seq.begin();
240 epvector::const_iterator itend = seq.end();
241 numeric c = numZERO();
242 while (it != itend) {
243 GINAC_ASSERT(!is_ex_exactly_of_type(it->rest,numeric));
244 GINAC_ASSERT(is_ex_exactly_of_type(it->coeff,numeric));
245 c = gcd(ex_to_numeric(it->coeff), c);
248 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
249 c = gcd(ex_to_numeric(overall_coeff),c);
253 numeric mul::integer_content(void) const
255 #ifdef DO_GINAC_ASSERT
256 epvector::const_iterator it = seq.begin();
257 epvector::const_iterator itend = seq.end();
258 while (it != itend) {
259 GINAC_ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*it),numeric));
262 #endif // def DO_GINAC_ASSERT
263 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
264 return abs(ex_to_numeric(overall_coeff));
269 * Polynomial quotients and remainders
272 /** Quotient q(x) of polynomials a(x) and b(x) in Q[x].
273 * It satisfies a(x)=b(x)*q(x)+r(x).
275 * @param a first polynomial in x (dividend)
276 * @param b second polynomial in x (divisor)
277 * @param x a and b are polynomials in x
278 * @param check_args check whether a and b are polynomials with rational
279 * coefficients (defaults to "true")
280 * @return quotient of a and b in Q[x] */
282 ex quo(const ex &a, const ex &b, const symbol &x, bool check_args)
285 throw(std::overflow_error("quo: division by zero"));
286 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric))
292 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
293 throw(std::invalid_argument("quo: arguments must be polynomials over the rationals"));
295 // Polynomial long division
300 int bdeg = b.degree(x);
301 int rdeg = r.degree(x);
302 ex blcoeff = b.expand().coeff(x, bdeg);
303 bool blcoeff_is_numeric = is_ex_exactly_of_type(blcoeff, numeric);
304 while (rdeg >= bdeg) {
305 ex term, rcoeff = r.coeff(x, rdeg);
306 if (blcoeff_is_numeric)
307 term = rcoeff / blcoeff;
309 if (!divide(rcoeff, blcoeff, term, false))
310 return *new ex(fail());
312 term *= power(x, rdeg - bdeg);
314 r -= (term * b).expand();
323 /** Remainder r(x) of polynomials a(x) and b(x) in Q[x].
324 * It satisfies a(x)=b(x)*q(x)+r(x).
326 * @param a first polynomial in x (dividend)
327 * @param b second polynomial in x (divisor)
328 * @param x a and b are polynomials in x
329 * @param check_args check whether a and b are polynomials with rational
330 * coefficients (defaults to "true")
331 * @return remainder of a(x) and b(x) in Q[x] */
333 ex rem(const ex &a, const ex &b, const symbol &x, bool check_args)
336 throw(std::overflow_error("rem: division by zero"));
337 if (is_ex_exactly_of_type(a, numeric)) {
338 if (is_ex_exactly_of_type(b, numeric))
347 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
348 throw(std::invalid_argument("rem: arguments must be polynomials over the rationals"));
350 // Polynomial long division
354 int bdeg = b.degree(x);
355 int rdeg = r.degree(x);
356 ex blcoeff = b.expand().coeff(x, bdeg);
357 bool blcoeff_is_numeric = is_ex_exactly_of_type(blcoeff, numeric);
358 while (rdeg >= bdeg) {
359 ex term, rcoeff = r.coeff(x, rdeg);
360 if (blcoeff_is_numeric)
361 term = rcoeff / blcoeff;
363 if (!divide(rcoeff, blcoeff, term, false))
364 return *new ex(fail());
366 term *= power(x, rdeg - bdeg);
367 r -= (term * b).expand();
376 /** Pseudo-remainder of polynomials a(x) and b(x) in Z[x].
378 * @param a first polynomial in x (dividend)
379 * @param b second polynomial in x (divisor)
380 * @param x a and b are polynomials in x
381 * @param check_args check whether a and b are polynomials with rational
382 * coefficients (defaults to "true")
383 * @return pseudo-remainder of a(x) and b(x) in Z[x] */
385 ex prem(const ex &a, const ex &b, const symbol &x, bool check_args)
388 throw(std::overflow_error("prem: division by zero"));
389 if (is_ex_exactly_of_type(a, numeric)) {
390 if (is_ex_exactly_of_type(b, numeric))
395 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
396 throw(std::invalid_argument("prem: arguments must be polynomials over the rationals"));
398 // Polynomial long division
401 int rdeg = r.degree(x);
402 int bdeg = eb.degree(x);
405 blcoeff = eb.coeff(x, bdeg);
409 eb -= blcoeff * power(x, bdeg);
413 int delta = rdeg - bdeg + 1, i = 0;
414 while (rdeg >= bdeg && !r.is_zero()) {
415 ex rlcoeff = r.coeff(x, rdeg);
416 ex term = (power(x, rdeg - bdeg) * eb * rlcoeff).expand();
420 r -= rlcoeff * power(x, rdeg);
421 r = (blcoeff * r).expand() - term;
425 return power(blcoeff, delta - i) * r;
429 /** Exact polynomial division of a(X) by b(X) in Q[X].
431 * @param a first multivariate polynomial (dividend)
432 * @param b second multivariate polynomial (divisor)
433 * @param q quotient (returned)
434 * @param check_args check whether a and b are polynomials with rational
435 * coefficients (defaults to "true")
436 * @return "true" when exact division succeeds (quotient returned in q),
437 * "false" otherwise */
439 bool divide(const ex &a, const ex &b, ex &q, bool check_args)
443 throw(std::overflow_error("divide: division by zero"));
444 if (is_ex_exactly_of_type(b, numeric)) {
447 } else if (is_ex_exactly_of_type(a, numeric))
455 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
456 throw(std::invalid_argument("divide: arguments must be polynomials over the rationals"));
460 if (!get_first_symbol(a, x) && !get_first_symbol(b, x))
461 throw(std::invalid_argument("invalid expression in divide()"));
463 // Polynomial long division (recursive)
467 int bdeg = b.degree(*x);
468 int rdeg = r.degree(*x);
469 ex blcoeff = b.expand().coeff(*x, bdeg);
470 bool blcoeff_is_numeric = is_ex_exactly_of_type(blcoeff, numeric);
471 while (rdeg >= bdeg) {
472 ex term, rcoeff = r.coeff(*x, rdeg);
473 if (blcoeff_is_numeric)
474 term = rcoeff / blcoeff;
476 if (!divide(rcoeff, blcoeff, term, false))
478 term *= power(*x, rdeg - bdeg);
480 r -= (term * b).expand();
494 typedef pair<ex, ex> ex2;
495 typedef pair<ex, bool> exbool;
498 bool operator() (const ex2 p, const ex2 q) const
500 return p.first.compare(q.first) < 0 || (!(q.first.compare(p.first) < 0) && p.second.compare(q.second) < 0);
504 typedef map<ex2, exbool, ex2_less> ex2_exbool_remember;
508 /** Exact polynomial division of a(X) by b(X) in Z[X].
509 * This functions works like divide() but the input and output polynomials are
510 * in Z[X] instead of Q[X] (i.e. they have integer coefficients). Unlike
511 * divide(), it doesnĀ“t check whether the input polynomials really are integer
512 * polynomials, so be careful of what you pass in. Also, you have to run
513 * get_symbol_stats() over the input polynomials before calling this function
514 * and pass an iterator to the first element of the sym_desc vector. This
515 * function is used internally by the heur_gcd().
517 * @param a first multivariate polynomial (dividend)
518 * @param b second multivariate polynomial (divisor)
519 * @param q quotient (returned)
520 * @param var iterator to first element of vector of sym_desc structs
521 * @return "true" when exact division succeeds (the quotient is returned in
522 * q), "false" otherwise.
523 * @see get_symbol_stats, heur_gcd */
524 static bool divide_in_z(const ex &a, const ex &b, ex &q, sym_desc_vec::const_iterator var)
528 throw(std::overflow_error("divide_in_z: division by zero"));
529 if (b.is_equal(exONE())) {
533 if (is_ex_exactly_of_type(a, numeric)) {
534 if (is_ex_exactly_of_type(b, numeric)) {
536 return q.info(info_flags::integer);
549 static ex2_exbool_remember dr_remember;
550 ex2_exbool_remember::const_iterator remembered = dr_remember.find(ex2(a, b));
551 if (remembered != dr_remember.end()) {
552 q = remembered->second.first;
553 return remembered->second.second;
558 const symbol *x = var->sym;
561 int adeg = a.degree(*x), bdeg = b.degree(*x);
567 // Polynomial long division (recursive)
573 ex blcoeff = eb.coeff(*x, bdeg);
574 while (rdeg >= bdeg) {
575 ex term, rcoeff = r.coeff(*x, rdeg);
576 if (!divide_in_z(rcoeff, blcoeff, term, var+1))
578 term = (term * power(*x, rdeg - bdeg)).expand();
580 r -= (term * eb).expand();
583 dr_remember[ex2(a, b)] = exbool(q, true);
590 dr_remember[ex2(a, b)] = exbool(q, false);
596 // Trial division using polynomial interpolation
599 // Compute values at evaluation points 0..adeg
600 vector<numeric> alpha; alpha.reserve(adeg + 1);
601 exvector u; u.reserve(adeg + 1);
602 numeric point = numZERO();
604 for (i=0; i<=adeg; i++) {
605 ex bs = b.subs(*x == point);
606 while (bs.is_zero()) {
608 bs = b.subs(*x == point);
610 if (!divide_in_z(a.subs(*x == point), bs, c, var+1))
612 alpha.push_back(point);
618 vector<numeric> rcp; rcp.reserve(adeg + 1);
620 for (k=1; k<=adeg; k++) {
621 numeric product = alpha[k] - alpha[0];
623 product *= alpha[k] - alpha[i];
624 rcp.push_back(product.inverse());
627 // Compute Newton coefficients
628 exvector v; v.reserve(adeg + 1);
630 for (k=1; k<=adeg; k++) {
632 for (i=k-2; i>=0; i--)
633 temp = temp * (alpha[k] - alpha[i]) + v[i];
634 v.push_back((u[k] - temp) * rcp[k]);
637 // Convert from Newton form to standard form
639 for (k=adeg-1; k>=0; k--)
640 c = c * (*x - alpha[k]) + v[k];
642 if (c.degree(*x) == (adeg - bdeg)) {
652 * Separation of unit part, content part and primitive part of polynomials
655 /** Compute unit part (= sign of leading coefficient) of a multivariate
656 * polynomial in Z[x]. The product of unit part, content part, and primitive
657 * part is the polynomial itself.
659 * @param x variable in which to compute the unit part
661 * @see ex::content, ex::primpart */
662 ex ex::unit(const symbol &x) const
664 ex c = expand().lcoeff(x);
665 if (is_ex_exactly_of_type(c, numeric))
666 return c < exZERO() ? exMINUSONE() : exONE();
669 if (get_first_symbol(c, y))
672 throw(std::invalid_argument("invalid expression in unit()"));
677 /** Compute content part (= unit normal GCD of all coefficients) of a
678 * multivariate polynomial in Z[x]. The product of unit part, content part,
679 * and primitive part is the polynomial itself.
681 * @param x variable in which to compute the content part
682 * @return content part
683 * @see ex::unit, ex::primpart */
684 ex ex::content(const symbol &x) const
688 if (is_ex_exactly_of_type(*this, numeric))
689 return info(info_flags::negative) ? -*this : *this;
694 // First, try the integer content
695 ex c = e.integer_content();
697 ex lcoeff = r.lcoeff(x);
698 if (lcoeff.info(info_flags::integer))
701 // GCD of all coefficients
702 int deg = e.degree(x);
703 int ldeg = e.ldegree(x);
705 return e.lcoeff(x) / e.unit(x);
707 for (int i=ldeg; i<=deg; i++)
708 c = gcd(e.coeff(x, i), c, NULL, NULL, false);
713 /** Compute primitive part of a multivariate polynomial in Z[x].
714 * The product of unit part, content part, and primitive part is the
717 * @param x variable in which to compute the primitive part
718 * @return primitive part
719 * @see ex::unit, ex::content */
720 ex ex::primpart(const symbol &x) const
724 if (is_ex_exactly_of_type(*this, numeric))
731 if (is_ex_exactly_of_type(c, numeric))
732 return *this / (c * u);
734 return quo(*this, c * u, x, false);
738 /** Compute primitive part of a multivariate polynomial in Z[x] when the
739 * content part is already known. This function is faster in computing the
740 * primitive part than the previous function.
742 * @param x variable in which to compute the primitive part
743 * @param c previously computed content part
744 * @return primitive part */
746 ex ex::primpart(const symbol &x, const ex &c) const
752 if (is_ex_exactly_of_type(*this, numeric))
756 if (is_ex_exactly_of_type(c, numeric))
757 return *this / (c * u);
759 return quo(*this, c * u, x, false);
764 * GCD of multivariate polynomials
767 /** Compute GCD of multivariate polynomials using the subresultant PRS
768 * algorithm. This function is used internally gy gcd().
770 * @param a first multivariate polynomial
771 * @param b second multivariate polynomial
772 * @param x pointer to symbol (main variable) in which to compute the GCD in
773 * @return the GCD as a new expression
776 static ex sr_gcd(const ex &a, const ex &b, const symbol *x)
778 // Sort c and d so that c has higher degree
780 int adeg = a.degree(*x), bdeg = b.degree(*x);
794 // Remove content from c and d, to be attached to GCD later
795 ex cont_c = c.content(*x);
796 ex cont_d = d.content(*x);
797 ex gamma = gcd(cont_c, cont_d, NULL, NULL, false);
800 c = c.primpart(*x, cont_c);
801 d = d.primpart(*x, cont_d);
803 // First element of subresultant sequence
804 ex r = exZERO(), ri = exONE(), psi = exONE();
805 int delta = cdeg - ddeg;
808 // Calculate polynomial pseudo-remainder
809 r = prem(c, d, *x, false);
811 return gamma * d.primpart(*x);
814 if (!divide(r, ri * power(psi, delta), d, false))
815 throw(std::runtime_error("invalid expression in sr_gcd(), division failed"));
818 if (is_ex_exactly_of_type(r, numeric))
821 return gamma * r.primpart(*x);
824 // Next element of subresultant sequence
825 ri = c.expand().lcoeff(*x);
829 divide(power(ri, delta), power(psi, delta-1), psi, false);
835 /** Return maximum (absolute value) coefficient of a polynomial.
836 * This function is used internally by heur_gcd().
838 * @param e expanded multivariate polynomial
839 * @return maximum coefficient
842 numeric ex::max_coefficient(void) const
845 return bp->max_coefficient();
848 numeric basic::max_coefficient(void) const
853 numeric numeric::max_coefficient(void) const
858 numeric add::max_coefficient(void) const
860 epvector::const_iterator it = seq.begin();
861 epvector::const_iterator itend = seq.end();
862 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
863 numeric cur_max = abs(ex_to_numeric(overall_coeff));
864 while (it != itend) {
866 GINAC_ASSERT(!is_ex_exactly_of_type(it->rest,numeric));
867 a = abs(ex_to_numeric(it->coeff));
875 numeric mul::max_coefficient(void) const
877 #ifdef DO_GINAC_ASSERT
878 epvector::const_iterator it = seq.begin();
879 epvector::const_iterator itend = seq.end();
880 while (it != itend) {
881 GINAC_ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*it),numeric));
884 #endif // def DO_GINAC_ASSERT
885 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
886 return abs(ex_to_numeric(overall_coeff));
890 /** Apply symmetric modular homomorphism to a multivariate polynomial.
891 * This function is used internally by heur_gcd().
893 * @param e expanded multivariate polynomial
895 * @return mapped polynomial
898 ex ex::smod(const numeric &xi) const
904 ex basic::smod(const numeric &xi) const
909 ex numeric::smod(const numeric &xi) const
911 return GiNaC::smod(*this, xi);
914 ex add::smod(const numeric &xi) const
917 newseq.reserve(seq.size()+1);
918 epvector::const_iterator it = seq.begin();
919 epvector::const_iterator itend = seq.end();
920 while (it != itend) {
921 GINAC_ASSERT(!is_ex_exactly_of_type(it->rest,numeric));
922 numeric coeff = GiNaC::smod(ex_to_numeric(it->coeff), xi);
923 if (!coeff.is_zero())
924 newseq.push_back(expair(it->rest, coeff));
927 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
928 numeric coeff = GiNaC::smod(ex_to_numeric(overall_coeff), xi);
929 return (new add(newseq,coeff))->setflag(status_flags::dynallocated);
932 ex mul::smod(const numeric &xi) const
934 #ifdef DO_GINAC_ASSERT
935 epvector::const_iterator it = seq.begin();
936 epvector::const_iterator itend = seq.end();
937 while (it != itend) {
938 GINAC_ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*it),numeric));
941 #endif // def DO_GINAC_ASSERT
942 mul * mulcopyp=new mul(*this);
943 GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
944 mulcopyp->overall_coeff = GiNaC::smod(ex_to_numeric(overall_coeff),xi);
945 mulcopyp->clearflag(status_flags::evaluated);
946 mulcopyp->clearflag(status_flags::hash_calculated);
947 return mulcopyp->setflag(status_flags::dynallocated);
951 /** Exception thrown by heur_gcd() to signal failure */
952 class gcdheu_failed {};
954 /** Compute GCD of multivariate polynomials using the heuristic GCD algorithm.
955 * get_symbol_stats() must have been called previously with the input
956 * polynomials and an iterator to the first element of the sym_desc vector
957 * passed in. This function is used internally by gcd().
959 * @param a first multivariate polynomial (expanded)
960 * @param b second multivariate polynomial (expanded)
961 * @param ca cofactor of polynomial a (returned), NULL to suppress
962 * calculation of cofactor
963 * @param cb cofactor of polynomial b (returned), NULL to suppress
964 * calculation of cofactor
965 * @param var iterator to first element of vector of sym_desc structs
966 * @return the GCD as a new expression
968 * @exception gcdheu_failed() */
970 static ex heur_gcd(const ex &a, const ex &b, ex *ca, ex *cb, sym_desc_vec::const_iterator var)
972 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric)) {
973 numeric g = gcd(ex_to_numeric(a), ex_to_numeric(b));
978 *ca = ex_to_numeric(a).mul(rg);
980 *cb = ex_to_numeric(b).mul(rg);
984 // The first symbol is our main variable
985 const symbol *x = var->sym;
987 // Remove integer content
988 numeric gc = gcd(a.integer_content(), b.integer_content());
989 numeric rgc = gc.inverse();
992 int maxdeg = max(p.degree(*x), q.degree(*x));
994 // Find evaluation point
995 numeric mp = p.max_coefficient(), mq = q.max_coefficient();
998 xi = mq * numTWO() + numTWO();
1000 xi = mp * numTWO() + numTWO();
1003 for (int t=0; t<6; t++) {
1004 if (xi.int_length() * maxdeg > 50000)
1005 throw gcdheu_failed();
1007 // Apply evaluation homomorphism and calculate GCD
1008 ex gamma = heur_gcd(p.subs(*x == xi), q.subs(*x == xi), NULL, NULL, var+1).expand();
1009 if (!is_ex_exactly_of_type(gamma, fail)) {
1011 // Reconstruct polynomial from GCD of mapped polynomials
1013 numeric rxi = xi.inverse();
1014 for (int i=0; !gamma.is_zero(); i++) {
1015 ex gi = gamma.smod(xi);
1016 g += gi * power(*x, i);
1017 gamma = (gamma - gi) * rxi;
1019 // Remove integer content
1020 g /= g.integer_content();
1022 // If the calculated polynomial divides both a and b, this is the GCD
1024 if (divide_in_z(p, g, ca ? *ca : dummy, var) && divide_in_z(q, g, cb ? *cb : dummy, var)) {
1026 ex lc = g.lcoeff(*x);
1027 if (is_ex_exactly_of_type(lc, numeric) && lc.compare(exZERO()) < 0)
1034 // Next evaluation point
1035 xi = iquo(xi * isqrt(isqrt(xi)) * numeric(73794), numeric(27011));
1037 return *new ex(fail());
1041 /** Compute GCD (Greatest Common Divisor) of multivariate polynomials a(X)
1044 * @param a first multivariate polynomial
1045 * @param b second multivariate polynomial
1046 * @param check_args check whether a and b are polynomials with rational
1047 * coefficients (defaults to "true")
1048 * @return the GCD as a new expression */
1050 ex gcd(const ex &a, const ex &b, ex *ca, ex *cb, bool check_args)
1052 // Some trivial cases
1053 ex aex = a.expand(), bex = b.expand();
1054 if (aex.is_zero()) {
1061 if (bex.is_zero()) {
1068 if (aex.is_equal(exONE()) || bex.is_equal(exONE())) {
1076 if (a.is_equal(b)) {
1084 if (is_ex_exactly_of_type(aex, numeric) && is_ex_exactly_of_type(bex, numeric)) {
1085 numeric g = gcd(ex_to_numeric(aex), ex_to_numeric(bex));
1087 *ca = ex_to_numeric(aex) / g;
1089 *cb = ex_to_numeric(bex) / g;
1092 if (check_args && !a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)) {
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((aex / common).expand(), (bex / 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 = bex.content(*x);
1118 ex g = gcd(aex, c, ca, cb, false);
1120 *cb *= bex.unit(*x) * bex.primpart(*x, c);
1122 } else if (var->deg_b == 0) {
1123 //clog << "eliminating variable " << *x << " from a" << endl;
1124 ex c = aex.content(*x);
1125 ex g = gcd(c, bex, ca, cb, false);
1127 *ca *= aex.unit(*x) * aex.primpart(*x, c);
1131 // Try heuristic algorithm first, fall back to PRS if that failed
1134 g = heur_gcd(aex, bex, 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(aex, bex, x);
1142 divide(aex, g, *ca, false);
1144 divide(bex, 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);
1487 } // namespace GiNaC