3 * This file implements several functions that work on univariate and
4 * multivariate polynomials and rational functions.
5 * These functions include polynomial quotient and remainder, GCD and LCM
6 * computation, square-free factorization and rational function normalization. */
9 * GiNaC Copyright (C) 1999-2002 Johannes Gutenberg University Mainz, Germany
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
21 * You should have received a copy of the GNU General Public License
22 * along with this program; if not, write to the Free Software
23 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
34 #include "expairseq.h"
41 #include "relational.h"
49 // If comparing expressions (ex::compare()) is fast, you can set this to 1.
50 // Some routines like quo(), rem() and gcd() will then return a quick answer
51 // when they are called with two identical arguments.
52 #define FAST_COMPARE 1
54 // Set this if you want divide_in_z() to use remembering
55 #define USE_REMEMBER 0
57 // Set this if you want divide_in_z() to use trial division followed by
58 // polynomial interpolation (always slower except for completely dense
60 #define USE_TRIAL_DIVISION 0
62 // Set this to enable some statistical output for the GCD routines
67 // Statistics variables
68 static int gcd_called = 0;
69 static int sr_gcd_called = 0;
70 static int heur_gcd_called = 0;
71 static int heur_gcd_failed = 0;
73 // Print statistics at end of program
74 static struct _stat_print {
77 std::cout << "gcd() called " << gcd_called << " times\n";
78 std::cout << "sr_gcd() called " << sr_gcd_called << " times\n";
79 std::cout << "heur_gcd() called " << heur_gcd_called << " times\n";
80 std::cout << "heur_gcd() failed " << heur_gcd_failed << " times\n";
86 /** Return pointer to first symbol found in expression. Due to GiNaCĀ“s
87 * internal ordering of terms, it may not be obvious which symbol this
88 * function returns for a given expression.
90 * @param e expression to search
91 * @param x pointer to first symbol found (returned)
92 * @return "false" if no symbol was found, "true" otherwise */
93 static bool get_first_symbol(const ex &e, const symbol *&x)
95 if (is_ex_exactly_of_type(e, symbol)) {
96 x = &ex_to<symbol>(e);
98 } else if (is_ex_exactly_of_type(e, add) || is_ex_exactly_of_type(e, mul)) {
99 for (unsigned i=0; i<e.nops(); i++)
100 if (get_first_symbol(e.op(i), x))
102 } else if (is_ex_exactly_of_type(e, power)) {
103 if (get_first_symbol(e.op(0), x))
111 * Statistical information about symbols in polynomials
114 /** This structure holds information about the highest and lowest degrees
115 * in which a symbol appears in two multivariate polynomials "a" and "b".
116 * A vector of these structures with information about all symbols in
117 * two polynomials can be created with the function get_symbol_stats().
119 * @see get_symbol_stats */
121 /** Pointer to symbol */
124 /** Highest degree of symbol in polynomial "a" */
127 /** Highest degree of symbol in polynomial "b" */
130 /** Lowest degree of symbol in polynomial "a" */
133 /** Lowest degree of symbol in polynomial "b" */
136 /** Maximum of deg_a and deg_b (Used for sorting) */
139 /** Maximum number of terms of leading coefficient of symbol in both polynomials */
142 /** Commparison operator for sorting */
143 bool operator<(const sym_desc &x) const
145 if (max_deg == x.max_deg)
146 return max_lcnops < x.max_lcnops;
148 return max_deg < x.max_deg;
152 // Vector of sym_desc structures
153 typedef std::vector<sym_desc> sym_desc_vec;
155 // Add symbol the sym_desc_vec (used internally by get_symbol_stats())
156 static void add_symbol(const symbol *s, sym_desc_vec &v)
158 sym_desc_vec::const_iterator it = v.begin(), itend = v.end();
159 while (it != itend) {
160 if (it->sym->compare(*s) == 0) // If it's already in there, don't add it a second time
169 // Collect all symbols of an expression (used internally by get_symbol_stats())
170 static void collect_symbols(const ex &e, sym_desc_vec &v)
172 if (is_ex_exactly_of_type(e, symbol)) {
173 add_symbol(&ex_to<symbol>(e), v);
174 } else if (is_ex_exactly_of_type(e, add) || is_ex_exactly_of_type(e, mul)) {
175 for (unsigned i=0; i<e.nops(); i++)
176 collect_symbols(e.op(i), v);
177 } else if (is_ex_exactly_of_type(e, power)) {
178 collect_symbols(e.op(0), v);
182 /** Collect statistical information about symbols in polynomials.
183 * This function fills in a vector of "sym_desc" structs which contain
184 * information about the highest and lowest degrees of all symbols that
185 * appear in two polynomials. The vector is then sorted by minimum
186 * degree (lowest to highest). The information gathered by this
187 * function is used by the GCD routines to identify trivial factors
188 * and to determine which variable to choose as the main variable
189 * for GCD computation.
191 * @param a first multivariate polynomial
192 * @param b second multivariate polynomial
193 * @param v vector of sym_desc structs (filled in) */
194 static void get_symbol_stats(const ex &a, const ex &b, sym_desc_vec &v)
196 collect_symbols(a.eval(), v); // eval() to expand assigned symbols
197 collect_symbols(b.eval(), v);
198 sym_desc_vec::iterator it = v.begin(), itend = v.end();
199 while (it != itend) {
200 int deg_a = a.degree(*(it->sym));
201 int deg_b = b.degree(*(it->sym));
204 it->max_deg = std::max(deg_a, deg_b);
205 it->max_lcnops = std::max(a.lcoeff(*(it->sym)).nops(), b.lcoeff(*(it->sym)).nops());
206 it->ldeg_a = a.ldegree(*(it->sym));
207 it->ldeg_b = b.ldegree(*(it->sym));
210 std::sort(v.begin(), v.end());
212 std::clog << "Symbols:\n";
213 it = v.begin(); itend = v.end();
214 while (it != itend) {
215 std::clog << " " << *it->sym << ": deg_a=" << it->deg_a << ", deg_b=" << it->deg_b << ", ldeg_a=" << it->ldeg_a << ", ldeg_b=" << it->ldeg_b << ", max_deg=" << it->max_deg << ", max_lcnops=" << it->max_lcnops << endl;
216 std::clog << " lcoeff_a=" << a.lcoeff(*(it->sym)) << ", lcoeff_b=" << b.lcoeff(*(it->sym)) << endl;
224 * Computation of LCM of denominators of coefficients of a polynomial
227 // Compute LCM of denominators of coefficients by going through the
228 // expression recursively (used internally by lcm_of_coefficients_denominators())
229 static numeric lcmcoeff(const ex &e, const numeric &l)
231 if (e.info(info_flags::rational))
232 return lcm(ex_to<numeric>(e).denom(), l);
233 else if (is_ex_exactly_of_type(e, add)) {
235 for (unsigned i=0; i<e.nops(); i++)
236 c = lcmcoeff(e.op(i), c);
238 } else if (is_ex_exactly_of_type(e, mul)) {
240 for (unsigned i=0; i<e.nops(); i++)
241 c *= lcmcoeff(e.op(i), _num1);
243 } else if (is_ex_exactly_of_type(e, power)) {
244 if (is_ex_exactly_of_type(e.op(0), symbol))
247 return pow(lcmcoeff(e.op(0), l), ex_to<numeric>(e.op(1)));
252 /** Compute LCM of denominators of coefficients of a polynomial.
253 * Given a polynomial with rational coefficients, this function computes
254 * the LCM of the denominators of all coefficients. This can be used
255 * to bring a polynomial from Q[X] to Z[X].
257 * @param e multivariate polynomial (need not be expanded)
258 * @return LCM of denominators of coefficients */
259 static numeric lcm_of_coefficients_denominators(const ex &e)
261 return lcmcoeff(e, _num1);
264 /** Bring polynomial from Q[X] to Z[X] by multiplying in the previously
265 * determined LCM of the coefficient's denominators.
267 * @param e multivariate polynomial (need not be expanded)
268 * @param lcm LCM to multiply in */
269 static ex multiply_lcm(const ex &e, const numeric &lcm)
271 if (is_ex_exactly_of_type(e, mul)) {
272 unsigned num = e.nops();
273 exvector v; v.reserve(num + 1);
274 numeric lcm_accum = _num1;
275 for (unsigned i=0; i<e.nops(); i++) {
276 numeric op_lcm = lcmcoeff(e.op(i), _num1);
277 v.push_back(multiply_lcm(e.op(i), op_lcm));
280 v.push_back(lcm / lcm_accum);
281 return (new mul(v))->setflag(status_flags::dynallocated);
282 } else if (is_ex_exactly_of_type(e, add)) {
283 unsigned num = e.nops();
284 exvector v; v.reserve(num);
285 for (unsigned i=0; i<num; i++)
286 v.push_back(multiply_lcm(e.op(i), lcm));
287 return (new add(v))->setflag(status_flags::dynallocated);
288 } else if (is_ex_exactly_of_type(e, power)) {
289 if (is_ex_exactly_of_type(e.op(0), symbol))
292 return pow(multiply_lcm(e.op(0), lcm.power(ex_to<numeric>(e.op(1)).inverse())), e.op(1));
298 /** Compute the integer content (= GCD of all numeric coefficients) of an
299 * expanded polynomial.
301 * @param e expanded polynomial
302 * @return integer content */
303 numeric ex::integer_content(void) const
306 return bp->integer_content();
309 numeric basic::integer_content(void) const
314 numeric numeric::integer_content(void) const
319 numeric add::integer_content(void) const
321 epvector::const_iterator it = seq.begin();
322 epvector::const_iterator itend = seq.end();
324 while (it != itend) {
325 GINAC_ASSERT(!is_exactly_a<numeric>(it->rest));
326 GINAC_ASSERT(is_exactly_a<numeric>(it->coeff));
327 c = gcd(ex_to<numeric>(it->coeff), c);
330 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
331 c = gcd(ex_to<numeric>(overall_coeff),c);
335 numeric mul::integer_content(void) const
337 #ifdef DO_GINAC_ASSERT
338 epvector::const_iterator it = seq.begin();
339 epvector::const_iterator itend = seq.end();
340 while (it != itend) {
341 GINAC_ASSERT(!is_exactly_a<numeric>(recombine_pair_to_ex(*it)));
344 #endif // def DO_GINAC_ASSERT
345 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
346 return abs(ex_to<numeric>(overall_coeff));
351 * Polynomial quotients and remainders
354 /** Quotient q(x) of polynomials a(x) and b(x) in Q[x].
355 * It satisfies a(x)=b(x)*q(x)+r(x).
357 * @param a first polynomial in x (dividend)
358 * @param b second polynomial in x (divisor)
359 * @param x a and b are polynomials in x
360 * @param check_args check whether a and b are polynomials with rational
361 * coefficients (defaults to "true")
362 * @return quotient of a and b in Q[x] */
363 ex quo(const ex &a, const ex &b, const symbol &x, bool check_args)
366 throw(std::overflow_error("quo: division by zero"));
367 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric))
373 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
374 throw(std::invalid_argument("quo: arguments must be polynomials over the rationals"));
376 // Polynomial long division
380 int bdeg = b.degree(x);
381 int rdeg = r.degree(x);
382 ex blcoeff = b.expand().coeff(x, bdeg);
383 bool blcoeff_is_numeric = is_ex_exactly_of_type(blcoeff, numeric);
384 exvector v; v.reserve(std::max(rdeg - bdeg + 1, 0));
385 while (rdeg >= bdeg) {
386 ex term, rcoeff = r.coeff(x, rdeg);
387 if (blcoeff_is_numeric)
388 term = rcoeff / blcoeff;
390 if (!divide(rcoeff, blcoeff, term, false))
391 return (new fail())->setflag(status_flags::dynallocated);
393 term *= power(x, rdeg - bdeg);
395 r -= (term * b).expand();
400 return (new add(v))->setflag(status_flags::dynallocated);
404 /** Remainder r(x) of polynomials a(x) and b(x) in Q[x].
405 * It satisfies a(x)=b(x)*q(x)+r(x).
407 * @param a first polynomial in x (dividend)
408 * @param b second polynomial in x (divisor)
409 * @param x a and b are polynomials in x
410 * @param check_args check whether a and b are polynomials with rational
411 * coefficients (defaults to "true")
412 * @return remainder of a(x) and b(x) in Q[x] */
413 ex rem(const ex &a, const ex &b, const symbol &x, bool check_args)
416 throw(std::overflow_error("rem: division by zero"));
417 if (is_ex_exactly_of_type(a, numeric)) {
418 if (is_ex_exactly_of_type(b, numeric))
427 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
428 throw(std::invalid_argument("rem: arguments must be polynomials over the rationals"));
430 // Polynomial long division
434 int bdeg = b.degree(x);
435 int rdeg = r.degree(x);
436 ex blcoeff = b.expand().coeff(x, bdeg);
437 bool blcoeff_is_numeric = is_ex_exactly_of_type(blcoeff, numeric);
438 while (rdeg >= bdeg) {
439 ex term, rcoeff = r.coeff(x, rdeg);
440 if (blcoeff_is_numeric)
441 term = rcoeff / blcoeff;
443 if (!divide(rcoeff, blcoeff, term, false))
444 return (new fail())->setflag(status_flags::dynallocated);
446 term *= power(x, rdeg - bdeg);
447 r -= (term * b).expand();
456 /** Decompose rational function a(x)=N(x)/D(x) into P(x)+n(x)/D(x)
457 * with degree(n, x) < degree(D, x).
459 * @param a rational function in x
460 * @param x a is a function of x
461 * @return decomposed function. */
462 ex decomp_rational(const ex &a, const symbol &x)
464 ex nd = numer_denom(a);
465 ex numer = nd.op(0), denom = nd.op(1);
466 ex q = quo(numer, denom, x);
467 if (is_ex_exactly_of_type(q, fail))
470 return q + rem(numer, denom, x) / denom;
474 /** Pseudo-remainder of polynomials a(x) and b(x) in Q[x].
476 * @param a first polynomial in x (dividend)
477 * @param b second polynomial in x (divisor)
478 * @param x a and b are polynomials in x
479 * @param check_args check whether a and b are polynomials with rational
480 * coefficients (defaults to "true")
481 * @return pseudo-remainder of a(x) and b(x) in Q[x] */
482 ex prem(const ex &a, const ex &b, const symbol &x, bool check_args)
485 throw(std::overflow_error("prem: division by zero"));
486 if (is_ex_exactly_of_type(a, numeric)) {
487 if (is_ex_exactly_of_type(b, numeric))
492 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
493 throw(std::invalid_argument("prem: arguments must be polynomials over the rationals"));
495 // Polynomial long division
498 int rdeg = r.degree(x);
499 int bdeg = eb.degree(x);
502 blcoeff = eb.coeff(x, bdeg);
506 eb -= blcoeff * power(x, bdeg);
510 int delta = rdeg - bdeg + 1, i = 0;
511 while (rdeg >= bdeg && !r.is_zero()) {
512 ex rlcoeff = r.coeff(x, rdeg);
513 ex term = (power(x, rdeg - bdeg) * eb * rlcoeff).expand();
517 r -= rlcoeff * power(x, rdeg);
518 r = (blcoeff * r).expand() - term;
522 return power(blcoeff, delta - i) * r;
526 /** Sparse pseudo-remainder of polynomials a(x) and b(x) in Q[x].
528 * @param a first polynomial in x (dividend)
529 * @param b second polynomial in x (divisor)
530 * @param x a and b are polynomials in x
531 * @param check_args check whether a and b are polynomials with rational
532 * coefficients (defaults to "true")
533 * @return sparse pseudo-remainder of a(x) and b(x) in Q[x] */
534 ex sprem(const ex &a, const ex &b, const symbol &x, bool check_args)
537 throw(std::overflow_error("prem: division by zero"));
538 if (is_ex_exactly_of_type(a, numeric)) {
539 if (is_ex_exactly_of_type(b, numeric))
544 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
545 throw(std::invalid_argument("prem: arguments must be polynomials over the rationals"));
547 // Polynomial long division
550 int rdeg = r.degree(x);
551 int bdeg = eb.degree(x);
554 blcoeff = eb.coeff(x, bdeg);
558 eb -= blcoeff * power(x, bdeg);
562 while (rdeg >= bdeg && !r.is_zero()) {
563 ex rlcoeff = r.coeff(x, rdeg);
564 ex term = (power(x, rdeg - bdeg) * eb * rlcoeff).expand();
568 r -= rlcoeff * power(x, rdeg);
569 r = (blcoeff * r).expand() - term;
576 /** Exact polynomial division of a(X) by b(X) in Q[X].
578 * @param a first multivariate polynomial (dividend)
579 * @param b second multivariate polynomial (divisor)
580 * @param q quotient (returned)
581 * @param check_args check whether a and b are polynomials with rational
582 * coefficients (defaults to "true")
583 * @return "true" when exact division succeeds (quotient returned in q),
584 * "false" otherwise (q left untouched) */
585 bool divide(const ex &a, const ex &b, ex &q, bool check_args)
588 throw(std::overflow_error("divide: division by zero"));
593 if (is_ex_exactly_of_type(b, numeric)) {
596 } else if (is_ex_exactly_of_type(a, numeric))
604 if (check_args && (!a.info(info_flags::rational_polynomial) ||
605 !b.info(info_flags::rational_polynomial)))
606 throw(std::invalid_argument("divide: arguments must be polynomials over the rationals"));
610 if (!get_first_symbol(a, x) && !get_first_symbol(b, x))
611 throw(std::invalid_argument("invalid expression in divide()"));
613 // Polynomial long division (recursive)
619 int bdeg = b.degree(*x);
620 int rdeg = r.degree(*x);
621 ex blcoeff = b.expand().coeff(*x, bdeg);
622 bool blcoeff_is_numeric = is_ex_exactly_of_type(blcoeff, numeric);
623 exvector v; v.reserve(std::max(rdeg - bdeg + 1, 0));
624 while (rdeg >= bdeg) {
625 ex term, rcoeff = r.coeff(*x, rdeg);
626 if (blcoeff_is_numeric)
627 term = rcoeff / blcoeff;
629 if (!divide(rcoeff, blcoeff, term, false))
631 term *= power(*x, rdeg - bdeg);
633 r -= (term * b).expand();
635 q = (new add(v))->setflag(status_flags::dynallocated);
649 typedef std::pair<ex, ex> ex2;
650 typedef std::pair<ex, bool> exbool;
653 bool operator() (const ex2 &p, const ex2 &q) const
655 int cmp = p.first.compare(q.first);
656 return ((cmp<0) || (!(cmp>0) && p.second.compare(q.second)<0));
660 typedef std::map<ex2, exbool, ex2_less> ex2_exbool_remember;
664 /** Exact polynomial division of a(X) by b(X) in Z[X].
665 * This functions works like divide() but the input and output polynomials are
666 * in Z[X] instead of Q[X] (i.e. they have integer coefficients). Unlike
667 * divide(), it doesnĀ“t check whether the input polynomials really are integer
668 * polynomials, so be careful of what you pass in. Also, you have to run
669 * get_symbol_stats() over the input polynomials before calling this function
670 * and pass an iterator to the first element of the sym_desc vector. This
671 * function is used internally by the heur_gcd().
673 * @param a first multivariate polynomial (dividend)
674 * @param b second multivariate polynomial (divisor)
675 * @param q quotient (returned)
676 * @param var iterator to first element of vector of sym_desc structs
677 * @return "true" when exact division succeeds (the quotient is returned in
678 * q), "false" otherwise.
679 * @see get_symbol_stats, heur_gcd */
680 static bool divide_in_z(const ex &a, const ex &b, ex &q, sym_desc_vec::const_iterator var)
684 throw(std::overflow_error("divide_in_z: division by zero"));
685 if (b.is_equal(_ex1)) {
689 if (is_ex_exactly_of_type(a, numeric)) {
690 if (is_ex_exactly_of_type(b, numeric)) {
692 return q.info(info_flags::integer);
705 static ex2_exbool_remember dr_remember;
706 ex2_exbool_remember::const_iterator remembered = dr_remember.find(ex2(a, b));
707 if (remembered != dr_remember.end()) {
708 q = remembered->second.first;
709 return remembered->second.second;
714 const symbol *x = var->sym;
717 int adeg = a.degree(*x), bdeg = b.degree(*x);
721 #if USE_TRIAL_DIVISION
723 // Trial division with polynomial interpolation
726 // Compute values at evaluation points 0..adeg
727 vector<numeric> alpha; alpha.reserve(adeg + 1);
728 exvector u; u.reserve(adeg + 1);
729 numeric point = _num0;
731 for (i=0; i<=adeg; i++) {
732 ex bs = b.subs(*x == point);
733 while (bs.is_zero()) {
735 bs = b.subs(*x == point);
737 if (!divide_in_z(a.subs(*x == point), bs, c, var+1))
739 alpha.push_back(point);
745 vector<numeric> rcp; rcp.reserve(adeg + 1);
746 rcp.push_back(_num0);
747 for (k=1; k<=adeg; k++) {
748 numeric product = alpha[k] - alpha[0];
750 product *= alpha[k] - alpha[i];
751 rcp.push_back(product.inverse());
754 // Compute Newton coefficients
755 exvector v; v.reserve(adeg + 1);
757 for (k=1; k<=adeg; k++) {
759 for (i=k-2; i>=0; i--)
760 temp = temp * (alpha[k] - alpha[i]) + v[i];
761 v.push_back((u[k] - temp) * rcp[k]);
764 // Convert from Newton form to standard form
766 for (k=adeg-1; k>=0; k--)
767 c = c * (*x - alpha[k]) + v[k];
769 if (c.degree(*x) == (adeg - bdeg)) {
777 // Polynomial long division (recursive)
783 ex blcoeff = eb.coeff(*x, bdeg);
784 exvector v; v.reserve(std::max(rdeg - bdeg + 1, 0));
785 while (rdeg >= bdeg) {
786 ex term, rcoeff = r.coeff(*x, rdeg);
787 if (!divide_in_z(rcoeff, blcoeff, term, var+1))
789 term = (term * power(*x, rdeg - bdeg)).expand();
791 r -= (term * eb).expand();
793 q = (new add(v))->setflag(status_flags::dynallocated);
795 dr_remember[ex2(a, b)] = exbool(q, true);
802 dr_remember[ex2(a, b)] = exbool(q, false);
811 * Separation of unit part, content part and primitive part of polynomials
814 /** Compute unit part (= sign of leading coefficient) of a multivariate
815 * polynomial in Z[x]. The product of unit part, content part, and primitive
816 * part is the polynomial itself.
818 * @param x variable in which to compute the unit part
820 * @see ex::content, ex::primpart */
821 ex ex::unit(const symbol &x) const
823 ex c = expand().lcoeff(x);
824 if (is_ex_exactly_of_type(c, numeric))
825 return c < _ex0 ? _ex_1 : _ex1;
828 if (get_first_symbol(c, y))
831 throw(std::invalid_argument("invalid expression in unit()"));
836 /** Compute content part (= unit normal GCD of all coefficients) of a
837 * multivariate polynomial in Z[x]. The product of unit part, content part,
838 * and primitive part is the polynomial itself.
840 * @param x variable in which to compute the content part
841 * @return content part
842 * @see ex::unit, ex::primpart */
843 ex ex::content(const symbol &x) const
847 if (is_ex_exactly_of_type(*this, numeric))
848 return info(info_flags::negative) ? -*this : *this;
853 // First, try the integer content
854 ex c = e.integer_content();
856 ex lcoeff = r.lcoeff(x);
857 if (lcoeff.info(info_flags::integer))
860 // GCD of all coefficients
861 int deg = e.degree(x);
862 int ldeg = e.ldegree(x);
864 return e.lcoeff(x) / e.unit(x);
866 for (int i=ldeg; i<=deg; i++)
867 c = gcd(e.coeff(x, i), c, NULL, NULL, false);
872 /** Compute primitive part of a multivariate polynomial in Z[x].
873 * The product of unit part, content part, and primitive part is the
876 * @param x variable in which to compute the primitive part
877 * @return primitive part
878 * @see ex::unit, ex::content */
879 ex ex::primpart(const symbol &x) const
883 if (is_ex_exactly_of_type(*this, numeric))
890 if (is_ex_exactly_of_type(c, numeric))
891 return *this / (c * u);
893 return quo(*this, c * u, x, false);
897 /** Compute primitive part of a multivariate polynomial in Z[x] when the
898 * content part is already known. This function is faster in computing the
899 * primitive part than the previous function.
901 * @param x variable in which to compute the primitive part
902 * @param c previously computed content part
903 * @return primitive part */
904 ex ex::primpart(const symbol &x, const ex &c) const
910 if (is_ex_exactly_of_type(*this, numeric))
914 if (is_ex_exactly_of_type(c, numeric))
915 return *this / (c * u);
917 return quo(*this, c * u, x, false);
922 * GCD of multivariate polynomials
925 /** Compute GCD of polynomials in Q[X] using the Euclidean algorithm (not
926 * really suited for multivariate GCDs). This function is only provided for
929 * @param a first multivariate polynomial
930 * @param b second multivariate polynomial
931 * @param x pointer to symbol (main variable) in which to compute the GCD in
932 * @return the GCD as a new expression
935 static ex eu_gcd(const ex &a, const ex &b, const symbol *x)
937 //std::clog << "eu_gcd(" << a << "," << b << ")\n";
939 // Sort c and d so that c has higher degree
941 int adeg = a.degree(*x), bdeg = b.degree(*x);
951 c = c / c.lcoeff(*x);
952 d = d / d.lcoeff(*x);
954 // Euclidean algorithm
957 //std::clog << " d = " << d << endl;
958 r = rem(c, d, *x, false);
960 return d / d.lcoeff(*x);
967 /** Compute GCD of multivariate polynomials using the Euclidean PRS algorithm
968 * with pseudo-remainders ("World's Worst GCD Algorithm", staying in Z[X]).
969 * This function is only provided for testing purposes.
971 * @param a first multivariate polynomial
972 * @param b second multivariate polynomial
973 * @param x pointer to symbol (main variable) in which to compute the GCD in
974 * @return the GCD as a new expression
977 static ex euprem_gcd(const ex &a, const ex &b, const symbol *x)
979 //std::clog << "euprem_gcd(" << a << "," << b << ")\n";
981 // Sort c and d so that c has higher degree
983 int adeg = a.degree(*x), bdeg = b.degree(*x);
992 // Calculate GCD of contents
993 ex gamma = gcd(c.content(*x), d.content(*x), NULL, NULL, false);
995 // Euclidean algorithm with pseudo-remainders
998 //std::clog << " d = " << d << endl;
999 r = prem(c, d, *x, false);
1001 return d.primpart(*x) * gamma;
1008 /** Compute GCD of multivariate polynomials using the primitive Euclidean
1009 * PRS algorithm (complete content removal at each step). This function is
1010 * only provided for testing purposes.
1012 * @param a first multivariate polynomial
1013 * @param b second multivariate polynomial
1014 * @param x pointer to symbol (main variable) in which to compute the GCD in
1015 * @return the GCD as a new expression
1018 static ex peu_gcd(const ex &a, const ex &b, const symbol *x)
1020 //std::clog << "peu_gcd(" << a << "," << b << ")\n";
1022 // Sort c and d so that c has higher degree
1024 int adeg = a.degree(*x), bdeg = b.degree(*x);
1036 // Remove content from c and d, to be attached to GCD later
1037 ex cont_c = c.content(*x);
1038 ex cont_d = d.content(*x);
1039 ex gamma = gcd(cont_c, cont_d, NULL, NULL, false);
1042 c = c.primpart(*x, cont_c);
1043 d = d.primpart(*x, cont_d);
1045 // Euclidean algorithm with content removal
1048 //std::clog << " d = " << d << endl;
1049 r = prem(c, d, *x, false);
1058 /** Compute GCD of multivariate polynomials using the reduced PRS algorithm.
1059 * This function is only provided for testing purposes.
1061 * @param a first multivariate polynomial
1062 * @param b second multivariate polynomial
1063 * @param x pointer to symbol (main variable) in which to compute the GCD in
1064 * @return the GCD as a new expression
1067 static ex red_gcd(const ex &a, const ex &b, const symbol *x)
1069 //std::clog << "red_gcd(" << a << "," << b << ")\n";
1071 // Sort c and d so that c has higher degree
1073 int adeg = a.degree(*x), bdeg = b.degree(*x);
1087 // Remove content from c and d, to be attached to GCD later
1088 ex cont_c = c.content(*x);
1089 ex cont_d = d.content(*x);
1090 ex gamma = gcd(cont_c, cont_d, NULL, NULL, false);
1093 c = c.primpart(*x, cont_c);
1094 d = d.primpart(*x, cont_d);
1096 // First element of divisor sequence
1098 int delta = cdeg - ddeg;
1101 // Calculate polynomial pseudo-remainder
1102 //std::clog << " d = " << d << endl;
1103 r = prem(c, d, *x, false);
1105 return gamma * d.primpart(*x);
1109 if (!divide(r, pow(ri, delta), d, false))
1110 throw(std::runtime_error("invalid expression in red_gcd(), division failed"));
1111 ddeg = d.degree(*x);
1113 if (is_ex_exactly_of_type(r, numeric))
1116 return gamma * r.primpart(*x);
1119 ri = c.expand().lcoeff(*x);
1120 delta = cdeg - ddeg;
1125 /** Compute GCD of multivariate polynomials using the subresultant PRS
1126 * algorithm. This function is used internally by gcd().
1128 * @param a first multivariate polynomial
1129 * @param b second multivariate polynomial
1130 * @param var iterator to first element of vector of sym_desc structs
1131 * @return the GCD as a new expression
1134 static ex sr_gcd(const ex &a, const ex &b, sym_desc_vec::const_iterator var)
1136 //std::clog << "sr_gcd(" << a << "," << b << ")\n";
1141 // The first symbol is our main variable
1142 const symbol &x = *(var->sym);
1144 // Sort c and d so that c has higher degree
1146 int adeg = a.degree(x), bdeg = b.degree(x);
1160 // Remove content from c and d, to be attached to GCD later
1161 ex cont_c = c.content(x);
1162 ex cont_d = d.content(x);
1163 ex gamma = gcd(cont_c, cont_d, NULL, NULL, false);
1166 c = c.primpart(x, cont_c);
1167 d = d.primpart(x, cont_d);
1168 //std::clog << " content " << gamma << " removed, continuing with sr_gcd(" << c << "," << d << ")\n";
1170 // First element of subresultant sequence
1171 ex r = _ex0, ri = _ex1, psi = _ex1;
1172 int delta = cdeg - ddeg;
1175 // Calculate polynomial pseudo-remainder
1176 //std::clog << " start of loop, psi = " << psi << ", calculating pseudo-remainder...\n";
1177 //std::clog << " d = " << d << endl;
1178 r = prem(c, d, x, false);
1180 return gamma * d.primpart(x);
1183 //std::clog << " dividing...\n";
1184 if (!divide_in_z(r, ri * pow(psi, delta), d, var))
1185 throw(std::runtime_error("invalid expression in sr_gcd(), division failed"));
1188 if (is_ex_exactly_of_type(r, numeric))
1191 return gamma * r.primpart(x);
1194 // Next element of subresultant sequence
1195 //std::clog << " calculating next subresultant...\n";
1196 ri = c.expand().lcoeff(x);
1200 divide_in_z(pow(ri, delta), pow(psi, delta-1), psi, var+1);
1201 delta = cdeg - ddeg;
1206 /** Return maximum (absolute value) coefficient of a polynomial.
1207 * This function is used internally by heur_gcd().
1209 * @param e expanded multivariate polynomial
1210 * @return maximum coefficient
1212 numeric ex::max_coefficient(void) const
1214 GINAC_ASSERT(bp!=0);
1215 return bp->max_coefficient();
1218 /** Implementation ex::max_coefficient().
1220 numeric basic::max_coefficient(void) const
1225 numeric numeric::max_coefficient(void) const
1230 numeric add::max_coefficient(void) const
1232 epvector::const_iterator it = seq.begin();
1233 epvector::const_iterator itend = seq.end();
1234 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
1235 numeric cur_max = abs(ex_to<numeric>(overall_coeff));
1236 while (it != itend) {
1238 GINAC_ASSERT(!is_exactly_a<numeric>(it->rest));
1239 a = abs(ex_to<numeric>(it->coeff));
1247 numeric mul::max_coefficient(void) const
1249 #ifdef DO_GINAC_ASSERT
1250 epvector::const_iterator it = seq.begin();
1251 epvector::const_iterator itend = seq.end();
1252 while (it != itend) {
1253 GINAC_ASSERT(!is_exactly_a<numeric>(recombine_pair_to_ex(*it)));
1256 #endif // def DO_GINAC_ASSERT
1257 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
1258 return abs(ex_to<numeric>(overall_coeff));
1262 /** Apply symmetric modular homomorphism to an expanded multivariate
1263 * polynomial. This function is usually used internally by heur_gcd().
1266 * @return mapped polynomial
1268 ex basic::smod(const numeric &xi) const
1273 ex numeric::smod(const numeric &xi) const
1275 return GiNaC::smod(*this, xi);
1278 ex add::smod(const numeric &xi) const
1281 newseq.reserve(seq.size()+1);
1282 epvector::const_iterator it = seq.begin();
1283 epvector::const_iterator itend = seq.end();
1284 while (it != itend) {
1285 GINAC_ASSERT(!is_exactly_a<numeric>(it->rest));
1286 numeric coeff = GiNaC::smod(ex_to<numeric>(it->coeff), xi);
1287 if (!coeff.is_zero())
1288 newseq.push_back(expair(it->rest, coeff));
1291 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
1292 numeric coeff = GiNaC::smod(ex_to<numeric>(overall_coeff), xi);
1293 return (new add(newseq,coeff))->setflag(status_flags::dynallocated);
1296 ex mul::smod(const numeric &xi) const
1298 #ifdef DO_GINAC_ASSERT
1299 epvector::const_iterator it = seq.begin();
1300 epvector::const_iterator itend = seq.end();
1301 while (it != itend) {
1302 GINAC_ASSERT(!is_exactly_a<numeric>(recombine_pair_to_ex(*it)));
1305 #endif // def DO_GINAC_ASSERT
1306 mul * mulcopyp = new mul(*this);
1307 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
1308 mulcopyp->overall_coeff = GiNaC::smod(ex_to<numeric>(overall_coeff),xi);
1309 mulcopyp->clearflag(status_flags::evaluated);
1310 mulcopyp->clearflag(status_flags::hash_calculated);
1311 return mulcopyp->setflag(status_flags::dynallocated);
1315 /** xi-adic polynomial interpolation */
1316 static ex interpolate(const ex &gamma, const numeric &xi, const symbol &x, int degree_hint = 1)
1318 exvector g; g.reserve(degree_hint);
1320 numeric rxi = xi.inverse();
1321 for (int i=0; !e.is_zero(); i++) {
1323 g.push_back(gi * power(x, i));
1326 return (new add(g))->setflag(status_flags::dynallocated);
1329 /** Exception thrown by heur_gcd() to signal failure. */
1330 class gcdheu_failed {};
1332 /** Compute GCD of multivariate polynomials using the heuristic GCD algorithm.
1333 * get_symbol_stats() must have been called previously with the input
1334 * polynomials and an iterator to the first element of the sym_desc vector
1335 * passed in. This function is used internally by gcd().
1337 * @param a first multivariate polynomial (expanded)
1338 * @param b second multivariate polynomial (expanded)
1339 * @param ca cofactor of polynomial a (returned), NULL to suppress
1340 * calculation of cofactor
1341 * @param cb cofactor of polynomial b (returned), NULL to suppress
1342 * calculation of cofactor
1343 * @param var iterator to first element of vector of sym_desc structs
1344 * @return the GCD as a new expression
1346 * @exception gcdheu_failed() */
1347 static ex heur_gcd(const ex &a, const ex &b, ex *ca, ex *cb, sym_desc_vec::const_iterator var)
1349 //std::clog << "heur_gcd(" << a << "," << b << ")\n";
1354 // Algorithm only works for non-vanishing input polynomials
1355 if (a.is_zero() || b.is_zero())
1356 return (new fail())->setflag(status_flags::dynallocated);
1358 // GCD of two numeric values -> CLN
1359 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric)) {
1360 numeric g = gcd(ex_to<numeric>(a), ex_to<numeric>(b));
1362 *ca = ex_to<numeric>(a) / g;
1364 *cb = ex_to<numeric>(b) / g;
1368 // The first symbol is our main variable
1369 const symbol &x = *(var->sym);
1371 // Remove integer content
1372 numeric gc = gcd(a.integer_content(), b.integer_content());
1373 numeric rgc = gc.inverse();
1376 int maxdeg = std::max(p.degree(x), q.degree(x));
1378 // Find evaluation point
1379 numeric mp = p.max_coefficient();
1380 numeric mq = q.max_coefficient();
1383 xi = mq * _num2 + _num2;
1385 xi = mp * _num2 + _num2;
1388 for (int t=0; t<6; t++) {
1389 if (xi.int_length() * maxdeg > 100000) {
1390 //std::clog << "giving up heur_gcd, xi.int_length = " << xi.int_length() << ", maxdeg = " << maxdeg << std::endl;
1391 throw gcdheu_failed();
1394 // Apply evaluation homomorphism and calculate GCD
1396 ex gamma = heur_gcd(p.subs(x == xi), q.subs(x == xi), &cp, &cq, var+1).expand();
1397 if (!is_ex_exactly_of_type(gamma, fail)) {
1399 // Reconstruct polynomial from GCD of mapped polynomials
1400 ex g = interpolate(gamma, xi, x, maxdeg);
1402 // Remove integer content
1403 g /= g.integer_content();
1405 // If the calculated polynomial divides both p and q, this is the GCD
1407 if (divide_in_z(p, g, ca ? *ca : dummy, var) && divide_in_z(q, g, cb ? *cb : dummy, var)) {
1409 ex lc = g.lcoeff(x);
1410 if (is_ex_exactly_of_type(lc, numeric) && ex_to<numeric>(lc).is_negative())
1416 cp = interpolate(cp, xi, x);
1417 if (divide_in_z(cp, p, g, var)) {
1418 if (divide_in_z(g, q, cb ? *cb : dummy, var)) {
1422 ex lc = g.lcoeff(x);
1423 if (is_ex_exactly_of_type(lc, numeric) && ex_to<numeric>(lc).is_negative())
1429 cq = interpolate(cq, xi, x);
1430 if (divide_in_z(cq, q, g, var)) {
1431 if (divide_in_z(g, p, ca ? *ca : dummy, var)) {
1435 ex lc = g.lcoeff(x);
1436 if (is_ex_exactly_of_type(lc, numeric) && ex_to<numeric>(lc).is_negative())
1445 // Next evaluation point
1446 xi = iquo(xi * isqrt(isqrt(xi)) * numeric(73794), numeric(27011));
1448 return (new fail())->setflag(status_flags::dynallocated);
1452 /** Compute GCD (Greatest Common Divisor) of multivariate polynomials a(X)
1455 * @param a first multivariate polynomial
1456 * @param b second multivariate polynomial
1457 * @param check_args check whether a and b are polynomials with rational
1458 * coefficients (defaults to "true")
1459 * @return the GCD as a new expression */
1460 ex gcd(const ex &a, const ex &b, ex *ca, ex *cb, bool check_args)
1462 //std::clog << "gcd(" << a << "," << b << ")\n";
1467 // GCD of numerics -> CLN
1468 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric)) {
1469 numeric g = gcd(ex_to<numeric>(a), ex_to<numeric>(b));
1478 *ca = ex_to<numeric>(a) / g;
1480 *cb = ex_to<numeric>(b) / g;
1487 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial))) {
1488 throw(std::invalid_argument("gcd: arguments must be polynomials over the rationals"));
1491 // Partially factored cases (to avoid expanding large expressions)
1492 if (is_ex_exactly_of_type(a, mul)) {
1493 if (is_ex_exactly_of_type(b, mul) && b.nops() > a.nops())
1496 unsigned num = a.nops();
1497 exvector g; g.reserve(num);
1498 exvector acc_ca; acc_ca.reserve(num);
1500 for (unsigned i=0; i<num; i++) {
1501 ex part_ca, part_cb;
1502 g.push_back(gcd(a.op(i), part_b, &part_ca, &part_cb, check_args));
1503 acc_ca.push_back(part_ca);
1507 *ca = (new mul(acc_ca))->setflag(status_flags::dynallocated);
1510 return (new mul(g))->setflag(status_flags::dynallocated);
1511 } else if (is_ex_exactly_of_type(b, mul)) {
1512 if (is_ex_exactly_of_type(a, mul) && a.nops() > b.nops())
1515 unsigned num = b.nops();
1516 exvector g; g.reserve(num);
1517 exvector acc_cb; acc_cb.reserve(num);
1519 for (unsigned i=0; i<num; i++) {
1520 ex part_ca, part_cb;
1521 g.push_back(gcd(part_a, b.op(i), &part_ca, &part_cb, check_args));
1522 acc_cb.push_back(part_cb);
1528 *cb = (new mul(acc_cb))->setflag(status_flags::dynallocated);
1529 return (new mul(g))->setflag(status_flags::dynallocated);
1533 // Input polynomials of the form poly^n are sometimes also trivial
1534 if (is_ex_exactly_of_type(a, power)) {
1536 if (is_ex_exactly_of_type(b, power)) {
1537 if (p.is_equal(b.op(0))) {
1538 // a = p^n, b = p^m, gcd = p^min(n, m)
1539 ex exp_a = a.op(1), exp_b = b.op(1);
1540 if (exp_a < exp_b) {
1544 *cb = power(p, exp_b - exp_a);
1545 return power(p, exp_a);
1548 *ca = power(p, exp_a - exp_b);
1551 return power(p, exp_b);
1555 if (p.is_equal(b)) {
1556 // a = p^n, b = p, gcd = p
1558 *ca = power(p, a.op(1) - 1);
1564 } else if (is_ex_exactly_of_type(b, power)) {
1566 if (p.is_equal(a)) {
1567 // a = p, b = p^n, gcd = p
1571 *cb = power(p, b.op(1) - 1);
1577 // Some trivial cases
1578 ex aex = a.expand(), bex = b.expand();
1579 if (aex.is_zero()) {
1586 if (bex.is_zero()) {
1593 if (aex.is_equal(_ex1) || bex.is_equal(_ex1)) {
1601 if (a.is_equal(b)) {
1610 // Gather symbol statistics
1611 sym_desc_vec sym_stats;
1612 get_symbol_stats(a, b, sym_stats);
1614 // The symbol with least degree is our main variable
1615 sym_desc_vec::const_iterator var = sym_stats.begin();
1616 const symbol &x = *(var->sym);
1618 // Cancel trivial common factor
1619 int ldeg_a = var->ldeg_a;
1620 int ldeg_b = var->ldeg_b;
1621 int min_ldeg = std::min(ldeg_a,ldeg_b);
1623 ex common = power(x, min_ldeg);
1624 //std::clog << "trivial common factor " << common << std::endl;
1625 return gcd((aex / common).expand(), (bex / common).expand(), ca, cb, false) * common;
1628 // Try to eliminate variables
1629 if (var->deg_a == 0) {
1630 //std::clog << "eliminating variable " << x << " from b" << std::endl;
1631 ex c = bex.content(x);
1632 ex g = gcd(aex, c, ca, cb, false);
1634 *cb *= bex.unit(x) * bex.primpart(x, c);
1636 } else if (var->deg_b == 0) {
1637 //std::clog << "eliminating variable " << x << " from a" << std::endl;
1638 ex c = aex.content(x);
1639 ex g = gcd(c, bex, ca, cb, false);
1641 *ca *= aex.unit(x) * aex.primpart(x, c);
1647 // Try heuristic algorithm first, fall back to PRS if that failed
1649 g = heur_gcd(aex, bex, ca, cb, var);
1650 } catch (gcdheu_failed) {
1653 if (is_ex_exactly_of_type(g, fail)) {
1654 //std::clog << "heuristics failed" << std::endl;
1659 // g = heur_gcd(aex, bex, ca, cb, var);
1660 // g = eu_gcd(aex, bex, &x);
1661 // g = euprem_gcd(aex, bex, &x);
1662 // g = peu_gcd(aex, bex, &x);
1663 // g = red_gcd(aex, bex, &x);
1664 g = sr_gcd(aex, bex, var);
1665 if (g.is_equal(_ex1)) {
1666 // Keep cofactors factored if possible
1673 divide(aex, g, *ca, false);
1675 divide(bex, g, *cb, false);
1679 if (g.is_equal(_ex1)) {
1680 // Keep cofactors factored if possible
1692 /** Compute LCM (Least Common Multiple) of multivariate polynomials in Z[X].
1694 * @param a first multivariate polynomial
1695 * @param b second multivariate polynomial
1696 * @param check_args check whether a and b are polynomials with rational
1697 * coefficients (defaults to "true")
1698 * @return the LCM as a new expression */
1699 ex lcm(const ex &a, const ex &b, bool check_args)
1701 if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric))
1702 return lcm(ex_to<numeric>(a), ex_to<numeric>(b));
1703 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
1704 throw(std::invalid_argument("lcm: arguments must be polynomials over the rationals"));
1707 ex g = gcd(a, b, &ca, &cb, false);
1713 * Square-free factorization
1716 /** Compute square-free factorization of multivariate polynomial a(x) using
1717 * YunĀ“s algorithm. Used internally by sqrfree().
1719 * @param a multivariate polynomial over Z[X], treated here as univariate
1721 * @param x variable to factor in
1722 * @return vector of factors sorted in ascending degree */
1723 static exvector sqrfree_yun(const ex &a, const symbol &x)
1729 if (g.is_equal(_ex1)) {
1740 } while (!z.is_zero());
1745 /** Compute a square-free factorization of a multivariate polynomial in Q[X].
1747 * @param a multivariate polynomial over Q[X]
1748 * @param x lst of variables to factor in, may be left empty for autodetection
1749 * @return a square-free factorization of \p a.
1752 * A polynomial \f$p(X) \in C[X]\f$ is said <EM>square-free</EM>
1753 * if, whenever any two polynomials \f$q(X)\f$ and \f$r(X)\f$
1756 * p(X) = q(X)^2 r(X),
1758 * we have \f$q(X) \in C\f$.
1759 * This means that \f$p(X)\f$ has no repeated factors, apart
1760 * eventually from constants.
1761 * Given a polynomial \f$p(X) \in C[X]\f$, we say that the
1764 * p(X) = b \cdot p_1(X)^{a_1} \cdot p_2(X)^{a_2} \cdots p_r(X)^{a_r}
1766 * is a <EM>square-free factorization</EM> of \f$p(X)\f$ if the
1767 * following conditions hold:
1768 * -# \f$b \in C\f$ and \f$b \neq 0\f$;
1769 * -# \f$a_i\f$ is a positive integer for \f$i = 1, \ldots, r\f$;
1770 * -# the degree of the polynomial \f$p_i\f$ is strictly positive
1771 * for \f$i = 1, \ldots, r\f$;
1772 * -# the polynomial \f$\Pi_{i=1}^r p_i(X)\f$ is square-free.
1774 * Square-free factorizations need not be unique. For example, if
1775 * \f$a_i\f$ is even, we could change the polynomial \f$p_i(X)\f$
1776 * into \f$-p_i(X)\f$.
1777 * Observe also that the factors \f$p_i(X)\f$ need not be irreducible
1780 ex sqrfree(const ex &a, const lst &l)
1782 if (is_a<numeric>(a) || // algorithm does not trap a==0
1783 is_a<symbol>(a)) // shortcut
1786 // If no lst of variables to factorize in was specified we have to
1787 // invent one now. Maybe one can optimize here by reversing the order
1788 // or so, I don't know.
1792 get_symbol_stats(a, _ex0, sdv);
1793 sym_desc_vec::const_iterator it = sdv.begin(), itend = sdv.end();
1794 while (it != itend) {
1795 args.append(*it->sym);
1802 // Find the symbol to factor in at this stage
1803 if (!is_ex_of_type(args.op(0), symbol))
1804 throw (std::runtime_error("sqrfree(): invalid factorization variable"));
1805 const symbol &x = ex_to<symbol>(args.op(0));
1807 // convert the argument from something in Q[X] to something in Z[X]
1808 const numeric lcm = lcm_of_coefficients_denominators(a);
1809 const ex tmp = multiply_lcm(a,lcm);
1812 exvector factors = sqrfree_yun(tmp,x);
1814 // construct the next list of symbols with the first element popped
1816 newargs.remove_first();
1818 // recurse down the factors in remaining variables
1819 if (newargs.nops()>0) {
1820 exvector::iterator i = factors.begin();
1821 while (i != factors.end()) {
1822 *i = sqrfree(*i, newargs);
1827 // Done with recursion, now construct the final result
1829 exvector::const_iterator it = factors.begin(), itend = factors.end();
1830 for (int p = 1; it!=itend; ++it, ++p)
1831 result *= power(*it, p);
1833 // Yun's algorithm does not account for constant factors. (For univariate
1834 // polynomials it works only in the monic case.) We can correct this by
1835 // inserting what has been lost back into the result. For completeness
1836 // we'll also have to recurse down that factor in the remaining variables.
1837 if (newargs.nops()>0)
1838 result *= sqrfree(quo(tmp, result, x), newargs);
1840 result *= quo(tmp, result, x);
1842 // Put in the reational overall factor again and return
1843 return result * lcm.inverse();
1847 /** Compute square-free partial fraction decomposition of rational function
1850 * @param a rational function over Z[x], treated as univariate polynomial
1852 * @param x variable to factor in
1853 * @return decomposed rational function */
1854 ex sqrfree_parfrac(const ex & a, const symbol & x)
1856 // Find numerator and denominator
1857 ex nd = numer_denom(a);
1858 ex numer = nd.op(0), denom = nd.op(1);
1859 //clog << "numer = " << numer << ", denom = " << denom << endl;
1861 // Convert N(x)/D(x) -> Q(x) + R(x)/D(x), so degree(R) < degree(D)
1862 ex red_poly = quo(numer, denom, x), red_numer = rem(numer, denom, x).expand();
1863 //clog << "red_poly = " << red_poly << ", red_numer = " << red_numer << endl;
1865 // Factorize denominator and compute cofactors
1866 exvector yun = sqrfree_yun(denom, x);
1867 //clog << "yun factors: " << exprseq(yun) << endl;
1868 unsigned num_yun = yun.size();
1869 exvector factor; factor.reserve(num_yun);
1870 exvector cofac; cofac.reserve(num_yun);
1871 for (unsigned i=0; i<num_yun; i++) {
1872 if (!yun[i].is_equal(_ex1)) {
1873 for (unsigned j=0; j<=i; j++) {
1874 factor.push_back(pow(yun[i], j+1));
1876 for (unsigned k=0; k<num_yun; k++) {
1878 prod *= pow(yun[k], i-j);
1880 prod *= pow(yun[k], k+1);
1882 cofac.push_back(prod.expand());
1886 unsigned num_factors = factor.size();
1887 //clog << "factors : " << exprseq(factor) << endl;
1888 //clog << "cofactors: " << exprseq(cofac) << endl;
1890 // Construct coefficient matrix for decomposition
1891 int max_denom_deg = denom.degree(x);
1892 matrix sys(max_denom_deg + 1, num_factors);
1893 matrix rhs(max_denom_deg + 1, 1);
1894 for (int i=0; i<=max_denom_deg; i++) {
1895 for (unsigned j=0; j<num_factors; j++)
1896 sys(i, j) = cofac[j].coeff(x, i);
1897 rhs(i, 0) = red_numer.coeff(x, i);
1899 //clog << "coeffs: " << sys << endl;
1900 //clog << "rhs : " << rhs << endl;
1902 // Solve resulting linear system
1903 matrix vars(num_factors, 1);
1904 for (unsigned i=0; i<num_factors; i++)
1905 vars(i, 0) = symbol();
1906 matrix sol = sys.solve(vars, rhs);
1908 // Sum up decomposed fractions
1910 for (unsigned i=0; i<num_factors; i++)
1911 sum += sol(i, 0) / factor[i];
1913 return red_poly + sum;
1918 * Normal form of rational functions
1922 * Note: The internal normal() functions (= basic::normal() and overloaded
1923 * functions) all return lists of the form {numerator, denominator}. This
1924 * is to get around mul::eval()'s automatic expansion of numeric coefficients.
1925 * E.g. (a+b)/3 is automatically converted to a/3+b/3 but we want to keep
1926 * the information that (a+b) is the numerator and 3 is the denominator.
1930 /** Create a symbol for replacing the expression "e" (or return a previously
1931 * assigned symbol). The symbol is appended to sym_lst and returned, the
1932 * expression is appended to repl_lst.
1933 * @see ex::normal */
1934 static ex replace_with_symbol(const ex &e, lst &sym_lst, lst &repl_lst)
1936 // Expression already in repl_lst? Then return the assigned symbol
1937 for (unsigned i=0; i<repl_lst.nops(); i++)
1938 if (repl_lst.op(i).is_equal(e))
1939 return sym_lst.op(i);
1941 // Otherwise create new symbol and add to list, taking care that the
1942 // replacement expression doesn't contain symbols from the sym_lst
1943 // because subs() is not recursive
1946 ex e_replaced = e.subs(sym_lst, repl_lst);
1948 repl_lst.append(e_replaced);
1952 /** Create a symbol for replacing the expression "e" (or return a previously
1953 * assigned symbol). An expression of the form "symbol == expression" is added
1954 * to repl_lst and the symbol is returned.
1955 * @see basic::to_rational */
1956 static ex replace_with_symbol(const ex &e, lst &repl_lst)
1958 // Expression already in repl_lst? Then return the assigned symbol
1959 for (unsigned i=0; i<repl_lst.nops(); i++)
1960 if (repl_lst.op(i).op(1).is_equal(e))
1961 return repl_lst.op(i).op(0);
1963 // Otherwise create new symbol and add to list, taking care that the
1964 // replacement expression doesn't contain symbols from the sym_lst
1965 // because subs() is not recursive
1968 ex e_replaced = e.subs(repl_lst);
1969 repl_lst.append(es == e_replaced);
1974 /** Function object to be applied by basic::normal(). */
1975 struct normal_map_function : public map_function {
1977 normal_map_function(int l) : level(l) {}
1978 ex operator()(const ex & e) { return normal(e, level); }
1981 /** Default implementation of ex::normal(). It normalizes the children and
1982 * replaces the object with a temporary symbol.
1983 * @see ex::normal */
1984 ex basic::normal(lst &sym_lst, lst &repl_lst, int level) const
1987 return (new lst(replace_with_symbol(*this, sym_lst, repl_lst), _ex1))->setflag(status_flags::dynallocated);
1990 return (new lst(replace_with_symbol(*this, sym_lst, repl_lst), _ex1))->setflag(status_flags::dynallocated);
1991 else if (level == -max_recursion_level)
1992 throw(std::runtime_error("max recursion level reached"));
1994 normal_map_function map_normal(level - 1);
1995 return (new lst(replace_with_symbol(map(map_normal), sym_lst, repl_lst), _ex1))->setflag(status_flags::dynallocated);
2001 /** Implementation of ex::normal() for symbols. This returns the unmodified symbol.
2002 * @see ex::normal */
2003 ex symbol::normal(lst &sym_lst, lst &repl_lst, int level) const
2005 return (new lst(*this, _ex1))->setflag(status_flags::dynallocated);
2009 /** Implementation of ex::normal() for a numeric. It splits complex numbers
2010 * into re+I*im and replaces I and non-rational real numbers with a temporary
2012 * @see ex::normal */
2013 ex numeric::normal(lst &sym_lst, lst &repl_lst, int level) const
2015 numeric num = numer();
2018 if (num.is_real()) {
2019 if (!num.is_integer())
2020 numex = replace_with_symbol(numex, sym_lst, repl_lst);
2022 numeric re = num.real(), im = num.imag();
2023 ex re_ex = re.is_rational() ? re : replace_with_symbol(re, sym_lst, repl_lst);
2024 ex im_ex = im.is_rational() ? im : replace_with_symbol(im, sym_lst, repl_lst);
2025 numex = re_ex + im_ex * replace_with_symbol(I, sym_lst, repl_lst);
2028 // Denominator is always a real integer (see numeric::denom())
2029 return (new lst(numex, denom()))->setflag(status_flags::dynallocated);
2033 /** Fraction cancellation.
2034 * @param n numerator
2035 * @param d denominator
2036 * @return cancelled fraction {n, d} as a list */
2037 static ex frac_cancel(const ex &n, const ex &d)
2041 numeric pre_factor = _num1;
2043 //std::clog << "frac_cancel num = " << num << ", den = " << den << std::endl;
2045 // Handle trivial case where denominator is 1
2046 if (den.is_equal(_ex1))
2047 return (new lst(num, den))->setflag(status_flags::dynallocated);
2049 // Handle special cases where numerator or denominator is 0
2051 return (new lst(num, _ex1))->setflag(status_flags::dynallocated);
2052 if (den.expand().is_zero())
2053 throw(std::overflow_error("frac_cancel: division by zero in frac_cancel"));
2055 // Bring numerator and denominator to Z[X] by multiplying with
2056 // LCM of all coefficients' denominators
2057 numeric num_lcm = lcm_of_coefficients_denominators(num);
2058 numeric den_lcm = lcm_of_coefficients_denominators(den);
2059 num = multiply_lcm(num, num_lcm);
2060 den = multiply_lcm(den, den_lcm);
2061 pre_factor = den_lcm / num_lcm;
2063 // Cancel GCD from numerator and denominator
2065 if (gcd(num, den, &cnum, &cden, false) != _ex1) {
2070 // Make denominator unit normal (i.e. coefficient of first symbol
2071 // as defined by get_first_symbol() is made positive)
2073 if (get_first_symbol(den, x)) {
2074 GINAC_ASSERT(is_exactly_a<numeric>(den.unit(*x)));
2075 if (ex_to<numeric>(den.unit(*x)).is_negative()) {
2081 // Return result as list
2082 //std::clog << " returns num = " << num << ", den = " << den << ", pre_factor = " << pre_factor << std::endl;
2083 return (new lst(num * pre_factor.numer(), den * pre_factor.denom()))->setflag(status_flags::dynallocated);
2087 /** Implementation of ex::normal() for a sum. It expands terms and performs
2088 * fractional addition.
2089 * @see ex::normal */
2090 ex add::normal(lst &sym_lst, lst &repl_lst, int level) const
2093 return (new lst(replace_with_symbol(*this, sym_lst, repl_lst), _ex1))->setflag(status_flags::dynallocated);
2094 else if (level == -max_recursion_level)
2095 throw(std::runtime_error("max recursion level reached"));
2097 // Normalize children and split each one into numerator and denominator
2098 exvector nums, dens;
2099 nums.reserve(seq.size()+1);
2100 dens.reserve(seq.size()+1);
2101 epvector::const_iterator it = seq.begin(), itend = seq.end();
2102 while (it != itend) {
2103 ex n = ex_to<basic>(recombine_pair_to_ex(*it)).normal(sym_lst, repl_lst, level-1);
2104 nums.push_back(n.op(0));
2105 dens.push_back(n.op(1));
2108 ex n = ex_to<numeric>(overall_coeff).normal(sym_lst, repl_lst, level-1);
2109 nums.push_back(n.op(0));
2110 dens.push_back(n.op(1));
2111 GINAC_ASSERT(nums.size() == dens.size());
2113 // Now, nums is a vector of all numerators and dens is a vector of
2115 //std::clog << "add::normal uses " << nums.size() << " summands:\n";
2117 // Add fractions sequentially
2118 exvector::const_iterator num_it = nums.begin(), num_itend = nums.end();
2119 exvector::const_iterator den_it = dens.begin(), den_itend = dens.end();
2120 //std::clog << " num = " << *num_it << ", den = " << *den_it << std::endl;
2121 ex num = *num_it++, den = *den_it++;
2122 while (num_it != num_itend) {
2123 //std::clog << " num = " << *num_it << ", den = " << *den_it << std::endl;
2124 ex next_num = *num_it++, next_den = *den_it++;
2126 // Trivially add sequences of fractions with identical denominators
2127 while ((den_it != den_itend) && next_den.is_equal(*den_it)) {
2128 next_num += *num_it;
2132 // Additiion of two fractions, taking advantage of the fact that
2133 // the heuristic GCD algorithm computes the cofactors at no extra cost
2134 ex co_den1, co_den2;
2135 ex g = gcd(den, next_den, &co_den1, &co_den2, false);
2136 num = ((num * co_den2) + (next_num * co_den1)).expand();
2137 den *= co_den2; // this is the lcm(den, next_den)
2139 //std::clog << " common denominator = " << den << std::endl;
2141 // Cancel common factors from num/den
2142 return frac_cancel(num, den);
2146 /** Implementation of ex::normal() for a product. It cancels common factors
2148 * @see ex::normal() */
2149 ex mul::normal(lst &sym_lst, lst &repl_lst, int level) const
2152 return (new lst(replace_with_symbol(*this, sym_lst, repl_lst), _ex1))->setflag(status_flags::dynallocated);
2153 else if (level == -max_recursion_level)
2154 throw(std::runtime_error("max recursion level reached"));
2156 // Normalize children, separate into numerator and denominator
2157 exvector num; num.reserve(seq.size());
2158 exvector den; den.reserve(seq.size());
2160 epvector::const_iterator it = seq.begin(), itend = seq.end();
2161 while (it != itend) {
2162 n = ex_to<basic>(recombine_pair_to_ex(*it)).normal(sym_lst, repl_lst, level-1);
2163 num.push_back(n.op(0));
2164 den.push_back(n.op(1));
2167 n = ex_to<numeric>(overall_coeff).normal(sym_lst, repl_lst, level-1);
2168 num.push_back(n.op(0));
2169 den.push_back(n.op(1));
2171 // Perform fraction cancellation
2172 return frac_cancel((new mul(num))->setflag(status_flags::dynallocated),
2173 (new mul(den))->setflag(status_flags::dynallocated));
2177 /** Implementation of ex::normal() for powers. It normalizes the basis,
2178 * distributes integer exponents to numerator and denominator, and replaces
2179 * non-integer powers by temporary symbols.
2180 * @see ex::normal */
2181 ex power::normal(lst &sym_lst, lst &repl_lst, int level) const
2184 return (new lst(replace_with_symbol(*this, sym_lst, repl_lst), _ex1))->setflag(status_flags::dynallocated);
2185 else if (level == -max_recursion_level)
2186 throw(std::runtime_error("max recursion level reached"));
2188 // Normalize basis and exponent (exponent gets reassembled)
2189 ex n_basis = ex_to<basic>(basis).normal(sym_lst, repl_lst, level-1);
2190 ex n_exponent = ex_to<basic>(exponent).normal(sym_lst, repl_lst, level-1);
2191 n_exponent = n_exponent.op(0) / n_exponent.op(1);
2193 if (n_exponent.info(info_flags::integer)) {
2195 if (n_exponent.info(info_flags::positive)) {
2197 // (a/b)^n -> {a^n, b^n}
2198 return (new lst(power(n_basis.op(0), n_exponent), power(n_basis.op(1), n_exponent)))->setflag(status_flags::dynallocated);
2200 } else if (n_exponent.info(info_flags::negative)) {
2202 // (a/b)^-n -> {b^n, a^n}
2203 return (new lst(power(n_basis.op(1), -n_exponent), power(n_basis.op(0), -n_exponent)))->setflag(status_flags::dynallocated);
2208 if (n_exponent.info(info_flags::positive)) {
2210 // (a/b)^x -> {sym((a/b)^x), 1}
2211 return (new lst(replace_with_symbol(power(n_basis.op(0) / n_basis.op(1), n_exponent), sym_lst, repl_lst), _ex1))->setflag(status_flags::dynallocated);
2213 } else if (n_exponent.info(info_flags::negative)) {
2215 if (n_basis.op(1).is_equal(_ex1)) {
2217 // a^-x -> {1, sym(a^x)}
2218 return (new lst(_ex1, replace_with_symbol(power(n_basis.op(0), -n_exponent), sym_lst, repl_lst)))->setflag(status_flags::dynallocated);
2222 // (a/b)^-x -> {sym((b/a)^x), 1}
2223 return (new lst(replace_with_symbol(power(n_basis.op(1) / n_basis.op(0), -n_exponent), sym_lst, repl_lst), _ex1))->setflag(status_flags::dynallocated);
2226 } else { // n_exponent not numeric
2228 // (a/b)^x -> {sym((a/b)^x, 1}
2229 return (new lst(replace_with_symbol(power(n_basis.op(0) / n_basis.op(1), n_exponent), sym_lst, repl_lst), _ex1))->setflag(status_flags::dynallocated);
2235 /** Implementation of ex::normal() for pseries. It normalizes each coefficient
2236 * and replaces the series by a temporary symbol.
2237 * @see ex::normal */
2238 ex pseries::normal(lst &sym_lst, lst &repl_lst, int level) const
2241 epvector::const_iterator i = seq.begin(), end = seq.end();
2243 ex restexp = i->rest.normal();
2244 if (!restexp.is_zero())
2245 newseq.push_back(expair(restexp, i->coeff));
2248 ex n = pseries(relational(var,point), newseq);
2249 return (new lst(replace_with_symbol(n, sym_lst, repl_lst), _ex1))->setflag(status_flags::dynallocated);
2253 /** Normalization of rational functions.
2254 * This function converts an expression to its normal form
2255 * "numerator/denominator", where numerator and denominator are (relatively
2256 * prime) polynomials. Any subexpressions which are not rational functions
2257 * (like non-rational numbers, non-integer powers or functions like sin(),
2258 * cos() etc.) are replaced by temporary symbols which are re-substituted by
2259 * the (normalized) subexpressions before normal() returns (this way, any
2260 * expression can be treated as a rational function). normal() is applied
2261 * recursively to arguments of functions etc.
2263 * @param level maximum depth of recursion
2264 * @return normalized expression */
2265 ex ex::normal(int level) const
2267 lst sym_lst, repl_lst;
2269 ex e = bp->normal(sym_lst, repl_lst, level);
2270 GINAC_ASSERT(is_a<lst>(e));
2272 // Re-insert replaced symbols
2273 if (sym_lst.nops() > 0)
2274 e = e.subs(sym_lst, repl_lst);
2276 // Convert {numerator, denominator} form back to fraction
2277 return e.op(0) / e.op(1);
2280 /** Get numerator of an expression. If the expression is not of the normal
2281 * form "numerator/denominator", it is first converted to this form and
2282 * then the numerator is returned.
2285 * @return numerator */
2286 ex ex::numer(void) const
2288 lst sym_lst, repl_lst;
2290 ex e = bp->normal(sym_lst, repl_lst, 0);
2291 GINAC_ASSERT(is_a<lst>(e));
2293 // Re-insert replaced symbols
2294 if (sym_lst.nops() > 0)
2295 return e.op(0).subs(sym_lst, repl_lst);
2300 /** Get denominator of an expression. If the expression is not of the normal
2301 * form "numerator/denominator", it is first converted to this form and
2302 * then the denominator is returned.
2305 * @return denominator */
2306 ex ex::denom(void) const
2308 lst sym_lst, repl_lst;
2310 ex e = bp->normal(sym_lst, repl_lst, 0);
2311 GINAC_ASSERT(is_a<lst>(e));
2313 // Re-insert replaced symbols
2314 if (sym_lst.nops() > 0)
2315 return e.op(1).subs(sym_lst, repl_lst);
2320 /** Get numerator and denominator of an expression. If the expresison is not
2321 * of the normal form "numerator/denominator", it is first converted to this
2322 * form and then a list [numerator, denominator] is returned.
2325 * @return a list [numerator, denominator] */
2326 ex ex::numer_denom(void) const
2328 lst sym_lst, repl_lst;
2330 ex e = bp->normal(sym_lst, repl_lst, 0);
2331 GINAC_ASSERT(is_a<lst>(e));
2333 // Re-insert replaced symbols
2334 if (sym_lst.nops() > 0)
2335 return e.subs(sym_lst, repl_lst);
2341 /** Rationalization of non-rational functions.
2342 * This function converts a general expression to a rational polynomial
2343 * by replacing all non-rational subexpressions (like non-rational numbers,
2344 * non-integer powers or functions like sin(), cos() etc.) to temporary
2345 * symbols. This makes it possible to use functions like gcd() and divide()
2346 * on non-rational functions by applying to_rational() on the arguments,
2347 * calling the desired function and re-substituting the temporary symbols
2348 * in the result. To make the last step possible, all temporary symbols and
2349 * their associated expressions are collected in the list specified by the
2350 * repl_lst parameter in the form {symbol == expression}, ready to be passed
2351 * as an argument to ex::subs().
2353 * @param repl_lst collects a list of all temporary symbols and their replacements
2354 * @return rationalized expression */
2355 ex basic::to_rational(lst &repl_lst) const
2357 return replace_with_symbol(*this, repl_lst);
2361 /** Implementation of ex::to_rational() for symbols. This returns the
2362 * unmodified symbol. */
2363 ex symbol::to_rational(lst &repl_lst) const
2369 /** Implementation of ex::to_rational() for a numeric. It splits complex
2370 * numbers into re+I*im and replaces I and non-rational real numbers with a
2371 * temporary symbol. */
2372 ex numeric::to_rational(lst &repl_lst) const
2376 return replace_with_symbol(*this, repl_lst);
2378 numeric re = real();
2379 numeric im = imag();
2380 ex re_ex = re.is_rational() ? re : replace_with_symbol(re, repl_lst);
2381 ex im_ex = im.is_rational() ? im : replace_with_symbol(im, repl_lst);
2382 return re_ex + im_ex * replace_with_symbol(I, repl_lst);
2388 /** Implementation of ex::to_rational() for powers. It replaces non-integer
2389 * powers by temporary symbols. */
2390 ex power::to_rational(lst &repl_lst) const
2392 if (exponent.info(info_flags::integer))
2393 return power(basis.to_rational(repl_lst), exponent);
2395 return replace_with_symbol(*this, repl_lst);
2399 /** Implementation of ex::to_rational() for expairseqs. */
2400 ex expairseq::to_rational(lst &repl_lst) const
2403 s.reserve(seq.size());
2404 epvector::const_iterator i = seq.begin(), end = seq.end();
2406 s.push_back(split_ex_to_pair(recombine_pair_to_ex(*i).to_rational(repl_lst)));
2409 ex oc = overall_coeff.to_rational(repl_lst);
2410 if (oc.info(info_flags::numeric))
2411 return thisexpairseq(s, overall_coeff);
2413 s.push_back(combine_ex_with_coeff_to_pair(oc, _ex1));
2414 return thisexpairseq(s, default_overall_coeff());
2418 /** Remove the common factor in the terms of a sum 'e' by calculating the GCD,
2419 * and multiply it into the expression 'factor' (which needs to be initialized
2420 * to 1, unless you're accumulating factors). */
2421 static ex find_common_factor(const ex & e, ex & factor, lst & repl)
2425 unsigned num = e.nops();
2426 exvector terms; terms.reserve(num);
2429 // Find the common GCD
2430 for (unsigned i=0; i<num; i++) {
2431 ex x = e.op(i).to_rational(repl);
2433 if (is_a<add>(x) || is_a<mul>(x)) {
2435 x = find_common_factor(x, f, repl);
2447 if (gc.is_equal(_ex1))
2450 // The GCD is the factor we pull out
2453 // Now divide all terms by the GCD
2454 for (unsigned i=0; i<num; i++) {
2457 // Try to avoid divide() because it expands the polynomial
2460 for (unsigned j=0; j<t.nops(); j++) {
2461 if (t.op(j).is_equal(gc)) {
2462 exvector v; v.reserve(t.nops());
2463 for (unsigned k=0; k<t.nops(); k++) {
2467 v.push_back(t.op(k));
2469 t = (new mul(v))->setflag(status_flags::dynallocated);
2479 return (new add(terms))->setflag(status_flags::dynallocated);
2481 } else if (is_a<mul>(e)) {
2483 unsigned num = e.nops();
2484 exvector v; v.reserve(num);
2486 for (unsigned i=0; i<num; i++)
2487 v.push_back(find_common_factor(e.op(i), factor, repl));
2489 return (new mul(v))->setflag(status_flags::dynallocated);
2491 } else if (is_a<power>(e)) {
2493 ex x = e.to_rational(repl);
2494 if (is_a<power>(x) && x.op(1).info(info_flags::negative))
2495 return replace_with_symbol(x, repl);
2504 /** Collect common factors in sums. This converts expressions like
2505 * 'a*(b*x+b*y)' to 'a*b*(x+y)'. */
2506 ex collect_common_factors(const ex & e)
2508 if (is_a<add>(e) || is_a<mul>(e)) {
2512 ex r = find_common_factor(e, factor, repl);
2513 return factor.subs(repl) * r.subs(repl);
2520 } // namespace GiNaC