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.
13 // If comparing expressions (ex::compare()) is fast, you can set this to 1.
14 // Some routines like quo(), rem() and gcd() will then return a quick answer
15 // when they are called with two identical arguments.
16 #define FAST_COMPARE 1
18 // Set this if you want divide_in_z() to use remembering
19 #define USE_REMEMBER 1
22 /** Return pointer to first symbol found in expression. Due to GiNaCĀ“s
23 * internal ordering of terms, it may not be obvious which symbol this
24 * function returns for a given expression.
26 * @param e expression to search
27 * @param x pointer to first symbol found (returned)
28 * @return "false" if no symbol was found, "true" otherwise */
30 static bool get_first_symbol(const ex &e, const symbol *&x)
32 if (is_ex_exactly_of_type(e, symbol)) {
33 x = static_cast<symbol *>(e.bp);
35 } else if (is_ex_exactly_of_type(e, add) || is_ex_exactly_of_type(e, mul)) {
36 for (int i=0; i<e.nops(); i++)
37 if (get_first_symbol(e.op(i), x))
39 } else if (is_ex_exactly_of_type(e, power)) {
40 if (get_first_symbol(e.op(0), x))
48 * Statistical information about symbols in polynomials
53 /** This structure holds information about the highest and lowest degrees
54 * in which a symbol appears in two multivariate polynomials "a" and "b".
55 * A vector of these structures with information about all symbols in
56 * two polynomials can be created with the function get_symbol_stats().
58 * @see get_symbol_stats */
60 /** Pointer to symbol */
63 /** Highest degree of symbol in polynomial "a" */
66 /** Highest degree of symbol in polynomial "b" */
69 /** Lowest degree of symbol in polynomial "a" */
72 /** Lowest degree of symbol in polynomial "b" */
75 /** Minimum of ldeg_a and ldeg_b (Used for sorting) */
78 /** Commparison operator for sorting */
79 bool operator<(const sym_desc &x) const {return min_deg < x.min_deg;}
82 // Vector of sym_desc structures
83 typedef vector<sym_desc> sym_desc_vec;
85 // Add symbol the sym_desc_vec (used internally by get_symbol_stats())
86 static void add_symbol(const symbol *s, sym_desc_vec &v)
88 sym_desc_vec::iterator it = v.begin(), itend = v.end();
90 if (it->sym->compare(*s) == 0) // If it's already in there, don't add it a second time
99 // Collect all symbols of an expression (used internally by get_symbol_stats())
100 static void collect_symbols(const ex &e, sym_desc_vec &v)
102 if (is_ex_exactly_of_type(e, symbol)) {
103 add_symbol(static_cast<symbol *>(e.bp), v);
104 } else if (is_ex_exactly_of_type(e, add) || is_ex_exactly_of_type(e, mul)) {
105 for (int i=0; i<e.nops(); i++)
106 collect_symbols(e.op(i), v);
107 } else if (is_ex_exactly_of_type(e, power)) {
108 collect_symbols(e.op(0), v);
112 /** Collect statistical information about symbols in polynomials.
113 * This function fills in a vector of "sym_desc" structs which contain
114 * information about the highest and lowest degrees of all symbols that
115 * appear in two polynomials. The vector is then sorted by minimum
116 * degree (lowest to highest). The information gathered by this
117 * function is used by the GCD routines to identify trivial factors
118 * and to determine which variable to choose as the main variable
119 * for GCD computation.
121 * @param a first multivariate polynomial
122 * @param b second multivariate polynomial
123 * @param v vector of sym_desc structs (filled in) */
125 static void get_symbol_stats(const ex &a, const ex &b, sym_desc_vec &v)
127 collect_symbols(a.eval(), v); // eval() to expand assigned symbols
128 collect_symbols(b.eval(), v);
129 sym_desc_vec::iterator it = v.begin(), itend = v.end();
130 while (it != itend) {
131 int deg_a = a.degree(*(it->sym));
132 int deg_b = b.degree(*(it->sym));
135 it->min_deg = min(deg_a, deg_b);
136 it->ldeg_a = a.ldegree(*(it->sym));
137 it->ldeg_b = b.ldegree(*(it->sym));
140 sort(v.begin(), v.end());
145 * Computation of LCM of denominators of coefficients of a polynomial
148 // Compute LCM of denominators of coefficients by going through the
149 // expression recursively (used internally by lcm_of_coefficients_denominators())
150 static numeric lcmcoeff(const ex &e, const numeric &l)
152 if (e.info(info_flags::rational))
153 return lcm(ex_to_numeric(e).denom(), l);
154 else if (is_ex_exactly_of_type(e, add) || is_ex_exactly_of_type(e, mul)) {
155 numeric c = numONE();
156 for (int i=0; i<e.nops(); i++) {
157 c = lcmcoeff(e.op(i), c);
160 } else if (is_ex_exactly_of_type(e, power))
161 return lcmcoeff(e.op(0), l);
165 /** Compute LCM of denominators of coefficients of a polynomial.
166 * Given a polynomial with rational coefficients, this function computes
167 * the LCM of the denominators of all coefficients. This can be used
168 * To bring a polynomial from Q[X] to Z[X].
170 * @param e multivariate polynomial
171 * @return LCM of denominators of coefficients */
173 static numeric lcm_of_coefficients_denominators(const ex &e)
175 return lcmcoeff(e.expand(), numONE());
179 /** Compute the integer content (= GCD of all numeric coefficients) of an
180 * expanded polynomial.
182 * @param e expanded polynomial
183 * @return integer content */
185 numeric ex::integer_content(void) const
188 return bp->integer_content();
191 numeric basic::integer_content(void) const
196 numeric numeric::integer_content(void) const
201 numeric add::integer_content(void) const
203 epvector::const_iterator it = seq.begin();
204 epvector::const_iterator itend = seq.end();
205 numeric c = numZERO();
206 while (it != itend) {
207 ASSERT(!is_ex_exactly_of_type(it->rest,numeric));
208 ASSERT(is_ex_exactly_of_type(it->coeff,numeric));
209 c = gcd(ex_to_numeric(it->coeff), c);
212 ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
213 c = gcd(ex_to_numeric(overall_coeff),c);
217 numeric mul::integer_content(void) const
220 epvector::const_iterator it = seq.begin();
221 epvector::const_iterator itend = seq.end();
222 while (it != itend) {
223 ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*it),numeric));
226 #endif // def DOASSERT
227 ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
228 return abs(ex_to_numeric(overall_coeff));
233 * Polynomial quotients and remainders
236 /** Quotient q(x) of polynomials a(x) and b(x) in Q[x].
237 * It satisfies a(x)=b(x)*q(x)+r(x).
239 * @param a first polynomial in x (dividend)
240 * @param b second polynomial in x (divisor)
241 * @param x a and b are polynomials in x
242 * @param check_args check whether a and b are polynomials with rational
243 * coefficients (defaults to "true")
244 * @return quotient of a and b in Q[x] */
246 ex quo(const ex &a, const ex &b, const symbol &x, bool check_args)
249 throw(std::overflow_error("quo: division by zero"));
250 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric))
256 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
257 throw(std::invalid_argument("quo: arguments must be polynomials over the rationals"));
259 // Polynomial long division
264 int bdeg = b.degree(x);
265 int rdeg = r.degree(x);
266 ex blcoeff = b.expand().coeff(x, bdeg);
267 bool blcoeff_is_numeric = is_ex_exactly_of_type(blcoeff, numeric);
268 while (rdeg >= bdeg) {
269 ex term, rcoeff = r.coeff(x, rdeg);
270 if (blcoeff_is_numeric)
271 term = rcoeff / blcoeff;
273 if (!divide(rcoeff, blcoeff, term, false))
274 return *new ex(fail());
276 term *= power(x, rdeg - bdeg);
278 r -= (term * b).expand();
287 /** Remainder r(x) of polynomials a(x) and b(x) in Q[x].
288 * It satisfies a(x)=b(x)*q(x)+r(x).
290 * @param a first polynomial in x (dividend)
291 * @param b second polynomial in x (divisor)
292 * @param x a and b are polynomials in x
293 * @param check_args check whether a and b are polynomials with rational
294 * coefficients (defaults to "true")
295 * @return remainder of a(x) and b(x) in Q[x] */
297 ex rem(const ex &a, const ex &b, const symbol &x, bool check_args)
300 throw(std::overflow_error("rem: division by zero"));
301 if (is_ex_exactly_of_type(a, numeric)) {
302 if (is_ex_exactly_of_type(b, numeric))
311 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
312 throw(std::invalid_argument("rem: arguments must be polynomials over the rationals"));
314 // Polynomial long division
318 int bdeg = b.degree(x);
319 int rdeg = r.degree(x);
320 ex blcoeff = b.expand().coeff(x, bdeg);
321 bool blcoeff_is_numeric = is_ex_exactly_of_type(blcoeff, numeric);
322 while (rdeg >= bdeg) {
323 ex term, rcoeff = r.coeff(x, rdeg);
324 if (blcoeff_is_numeric)
325 term = rcoeff / blcoeff;
327 if (!divide(rcoeff, blcoeff, term, false))
328 return *new ex(fail());
330 term *= power(x, rdeg - bdeg);
331 r -= (term * b).expand();
340 /** Pseudo-remainder of polynomials a(x) and b(x) in Z[x].
342 * @param a first polynomial in x (dividend)
343 * @param b second polynomial in x (divisor)
344 * @param x a and b are polynomials in x
345 * @param check_args check whether a and b are polynomials with rational
346 * coefficients (defaults to "true")
347 * @return pseudo-remainder of a(x) and b(x) in Z[x] */
349 ex prem(const ex &a, const ex &b, const symbol &x, bool check_args)
352 throw(std::overflow_error("prem: division by zero"));
353 if (is_ex_exactly_of_type(a, numeric)) {
354 if (is_ex_exactly_of_type(b, numeric))
359 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
360 throw(std::invalid_argument("prem: arguments must be polynomials over the rationals"));
362 // Polynomial long division
365 int rdeg = r.degree(x);
366 int bdeg = eb.degree(x);
369 blcoeff = eb.coeff(x, bdeg);
373 eb -= blcoeff * power(x, bdeg);
377 int delta = rdeg - bdeg + 1, i = 0;
378 while (rdeg >= bdeg && !r.is_zero()) {
379 ex rlcoeff = r.coeff(x, rdeg);
380 ex term = (power(x, rdeg - bdeg) * eb * rlcoeff).expand();
384 r -= rlcoeff * power(x, rdeg);
385 r = (blcoeff * r).expand() - term;
389 return power(blcoeff, delta - i) * r;
393 /** Exact polynomial division of a(X) by b(X) in Q[X].
395 * @param a first multivariate polynomial (dividend)
396 * @param b second multivariate polynomial (divisor)
397 * @param q quotient (returned)
398 * @param check_args check whether a and b are polynomials with rational
399 * coefficients (defaults to "true")
400 * @return "true" when exact division succeeds (quotient returned in q),
401 * "false" otherwise */
403 bool divide(const ex &a, const ex &b, ex &q, bool check_args)
407 throw(std::overflow_error("divide: division by zero"));
408 if (is_ex_exactly_of_type(b, numeric)) {
411 } else if (is_ex_exactly_of_type(a, numeric))
419 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
420 throw(std::invalid_argument("divide: arguments must be polynomials over the rationals"));
424 if (!get_first_symbol(a, x) && !get_first_symbol(b, x))
425 throw(std::invalid_argument("invalid expression in divide()"));
427 // Polynomial long division (recursive)
431 int bdeg = b.degree(*x);
432 int rdeg = r.degree(*x);
433 ex blcoeff = b.expand().coeff(*x, bdeg);
434 bool blcoeff_is_numeric = is_ex_exactly_of_type(blcoeff, numeric);
435 while (rdeg >= bdeg) {
436 ex term, rcoeff = r.coeff(*x, rdeg);
437 if (blcoeff_is_numeric)
438 term = rcoeff / blcoeff;
440 if (!divide(rcoeff, blcoeff, term, false))
442 term *= power(*x, rdeg - bdeg);
444 r -= (term * b).expand();
460 typedef pair<ex, ex> ex2;
461 typedef pair<ex, bool> exbool;
464 bool operator() (const ex2 p, const ex2 q) const
466 return p.first.compare(q.first) < 0 || (!(q.first.compare(p.first) < 0) && p.second.compare(q.second) < 0);
470 typedef map<ex2, exbool, ex2_less> ex2_exbool_remember;
474 /** Exact polynomial division of a(X) by b(X) in Z[X].
475 * This functions works like divide() but the input and output polynomials are
476 * in Z[X] instead of Q[X] (i.e. they have integer coefficients). Unlike
477 * divide(), it doesnĀ“t check whether the input polynomials really are integer
478 * polynomials, so be careful of what you pass in. Also, you have to run
479 * get_symbol_stats() over the input polynomials before calling this function
480 * and pass an iterator to the first element of the sym_desc vector. This
481 * function is used internally by the heur_gcd().
483 * @param a first multivariate polynomial (dividend)
484 * @param b second multivariate polynomial (divisor)
485 * @param q quotient (returned)
486 * @param var iterator to first element of vector of sym_desc structs
487 * @return "true" when exact division succeeds (the quotient is returned in
488 * q), "false" otherwise.
489 * @see get_symbol_stats, heur_gcd */
490 static bool divide_in_z(const ex &a, const ex &b, ex &q, sym_desc_vec::const_iterator var)
494 throw(std::overflow_error("divide_in_z: division by zero"));
495 if (b.is_equal(exONE())) {
499 if (is_ex_exactly_of_type(a, numeric)) {
500 if (is_ex_exactly_of_type(b, numeric)) {
502 return q.info(info_flags::integer);
515 static ex2_exbool_remember dr_remember;
516 ex2_exbool_remember::const_iterator remembered = dr_remember.find(ex2(a, b));
517 if (remembered != dr_remember.end()) {
518 q = remembered->second.first;
519 return remembered->second.second;
524 const symbol *x = var->sym;
527 int adeg = a.degree(*x), bdeg = b.degree(*x);
533 // Polynomial long division (recursive)
539 ex blcoeff = eb.coeff(*x, bdeg);
540 while (rdeg >= bdeg) {
541 ex term, rcoeff = r.coeff(*x, rdeg);
542 if (!divide_in_z(rcoeff, blcoeff, term, var+1))
544 term = (term * power(*x, rdeg - bdeg)).expand();
546 r -= (term * eb).expand();
549 dr_remember[ex2(a, b)] = exbool(q, true);
556 dr_remember[ex2(a, b)] = exbool(q, false);
562 // Trial division using polynomial interpolation
565 // Compute values at evaluation points 0..adeg
566 vector<numeric> alpha; alpha.reserve(adeg + 1);
567 exvector u; u.reserve(adeg + 1);
568 numeric point = numZERO();
570 for (i=0; i<=adeg; i++) {
571 ex bs = b.subs(*x == point);
572 while (bs.is_zero()) {
574 bs = b.subs(*x == point);
576 if (!divide_in_z(a.subs(*x == point), bs, c, var+1))
578 alpha.push_back(point);
584 vector<numeric> rcp; rcp.reserve(adeg + 1);
586 for (k=1; k<=adeg; k++) {
587 numeric product = alpha[k] - alpha[0];
589 product *= alpha[k] - alpha[i];
590 rcp.push_back(product.inverse());
593 // Compute Newton coefficients
594 exvector v; v.reserve(adeg + 1);
596 for (k=1; k<=adeg; k++) {
598 for (i=k-2; i>=0; i--)
599 temp = temp * (alpha[k] - alpha[i]) + v[i];
600 v.push_back((u[k] - temp) * rcp[k]);
603 // Convert from Newton form to standard form
605 for (k=adeg-1; k>=0; k--)
606 c = c * (*x - alpha[k]) + v[k];
608 if (c.degree(*x) == (adeg - bdeg)) {
618 * Separation of unit part, content part and primitive part of polynomials
621 /** Compute unit part (= sign of leading coefficient) of a multivariate
622 * polynomial in Z[x]. The product of unit part, content part, and primitive
623 * part is the polynomial itself.
625 * @param x variable in which to compute the unit part
627 * @see ex::content, ex::primpart */
628 ex ex::unit(const symbol &x) const
630 ex c = expand().lcoeff(x);
631 if (is_ex_exactly_of_type(c, numeric))
632 return c < exZERO() ? exMINUSONE() : exONE();
635 if (get_first_symbol(c, y))
638 throw(std::invalid_argument("invalid expression in unit()"));
643 /** Compute content part (= unit normal GCD of all coefficients) of a
644 * multivariate polynomial in Z[x]. The product of unit part, content part,
645 * and primitive part is the polynomial itself.
647 * @param x variable in which to compute the content part
648 * @return content part
649 * @see ex::unit, ex::primpart */
650 ex ex::content(const symbol &x) const
654 if (is_ex_exactly_of_type(*this, numeric))
655 return info(info_flags::negative) ? -*this : *this;
660 // First, try the integer content
661 ex c = e.integer_content();
663 ex lcoeff = r.lcoeff(x);
664 if (lcoeff.info(info_flags::integer))
667 // GCD of all coefficients
668 int deg = e.degree(x);
669 int ldeg = e.ldegree(x);
671 return e.lcoeff(x) / e.unit(x);
673 for (int i=ldeg; i<=deg; i++)
674 c = gcd(e.coeff(x, i), c, NULL, NULL, false);
679 /** Compute primitive part of a multivariate polynomial in Z[x].
680 * The product of unit part, content part, and primitive part is the
683 * @param x variable in which to compute the primitive part
684 * @return primitive part
685 * @see ex::unit, ex::content */
686 ex ex::primpart(const symbol &x) const
690 if (is_ex_exactly_of_type(*this, numeric))
697 if (is_ex_exactly_of_type(c, numeric))
698 return *this / (c * u);
700 return quo(*this, c * u, x, false);
704 /** Compute primitive part of a multivariate polynomial in Z[x] when the
705 * content part is already known. This function is faster in computing the
706 * primitive part than the previous function.
708 * @param x variable in which to compute the primitive part
709 * @param c previously computed content part
710 * @return primitive part */
712 ex ex::primpart(const symbol &x, const ex &c) const
718 if (is_ex_exactly_of_type(*this, numeric))
722 if (is_ex_exactly_of_type(c, numeric))
723 return *this / (c * u);
725 return quo(*this, c * u, x, false);
730 * GCD of multivariate polynomials
733 /** Compute GCD of multivariate polynomials using the subresultant PRS
734 * algorithm. This function is used internally gy gcd().
736 * @param a first multivariate polynomial
737 * @param b second multivariate polynomial
738 * @param x pointer to symbol (main variable) in which to compute the GCD in
739 * @return the GCD as a new expression
742 static ex sr_gcd(const ex &a, const ex &b, const symbol *x)
744 // Sort c and d so that c has higher degree
746 int adeg = a.degree(*x), bdeg = b.degree(*x);
760 // Remove content from c and d, to be attached to GCD later
761 ex cont_c = c.content(*x);
762 ex cont_d = d.content(*x);
763 ex gamma = gcd(cont_c, cont_d, NULL, NULL, false);
766 c = c.primpart(*x, cont_c);
767 d = d.primpart(*x, cont_d);
769 // First element of subresultant sequence
770 ex r = exZERO(), ri = exONE(), psi = exONE();
771 int delta = cdeg - ddeg;
774 // Calculate polynomial pseudo-remainder
775 r = prem(c, d, *x, false);
777 return gamma * d.primpart(*x);
780 if (!divide(r, ri * power(psi, delta), d, false))
781 throw(std::runtime_error("invalid expression in sr_gcd(), division failed"));
784 if (is_ex_exactly_of_type(r, numeric))
787 return gamma * r.primpart(*x);
790 // Next element of subresultant sequence
791 ri = c.expand().lcoeff(*x);
795 divide(power(ri, delta), power(psi, delta-1), psi, false);
801 /** Return maximum (absolute value) coefficient of a polynomial.
802 * This function is used internally by heur_gcd().
804 * @param e expanded multivariate polynomial
805 * @return maximum coefficient
808 numeric ex::max_coefficient(void) const
811 return bp->max_coefficient();
814 numeric basic::max_coefficient(void) const
819 numeric numeric::max_coefficient(void) const
824 numeric add::max_coefficient(void) const
826 epvector::const_iterator it = seq.begin();
827 epvector::const_iterator itend = seq.end();
828 ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
829 numeric cur_max = abs(ex_to_numeric(overall_coeff));
830 while (it != itend) {
832 ASSERT(!is_ex_exactly_of_type(it->rest,numeric));
833 a = abs(ex_to_numeric(it->coeff));
841 numeric mul::max_coefficient(void) const
844 epvector::const_iterator it = seq.begin();
845 epvector::const_iterator itend = seq.end();
846 while (it != itend) {
847 ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*it),numeric));
850 #endif // def DOASSERT
851 ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
852 return abs(ex_to_numeric(overall_coeff));
856 /** Apply symmetric modular homomorphism to a multivariate polynomial.
857 * This function is used internally by heur_gcd().
859 * @param e expanded multivariate polynomial
861 * @return mapped polynomial
864 ex ex::smod(const numeric &xi) const
870 ex basic::smod(const numeric &xi) const
875 ex numeric::smod(const numeric &xi) const
877 return ::smod(*this, xi);
880 ex add::smod(const numeric &xi) const
883 newseq.reserve(seq.size()+1);
884 epvector::const_iterator it = seq.begin();
885 epvector::const_iterator itend = seq.end();
886 while (it != itend) {
887 ASSERT(!is_ex_exactly_of_type(it->rest,numeric));
888 numeric coeff = ::smod(ex_to_numeric(it->coeff), xi);
889 if (!coeff.is_zero())
890 newseq.push_back(expair(it->rest, coeff));
893 ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
894 numeric coeff = ::smod(ex_to_numeric(overall_coeff), xi);
895 return (new add(newseq,coeff))->setflag(status_flags::dynallocated);
898 ex mul::smod(const numeric &xi) const
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(recombine_pair_to_ex(*it),numeric));
907 #endif // def DOASSERT
908 mul * mulcopyp=new mul(*this);
909 ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
910 mulcopyp->overall_coeff=::smod(ex_to_numeric(overall_coeff),xi);
911 mulcopyp->clearflag(status_flags::evaluated);
912 mulcopyp->clearflag(status_flags::hash_calculated);
913 return mulcopyp->setflag(status_flags::dynallocated);
917 /** Exception thrown by heur_gcd() to signal failure */
918 class gcdheu_failed {};
920 /** Compute GCD of multivariate polynomials using the heuristic GCD algorithm.
921 * get_symbol_stats() must have been called previously with the input
922 * polynomials and an iterator to the first element of the sym_desc vector
923 * passed in. This function is used internally by gcd().
925 * @param a first multivariate polynomial (expanded)
926 * @param b second multivariate polynomial (expanded)
927 * @param ca cofactor of polynomial a (returned), NULL to suppress
928 * calculation of cofactor
929 * @param cb cofactor of polynomial b (returned), NULL to suppress
930 * calculation of cofactor
931 * @param var iterator to first element of vector of sym_desc structs
932 * @return the GCD as a new expression
934 * @exception gcdheu_failed() */
936 static ex heur_gcd(const ex &a, const ex &b, ex *ca, ex *cb, sym_desc_vec::const_iterator var)
938 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric)) {
939 numeric g = gcd(ex_to_numeric(a), ex_to_numeric(b));
944 *ca = ex_to_numeric(a).mul(rg);
946 *cb = ex_to_numeric(b).mul(rg);
950 // The first symbol is our main variable
951 const symbol *x = var->sym;
953 // Remove integer content
954 numeric gc = gcd(a.integer_content(), b.integer_content());
955 numeric rgc = gc.inverse();
958 int maxdeg = max(p.degree(*x), q.degree(*x));
960 // Find evaluation point
961 numeric mp = p.max_coefficient(), mq = q.max_coefficient();
964 xi = mq * numTWO() + numTWO();
966 xi = mp * numTWO() + numTWO();
969 for (int t=0; t<6; t++) {
970 if (xi.int_length() * maxdeg > 50000)
971 throw gcdheu_failed();
973 // Apply evaluation homomorphism and calculate GCD
974 ex gamma = heur_gcd(p.subs(*x == xi), q.subs(*x == xi), NULL, NULL, var+1).expand();
975 if (!is_ex_exactly_of_type(gamma, fail)) {
977 // Reconstruct polynomial from GCD of mapped polynomials
979 numeric rxi = xi.inverse();
980 for (int i=0; !gamma.is_zero(); i++) {
981 ex gi = gamma.smod(xi);
982 g += gi * power(*x, i);
983 gamma = (gamma - gi) * rxi;
985 // Remove integer content
986 g /= g.integer_content();
988 // If the calculated polynomial divides both a and b, this is the GCD
990 if (divide_in_z(p, g, ca ? *ca : dummy, var) && divide_in_z(q, g, cb ? *cb : dummy, var)) {
992 ex lc = g.lcoeff(*x);
993 if (is_ex_exactly_of_type(lc, numeric) && lc.compare(exZERO()) < 0)
1000 // Next evaluation point
1001 xi = iquo(xi * isqrt(isqrt(xi)) * numeric(73794), numeric(27011));
1003 return *new ex(fail());
1007 /** Compute GCD (Greatest Common Divisor) of multivariate polynomials a(X)
1010 * @param a first multivariate polynomial
1011 * @param b second multivariate polynomial
1012 * @param check_args check whether a and b are polynomials with rational
1013 * coefficients (defaults to "true")
1014 * @return the GCD as a new expression */
1016 ex gcd(const ex &a, const ex &b, ex *ca, ex *cb, bool check_args)
1018 // Some trivial cases
1033 if (a.is_equal(exONE()) || b.is_equal(exONE())) {
1041 if (a.is_equal(b)) {
1049 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric)) {
1050 numeric g = gcd(ex_to_numeric(a), ex_to_numeric(b));
1052 *ca = ex_to_numeric(a) / g;
1054 *cb = ex_to_numeric(b) / g;
1057 if (check_args && !a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)) {
1058 cerr << "a=" << a << endl;
1059 cerr << "b=" << b << endl;
1060 throw(std::invalid_argument("gcd: arguments must be polynomials over the rationals"));
1063 // Gather symbol statistics
1064 sym_desc_vec sym_stats;
1065 get_symbol_stats(a, b, sym_stats);
1067 // The symbol with least degree is our main variable
1068 sym_desc_vec::const_iterator var = sym_stats.begin();
1069 const symbol *x = var->sym;
1071 // Cancel trivial common factor
1072 int ldeg_a = var->ldeg_a;
1073 int ldeg_b = var->ldeg_b;
1074 int min_ldeg = min(ldeg_a, ldeg_b);
1076 ex common = power(*x, min_ldeg);
1077 //clog << "trivial common factor " << common << endl;
1078 return gcd((a / common).expand(), (b / common).expand(), ca, cb, false) * common;
1081 // Try to eliminate variables
1082 if (var->deg_a == 0) {
1083 //clog << "eliminating variable " << *x << " from b" << endl;
1084 ex c = b.content(*x);
1085 ex g = gcd(a, c, ca, cb, false);
1087 *cb *= b.unit(*x) * b.primpart(*x, c);
1089 } else if (var->deg_b == 0) {
1090 //clog << "eliminating variable " << *x << " from a" << endl;
1091 ex c = a.content(*x);
1092 ex g = gcd(c, b, ca, cb, false);
1094 *ca *= a.unit(*x) * a.primpart(*x, c);
1098 // Try heuristic algorithm first, fall back to PRS if that failed
1101 g = heur_gcd(a.expand(), b.expand(), ca, cb, var);
1102 } catch (gcdheu_failed) {
1103 g = *new ex(fail());
1105 if (is_ex_exactly_of_type(g, fail)) {
1106 //clog << "heuristics failed\n";
1107 g = sr_gcd(a, b, x);
1109 divide(a, g, *ca, false);
1111 divide(b, g, *cb, false);
1117 /** Compute LCM (Least Common Multiple) of multivariate polynomials in Z[X].
1119 * @param a first multivariate polynomial
1120 * @param b second multivariate polynomial
1121 * @param check_args check whether a and b are polynomials with rational
1122 * coefficients (defaults to "true")
1123 * @return the LCM as a new expression */
1124 ex lcm(const ex &a, const ex &b, bool check_args)
1126 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric))
1127 return gcd(ex_to_numeric(a), ex_to_numeric(b));
1128 if (check_args && !a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial))
1129 throw(std::invalid_argument("lcm: arguments must be polynomials over the rationals"));
1132 ex g = gcd(a, b, &ca, &cb, false);
1138 * Square-free factorization
1141 // Univariate GCD of polynomials in Q[x] (used internally by sqrfree()).
1142 // a and b can be multivariate polynomials but they are treated as univariate polynomials in x.
1143 static ex univariate_gcd(const ex &a, const ex &b, const symbol &x)
1149 if (a.is_equal(exONE()) || b.is_equal(exONE()))
1151 if (is_ex_of_type(a, numeric) && is_ex_of_type(b, numeric))
1152 return gcd(ex_to_numeric(a), ex_to_numeric(b));
1153 if (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial))
1154 throw(std::invalid_argument("univariate_gcd: arguments must be polynomials over the rationals"));
1156 // Euclidean algorithm
1158 if (a.degree(x) >= b.degree(x)) {
1166 r = rem(c, d, x, false);
1172 return d / d.lcoeff(x);
1176 /** Compute square-free factorization of multivariate polynomial a(x) using
1179 * @param a multivariate polynomial
1180 * @param x variable to factor in
1181 * @return factored polynomial */
1182 ex sqrfree(const ex &a, const symbol &x)
1187 ex c = univariate_gcd(a, b, x);
1189 if (c.is_equal(exONE())) {
1193 ex y = quo(b, c, x);
1194 ex z = y - w.diff(x);
1195 while (!z.is_zero()) {
1196 ex g = univariate_gcd(w, z, x);
1204 return res * power(w, i);
1209 * Normal form of rational functions
1212 // Create a symbol for replacing the expression "e" (or return a previously
1213 // assigned symbol). The symbol is appended to sym_list and returned, the
1214 // expression is appended to repl_list.
1215 static ex replace_with_symbol(const ex &e, lst &sym_lst, lst &repl_lst)
1217 // Expression already in repl_lst? Then return the assigned symbol
1218 for (int i=0; i<repl_lst.nops(); i++)
1219 if (repl_lst.op(i).is_equal(e))
1220 return sym_lst.op(i);
1222 // Otherwise create new symbol and add to list, taking care that the
1223 // replacement expression doesn't contain symbols from the sym_lst
1224 // because subs() is not recursive
1227 ex e_replaced = e.subs(sym_lst, repl_lst);
1229 repl_lst.append(e_replaced);
1234 /** Default implementation of ex::normal(). It replaces the object with a
1236 * @see ex::normal */
1237 ex basic::normal(lst &sym_lst, lst &repl_lst, int level) const
1239 return replace_with_symbol(*this, sym_lst, repl_lst);
1243 /** Implementation of ex::normal() for symbols. This returns the unmodifies symbol.
1244 * @see ex::normal */
1245 ex symbol::normal(lst &sym_lst, lst &repl_lst, int level) const
1251 /** Implementation of ex::normal() for a numeric. It splits complex numbers
1252 * into re+I*im and replaces I and non-rational real numbers with a temporary
1254 * @see ex::normal */
1255 ex numeric::normal(lst &sym_lst, lst &repl_lst, int level) const
1261 return replace_with_symbol(*this, sym_lst, repl_lst);
1263 numeric re = real(), im = imag();
1264 ex re_ex = re.is_rational() ? re : replace_with_symbol(re, sym_lst, repl_lst);
1265 ex im_ex = im.is_rational() ? im : replace_with_symbol(im, sym_lst, repl_lst);
1266 return re_ex + im_ex * replace_with_symbol(I, sym_lst, repl_lst);
1272 * Helper function for fraction cancellation (returns cancelled fraction n/d)
1275 static ex frac_cancel(const ex &n, const ex &d)
1279 ex pre_factor = exONE();
1281 // Handle special cases where numerator or denominator is 0
1284 if (den.expand().is_zero())
1285 throw(std::overflow_error("frac_cancel: division by zero in frac_cancel"));
1287 // More special cases
1288 if (is_ex_exactly_of_type(den, numeric))
1293 // Bring numerator and denominator to Z[X] by multiplying with
1294 // LCM of all coefficients' denominators
1295 ex num_lcm = lcm_of_coefficients_denominators(num);
1296 ex den_lcm = lcm_of_coefficients_denominators(den);
1299 pre_factor = den_lcm / num_lcm;
1301 // Cancel GCD from numerator and denominator
1303 if (gcd(num, den, &cnum, &cden, false) != exONE()) {
1308 // Make denominator unit normal (i.e. coefficient of first symbol
1309 // as defined by get_first_symbol() is made positive)
1311 if (get_first_symbol(den, x)) {
1312 if (den.unit(*x).compare(exZERO()) < 0) {
1313 num *= exMINUSONE();
1314 den *= exMINUSONE();
1317 return pre_factor * num / den;
1321 /** Implementation of ex::normal() for a sum. It expands terms and performs
1322 * fractional addition.
1323 * @see ex::normal */
1324 ex add::normal(lst &sym_lst, lst &repl_lst, int level) const
1326 // Normalize and expand children
1328 o.reserve(seq.size()+1);
1329 epvector::const_iterator it = seq.begin(), itend = seq.end();
1330 while (it != itend) {
1331 ex n = recombine_pair_to_ex(*it).bp->normal(sym_lst, repl_lst, level-1).expand();
1332 if (is_ex_exactly_of_type(n, add)) {
1333 epvector::const_iterator bit = (static_cast<add *>(n.bp))->seq.begin(), bitend = (static_cast<add *>(n.bp))->seq.end();
1334 while (bit != bitend) {
1335 o.push_back(recombine_pair_to_ex(*bit));
1338 o.push_back((static_cast<add *>(n.bp))->overall_coeff);
1343 o.push_back(overall_coeff.bp->normal(sym_lst, repl_lst, level-1));
1345 // Determine common denominator
1347 exvector::const_iterator ait = o.begin(), aitend = o.end();
1348 while (ait != aitend) {
1349 den = lcm((*ait).denom(false), den, false);
1354 if (den.is_equal(exONE()))
1355 return (new add(o))->setflag(status_flags::dynallocated);
1358 for (ait=o.begin(); ait!=aitend; ait++) {
1360 if (!divide(den, (*ait).denom(false), q, false)) {
1361 // should not happen
1362 throw(std::runtime_error("invalid expression in add::normal, division failed"));
1364 num_seq.push_back((*ait).numer(false) * q);
1366 ex num = add(num_seq);
1368 // Cancel common factors from num/den
1369 return frac_cancel(num, den);
1374 /** Implementation of ex::normal() for a product. It cancels common factors
1376 * @see ex::normal() */
1377 ex mul::normal(lst &sym_lst, lst &repl_lst, int level) const
1379 // Normalize children
1381 o.reserve(seq.size()+1);
1382 epvector::const_iterator it = seq.begin(), itend = seq.end();
1383 while (it != itend) {
1384 o.push_back(recombine_pair_to_ex(*it).bp->normal(sym_lst, repl_lst, level-1));
1387 o.push_back(overall_coeff.bp->normal(sym_lst, repl_lst, level-1));
1388 ex n = (new mul(o))->setflag(status_flags::dynallocated);
1389 return frac_cancel(n.numer(false), n.denom(false));
1393 /** Implementation of ex::normal() for powers. It normalizes the basis,
1394 * distributes integer exponents to numerator and denominator, and replaces
1395 * non-integer powers by temporary symbols.
1396 * @see ex::normal */
1397 ex power::normal(lst &sym_lst, lst &repl_lst, int level) const
1399 if (exponent.info(info_flags::integer)) {
1400 // Integer powers are distributed
1401 ex n = basis.bp->normal(sym_lst, repl_lst, level-1);
1402 ex num = n.numer(false);
1403 ex den = n.denom(false);
1404 return power(num, exponent) / power(den, exponent);
1406 // Non-integer powers are replaced by temporary symbol (after normalizing basis)
1407 ex n = power(basis.bp->normal(sym_lst, repl_lst, level-1), exponent);
1408 return replace_with_symbol(n, sym_lst, repl_lst);
1413 /** Implementation of ex::normal() for series. It normalizes each coefficient and
1414 * replaces the series by a temporary symbol.
1415 * @see ex::normal */
1416 ex series::normal(lst &sym_lst, lst &repl_lst, int level) const
1419 new_seq.reserve(seq.size());
1421 epvector::const_iterator it = seq.begin(), itend = seq.end();
1422 while (it != itend) {
1423 new_seq.push_back(expair(it->rest.normal(), it->coeff));
1427 ex n = series(var, point, new_seq);
1428 return replace_with_symbol(n, sym_lst, repl_lst);
1432 /** Normalization of rational functions.
1433 * This function converts an expression to its normal form
1434 * "numerator/denominator", where numerator and denominator are (relatively
1435 * prime) polynomials. Any subexpressions which are not rational functions
1436 * (like non-rational numbers, non-integer powers or functions like Sin(),
1437 * Cos() etc.) are replaced by temporary symbols which are re-substituted by
1438 * the (normalized) subexpressions before normal() returns (this way, any
1439 * expression can be treated as a rational function). normal() is applied
1440 * recursively to arguments of functions etc.
1442 * @param level maximum depth of recursion
1443 * @return normalized expression */
1444 ex ex::normal(int level) const
1446 lst sym_lst, repl_lst;
1447 ex e = bp->normal(sym_lst, repl_lst, level);
1448 if (sym_lst.nops() > 0)
1449 return e.subs(sym_lst, repl_lst);