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 ASSERT(!is_ex_exactly_of_type(it->rest,numeric));
244 ASSERT(is_ex_exactly_of_type(it->coeff,numeric));
245 c = gcd(ex_to_numeric(it->coeff), c);
248 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
256 epvector::const_iterator it = seq.begin();
257 epvector::const_iterator itend = seq.end();
258 while (it != itend) {
259 ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*it),numeric));
262 #endif // def DOASSERT
263 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 ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
863 numeric cur_max = abs(ex_to_numeric(overall_coeff));
864 while (it != itend) {
866 ASSERT(!is_ex_exactly_of_type(it->rest,numeric));
867 a = abs(ex_to_numeric(it->coeff));
875 numeric mul::max_coefficient(void) const
878 epvector::const_iterator it = seq.begin();
879 epvector::const_iterator itend = seq.end();
880 while (it != itend) {
881 ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*it),numeric));
884 #endif // def DOASSERT
885 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 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 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
935 epvector::const_iterator it = seq.begin();
936 epvector::const_iterator itend = seq.end();
937 while (it != itend) {
938 ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*it),numeric));
941 #endif // def DOASSERT
942 mul * mulcopyp=new mul(*this);
943 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
1067 if (a.is_equal(exONE()) || b.is_equal(exONE())) {
1075 if (a.is_equal(b)) {
1083 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric)) {
1084 numeric g = gcd(ex_to_numeric(a), ex_to_numeric(b));
1086 *ca = ex_to_numeric(a) / g;
1088 *cb = ex_to_numeric(b) / g;
1091 if (check_args && !a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)) {
1092 cerr << "a=" << a << endl;
1093 cerr << "b=" << b << endl;
1094 throw(std::invalid_argument("gcd: arguments must be polynomials over the rationals"));
1097 // Gather symbol statistics
1098 sym_desc_vec sym_stats;
1099 get_symbol_stats(a, b, sym_stats);
1101 // The symbol with least degree is our main variable
1102 sym_desc_vec::const_iterator var = sym_stats.begin();
1103 const symbol *x = var->sym;
1105 // Cancel trivial common factor
1106 int ldeg_a = var->ldeg_a;
1107 int ldeg_b = var->ldeg_b;
1108 int min_ldeg = min(ldeg_a, ldeg_b);
1110 ex common = power(*x, min_ldeg);
1111 //clog << "trivial common factor " << common << endl;
1112 return gcd((a / common).expand(), (b / common).expand(), ca, cb, false) * common;
1115 // Try to eliminate variables
1116 if (var->deg_a == 0) {
1117 //clog << "eliminating variable " << *x << " from b" << endl;
1118 ex c = b.content(*x);
1119 ex g = gcd(a, c, ca, cb, false);
1121 *cb *= b.unit(*x) * b.primpart(*x, c);
1123 } else if (var->deg_b == 0) {
1124 //clog << "eliminating variable " << *x << " from a" << endl;
1125 ex c = a.content(*x);
1126 ex g = gcd(c, b, ca, cb, false);
1128 *ca *= a.unit(*x) * a.primpart(*x, c);
1132 // Try heuristic algorithm first, fall back to PRS if that failed
1135 g = heur_gcd(a.expand(), b.expand(), ca, cb, var);
1136 } catch (gcdheu_failed) {
1137 g = *new ex(fail());
1139 if (is_ex_exactly_of_type(g, fail)) {
1140 //clog << "heuristics failed\n";
1141 g = sr_gcd(a, b, x);
1143 divide(a, g, *ca, false);
1145 divide(b, g, *cb, false);
1151 /** Compute LCM (Least Common Multiple) of multivariate polynomials in Z[X].
1153 * @param a first multivariate polynomial
1154 * @param b second multivariate polynomial
1155 * @param check_args check whether a and b are polynomials with rational
1156 * coefficients (defaults to "true")
1157 * @return the LCM as a new expression */
1158 ex lcm(const ex &a, const ex &b, bool check_args)
1160 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric))
1161 return gcd(ex_to_numeric(a), ex_to_numeric(b));
1162 if (check_args && !a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial))
1163 throw(std::invalid_argument("lcm: arguments must be polynomials over the rationals"));
1166 ex g = gcd(a, b, &ca, &cb, false);
1172 * Square-free factorization
1175 // Univariate GCD of polynomials in Q[x] (used internally by sqrfree()).
1176 // a and b can be multivariate polynomials but they are treated as univariate polynomials in x.
1177 static ex univariate_gcd(const ex &a, const ex &b, const symbol &x)
1183 if (a.is_equal(exONE()) || b.is_equal(exONE()))
1185 if (is_ex_of_type(a, numeric) && is_ex_of_type(b, numeric))
1186 return gcd(ex_to_numeric(a), ex_to_numeric(b));
1187 if (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial))
1188 throw(std::invalid_argument("univariate_gcd: arguments must be polynomials over the rationals"));
1190 // Euclidean algorithm
1192 if (a.degree(x) >= b.degree(x)) {
1200 r = rem(c, d, x, false);
1206 return d / d.lcoeff(x);
1210 /** Compute square-free factorization of multivariate polynomial a(x) using
1213 * @param a multivariate polynomial
1214 * @param x variable to factor in
1215 * @return factored polynomial */
1216 ex sqrfree(const ex &a, const symbol &x)
1221 ex c = univariate_gcd(a, b, x);
1223 if (c.is_equal(exONE())) {
1227 ex y = quo(b, c, x);
1228 ex z = y - w.diff(x);
1229 while (!z.is_zero()) {
1230 ex g = univariate_gcd(w, z, x);
1238 return res * power(w, i);
1243 * Normal form of rational functions
1246 // Create a symbol for replacing the expression "e" (or return a previously
1247 // assigned symbol). The symbol is appended to sym_list and returned, the
1248 // expression is appended to repl_list.
1249 static ex replace_with_symbol(const ex &e, lst &sym_lst, lst &repl_lst)
1251 // Expression already in repl_lst? Then return the assigned symbol
1252 for (int i=0; i<repl_lst.nops(); i++)
1253 if (repl_lst.op(i).is_equal(e))
1254 return sym_lst.op(i);
1256 // Otherwise create new symbol and add to list, taking care that the
1257 // replacement expression doesn't contain symbols from the sym_lst
1258 // because subs() is not recursive
1261 ex e_replaced = e.subs(sym_lst, repl_lst);
1263 repl_lst.append(e_replaced);
1268 /** Default implementation of ex::normal(). It replaces the object with a
1270 * @see ex::normal */
1271 ex basic::normal(lst &sym_lst, lst &repl_lst, int level) const
1273 return replace_with_symbol(*this, sym_lst, repl_lst);
1277 /** Implementation of ex::normal() for symbols. This returns the unmodifies symbol.
1278 * @see ex::normal */
1279 ex symbol::normal(lst &sym_lst, lst &repl_lst, int level) const
1285 /** Implementation of ex::normal() for a numeric. It splits complex numbers
1286 * into re+I*im and replaces I and non-rational real numbers with a temporary
1288 * @see ex::normal */
1289 ex numeric::normal(lst &sym_lst, lst &repl_lst, int level) const
1295 return replace_with_symbol(*this, sym_lst, repl_lst);
1297 numeric re = real(), im = imag();
1298 ex re_ex = re.is_rational() ? re : replace_with_symbol(re, sym_lst, repl_lst);
1299 ex im_ex = im.is_rational() ? im : replace_with_symbol(im, sym_lst, repl_lst);
1300 return re_ex + im_ex * replace_with_symbol(I, sym_lst, repl_lst);
1306 * Helper function for fraction cancellation (returns cancelled fraction n/d)
1309 static ex frac_cancel(const ex &n, const ex &d)
1313 ex pre_factor = exONE();
1315 // Handle special cases where numerator or denominator is 0
1318 if (den.expand().is_zero())
1319 throw(std::overflow_error("frac_cancel: division by zero in frac_cancel"));
1321 // More special cases
1322 if (is_ex_exactly_of_type(den, numeric))
1327 // Bring numerator and denominator to Z[X] by multiplying with
1328 // LCM of all coefficients' denominators
1329 ex num_lcm = lcm_of_coefficients_denominators(num);
1330 ex den_lcm = lcm_of_coefficients_denominators(den);
1333 pre_factor = den_lcm / num_lcm;
1335 // Cancel GCD from numerator and denominator
1337 if (gcd(num, den, &cnum, &cden, false) != exONE()) {
1342 // Make denominator unit normal (i.e. coefficient of first symbol
1343 // as defined by get_first_symbol() is made positive)
1345 if (get_first_symbol(den, x)) {
1346 if (den.unit(*x).compare(exZERO()) < 0) {
1347 num *= exMINUSONE();
1348 den *= exMINUSONE();
1351 return pre_factor * num / den;
1355 /** Implementation of ex::normal() for a sum. It expands terms and performs
1356 * fractional addition.
1357 * @see ex::normal */
1358 ex add::normal(lst &sym_lst, lst &repl_lst, int level) const
1360 // Normalize and expand children
1362 o.reserve(seq.size()+1);
1363 epvector::const_iterator it = seq.begin(), itend = seq.end();
1364 while (it != itend) {
1365 ex n = recombine_pair_to_ex(*it).bp->normal(sym_lst, repl_lst, level-1).expand();
1366 if (is_ex_exactly_of_type(n, add)) {
1367 epvector::const_iterator bit = (static_cast<add *>(n.bp))->seq.begin(), bitend = (static_cast<add *>(n.bp))->seq.end();
1368 while (bit != bitend) {
1369 o.push_back(recombine_pair_to_ex(*bit));
1372 o.push_back((static_cast<add *>(n.bp))->overall_coeff);
1377 o.push_back(overall_coeff.bp->normal(sym_lst, repl_lst, level-1));
1379 // Determine common denominator
1381 exvector::const_iterator ait = o.begin(), aitend = o.end();
1382 while (ait != aitend) {
1383 den = lcm((*ait).denom(false), den, false);
1388 if (den.is_equal(exONE()))
1389 return (new add(o))->setflag(status_flags::dynallocated);
1392 for (ait=o.begin(); ait!=aitend; ait++) {
1394 if (!divide(den, (*ait).denom(false), q, false)) {
1395 // should not happen
1396 throw(std::runtime_error("invalid expression in add::normal, division failed"));
1398 num_seq.push_back((*ait).numer(false) * q);
1400 ex num = add(num_seq);
1402 // Cancel common factors from num/den
1403 return frac_cancel(num, den);
1408 /** Implementation of ex::normal() for a product. It cancels common factors
1410 * @see ex::normal() */
1411 ex mul::normal(lst &sym_lst, lst &repl_lst, int level) const
1413 // Normalize children
1415 o.reserve(seq.size()+1);
1416 epvector::const_iterator it = seq.begin(), itend = seq.end();
1417 while (it != itend) {
1418 o.push_back(recombine_pair_to_ex(*it).bp->normal(sym_lst, repl_lst, level-1));
1421 o.push_back(overall_coeff.bp->normal(sym_lst, repl_lst, level-1));
1422 ex n = (new mul(o))->setflag(status_flags::dynallocated);
1423 return frac_cancel(n.numer(false), n.denom(false));
1427 /** Implementation of ex::normal() for powers. It normalizes the basis,
1428 * distributes integer exponents to numerator and denominator, and replaces
1429 * non-integer powers by temporary symbols.
1430 * @see ex::normal */
1431 ex power::normal(lst &sym_lst, lst &repl_lst, int level) const
1433 if (exponent.info(info_flags::integer)) {
1434 // Integer powers are distributed
1435 ex n = basis.bp->normal(sym_lst, repl_lst, level-1);
1436 ex num = n.numer(false);
1437 ex den = n.denom(false);
1438 return power(num, exponent) / power(den, exponent);
1440 // Non-integer powers are replaced by temporary symbol (after normalizing basis)
1441 ex n = power(basis.bp->normal(sym_lst, repl_lst, level-1), exponent);
1442 return replace_with_symbol(n, sym_lst, repl_lst);
1447 /** Implementation of ex::normal() for series. It normalizes each coefficient and
1448 * replaces the series by a temporary symbol.
1449 * @see ex::normal */
1450 ex series::normal(lst &sym_lst, lst &repl_lst, int level) const
1453 new_seq.reserve(seq.size());
1455 epvector::const_iterator it = seq.begin(), itend = seq.end();
1456 while (it != itend) {
1457 new_seq.push_back(expair(it->rest.normal(), it->coeff));
1461 ex n = series(var, point, new_seq);
1462 return replace_with_symbol(n, sym_lst, repl_lst);
1466 /** Normalization of rational functions.
1467 * This function converts an expression to its normal form
1468 * "numerator/denominator", where numerator and denominator are (relatively
1469 * prime) polynomials. Any subexpressions which are not rational functions
1470 * (like non-rational numbers, non-integer powers or functions like Sin(),
1471 * Cos() etc.) are replaced by temporary symbols which are re-substituted by
1472 * the (normalized) subexpressions before normal() returns (this way, any
1473 * expression can be treated as a rational function). normal() is applied
1474 * recursively to arguments of functions etc.
1476 * @param level maximum depth of recursion
1477 * @return normalized expression */
1478 ex ex::normal(int level) const
1480 lst sym_lst, repl_lst;
1481 ex e = bp->normal(sym_lst, repl_lst, level);
1482 if (sym_lst.nops() > 0)
1483 return e.subs(sym_lst, repl_lst);
1488 } // namespace GiNaC