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-2005 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
35 #include "expairseq.h"
42 #include "relational.h"
43 #include "operators.h"
51 // If comparing expressions (ex::compare()) is fast, you can set this to 1.
52 // Some routines like quo(), rem() and gcd() will then return a quick answer
53 // when they are called with two identical arguments.
54 #define FAST_COMPARE 1
56 // Set this if you want divide_in_z() to use remembering
57 #define USE_REMEMBER 0
59 // Set this if you want divide_in_z() to use trial division followed by
60 // polynomial interpolation (always slower except for completely dense
62 #define USE_TRIAL_DIVISION 0
64 // Set this to enable some statistical output for the GCD routines
69 // Statistics variables
70 static int gcd_called = 0;
71 static int sr_gcd_called = 0;
72 static int heur_gcd_called = 0;
73 static int heur_gcd_failed = 0;
75 // Print statistics at end of program
76 static struct _stat_print {
79 std::cout << "gcd() called " << gcd_called << " times\n";
80 std::cout << "sr_gcd() called " << sr_gcd_called << " times\n";
81 std::cout << "heur_gcd() called " << heur_gcd_called << " times\n";
82 std::cout << "heur_gcd() failed " << heur_gcd_failed << " times\n";
88 /** Return pointer to first symbol found in expression. Due to GiNaC's
89 * internal ordering of terms, it may not be obvious which symbol this
90 * function returns for a given expression.
92 * @param e expression to search
93 * @param x first symbol found (returned)
94 * @return "false" if no symbol was found, "true" otherwise */
95 static bool get_first_symbol(const ex &e, ex &x)
97 if (is_a<symbol>(e)) {
100 } else if (is_exactly_a<add>(e) || is_exactly_a<mul>(e)) {
101 for (size_t i=0; i<e.nops(); i++)
102 if (get_first_symbol(e.op(i), x))
104 } else if (is_exactly_a<power>(e)) {
105 if (get_first_symbol(e.op(0), x))
113 * Statistical information about symbols in polynomials
116 /** This structure holds information about the highest and lowest degrees
117 * in which a symbol appears in two multivariate polynomials "a" and "b".
118 * A vector of these structures with information about all symbols in
119 * two polynomials can be created with the function get_symbol_stats().
121 * @see get_symbol_stats */
123 /** Reference to symbol */
126 /** Highest degree of symbol in polynomial "a" */
129 /** Highest degree of symbol in polynomial "b" */
132 /** Lowest degree of symbol in polynomial "a" */
135 /** Lowest degree of symbol in polynomial "b" */
138 /** Maximum of deg_a and deg_b (Used for sorting) */
141 /** Maximum number of terms of leading coefficient of symbol in both polynomials */
144 /** Commparison operator for sorting */
145 bool operator<(const sym_desc &x) const
147 if (max_deg == x.max_deg)
148 return max_lcnops < x.max_lcnops;
150 return max_deg < x.max_deg;
154 // Vector of sym_desc structures
155 typedef std::vector<sym_desc> sym_desc_vec;
157 // Add symbol the sym_desc_vec (used internally by get_symbol_stats())
158 static void add_symbol(const ex &s, sym_desc_vec &v)
160 sym_desc_vec::const_iterator it = v.begin(), itend = v.end();
161 while (it != itend) {
162 if (it->sym.is_equal(s)) // If it's already in there, don't add it a second time
171 // Collect all symbols of an expression (used internally by get_symbol_stats())
172 static void collect_symbols(const ex &e, sym_desc_vec &v)
174 if (is_a<symbol>(e)) {
176 } else if (is_exactly_a<add>(e) || is_exactly_a<mul>(e)) {
177 for (size_t i=0; i<e.nops(); i++)
178 collect_symbols(e.op(i), v);
179 } else if (is_exactly_a<power>(e)) {
180 collect_symbols(e.op(0), v);
184 /** Collect statistical information about symbols in polynomials.
185 * This function fills in a vector of "sym_desc" structs which contain
186 * information about the highest and lowest degrees of all symbols that
187 * appear in two polynomials. The vector is then sorted by minimum
188 * degree (lowest to highest). The information gathered by this
189 * function is used by the GCD routines to identify trivial factors
190 * and to determine which variable to choose as the main variable
191 * for GCD computation.
193 * @param a first multivariate polynomial
194 * @param b second multivariate polynomial
195 * @param v vector of sym_desc structs (filled in) */
196 static void get_symbol_stats(const ex &a, const ex &b, sym_desc_vec &v)
198 collect_symbols(a.eval(), v); // eval() to expand assigned symbols
199 collect_symbols(b.eval(), v);
200 sym_desc_vec::iterator it = v.begin(), itend = v.end();
201 while (it != itend) {
202 int deg_a = a.degree(it->sym);
203 int deg_b = b.degree(it->sym);
206 it->max_deg = std::max(deg_a, deg_b);
207 it->max_lcnops = std::max(a.lcoeff(it->sym).nops(), b.lcoeff(it->sym).nops());
208 it->ldeg_a = a.ldegree(it->sym);
209 it->ldeg_b = b.ldegree(it->sym);
212 std::sort(v.begin(), v.end());
215 std::clog << "Symbols:\n";
216 it = v.begin(); itend = v.end();
217 while (it != itend) {
218 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;
219 std::clog << " lcoeff_a=" << a.lcoeff(it->sym) << ", lcoeff_b=" << b.lcoeff(it->sym) << endl;
227 * Computation of LCM of denominators of coefficients of a polynomial
230 // Compute LCM of denominators of coefficients by going through the
231 // expression recursively (used internally by lcm_of_coefficients_denominators())
232 static numeric lcmcoeff(const ex &e, const numeric &l)
234 if (e.info(info_flags::rational))
235 return lcm(ex_to<numeric>(e).denom(), l);
236 else if (is_exactly_a<add>(e)) {
237 numeric c = *_num1_p;
238 for (size_t i=0; i<e.nops(); i++)
239 c = lcmcoeff(e.op(i), c);
241 } else if (is_exactly_a<mul>(e)) {
242 numeric c = *_num1_p;
243 for (size_t i=0; i<e.nops(); i++)
244 c *= lcmcoeff(e.op(i), *_num1_p);
246 } else if (is_exactly_a<power>(e)) {
247 if (is_a<symbol>(e.op(0)))
250 return pow(lcmcoeff(e.op(0), l), ex_to<numeric>(e.op(1)));
255 /** Compute LCM of denominators of coefficients of a polynomial.
256 * Given a polynomial with rational coefficients, this function computes
257 * the LCM of the denominators of all coefficients. This can be used
258 * to bring a polynomial from Q[X] to Z[X].
260 * @param e multivariate polynomial (need not be expanded)
261 * @return LCM of denominators of coefficients */
262 static numeric lcm_of_coefficients_denominators(const ex &e)
264 return lcmcoeff(e, *_num1_p);
267 /** Bring polynomial from Q[X] to Z[X] by multiplying in the previously
268 * determined LCM of the coefficient's denominators.
270 * @param e multivariate polynomial (need not be expanded)
271 * @param lcm LCM to multiply in */
272 static ex multiply_lcm(const ex &e, const numeric &lcm)
274 if (is_exactly_a<mul>(e)) {
275 size_t num = e.nops();
276 exvector v; v.reserve(num + 1);
277 numeric lcm_accum = *_num1_p;
278 for (size_t i=0; i<num; i++) {
279 numeric op_lcm = lcmcoeff(e.op(i), *_num1_p);
280 v.push_back(multiply_lcm(e.op(i), op_lcm));
283 v.push_back(lcm / lcm_accum);
284 return (new mul(v))->setflag(status_flags::dynallocated);
285 } else if (is_exactly_a<add>(e)) {
286 size_t num = e.nops();
287 exvector v; v.reserve(num);
288 for (size_t i=0; i<num; i++)
289 v.push_back(multiply_lcm(e.op(i), lcm));
290 return (new add(v))->setflag(status_flags::dynallocated);
291 } else if (is_exactly_a<power>(e)) {
292 if (is_a<symbol>(e.op(0)))
295 return pow(multiply_lcm(e.op(0), lcm.power(ex_to<numeric>(e.op(1)).inverse())), e.op(1));
301 /** Compute the integer content (= GCD of all numeric coefficients) of an
302 * expanded polynomial. For a polynomial with rational coefficients, this
303 * returns g/l where g is the GCD of the coefficients' numerators and l
304 * is the LCM of the coefficients' denominators.
306 * @return integer content */
307 numeric ex::integer_content() const
309 return bp->integer_content();
312 numeric basic::integer_content() const
317 numeric numeric::integer_content() const
319 return abs_function::eval_numeric(*this);
322 numeric add::integer_content() const
324 epvector::const_iterator it = seq.begin();
325 epvector::const_iterator itend = seq.end();
326 numeric c = *_num0_p, l = *_num1_p;
327 while (it != itend) {
328 GINAC_ASSERT(!is_exactly_a<numeric>(it->rest));
329 GINAC_ASSERT(is_exactly_a<numeric>(it->coeff));
330 c = gcd(ex_to<numeric>(it->coeff).numer(), c);
331 l = lcm(ex_to<numeric>(it->coeff).denom(), l);
334 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
335 c = gcd(ex_to<numeric>(overall_coeff).numer(), c);
336 l = lcm(ex_to<numeric>(overall_coeff).denom(), l);
340 numeric mul::integer_content() const
342 #ifdef DO_GINAC_ASSERT
343 epvector::const_iterator it = seq.begin();
344 epvector::const_iterator itend = seq.end();
345 while (it != itend) {
346 GINAC_ASSERT(!is_exactly_a<numeric>(recombine_pair_to_ex(*it)));
349 #endif // def DO_GINAC_ASSERT
350 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
351 return abs_function::eval_numeric(ex_to<numeric>(overall_coeff));
356 * Polynomial quotients and remainders
359 /** Quotient q(x) of polynomials a(x) and b(x) in Q[x].
360 * It satisfies a(x)=b(x)*q(x)+r(x).
362 * @param a first polynomial in x (dividend)
363 * @param b second polynomial in x (divisor)
364 * @param x a and b are polynomials in x
365 * @param check_args check whether a and b are polynomials with rational
366 * coefficients (defaults to "true")
367 * @return quotient of a and b in Q[x] */
368 ex quo(const ex &a, const ex &b, const ex &x, bool check_args)
371 throw(std::overflow_error("quo: division by zero"));
372 if (is_exactly_a<numeric>(a) && is_exactly_a<numeric>(b))
378 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
379 throw(std::invalid_argument("quo: arguments must be polynomials over the rationals"));
381 // Polynomial long division
385 int bdeg = b.degree(x);
386 int rdeg = r.degree(x);
387 ex blcoeff = b.expand().coeff(x, bdeg);
388 bool blcoeff_is_numeric = is_exactly_a<numeric>(blcoeff);
389 exvector v; v.reserve(std::max(rdeg - bdeg + 1, 0));
390 while (rdeg >= bdeg) {
391 ex term, rcoeff = r.coeff(x, rdeg);
392 if (blcoeff_is_numeric)
393 term = rcoeff / blcoeff;
395 if (!divide(rcoeff, blcoeff, term, false))
396 return (new fail())->setflag(status_flags::dynallocated);
398 term *= power(x, rdeg - bdeg);
400 r -= (term * b).expand();
405 return (new add(v))->setflag(status_flags::dynallocated);
409 /** Remainder r(x) of polynomials a(x) and b(x) in Q[x].
410 * It satisfies a(x)=b(x)*q(x)+r(x).
412 * @param a first polynomial in x (dividend)
413 * @param b second polynomial in x (divisor)
414 * @param x a and b are polynomials in x
415 * @param check_args check whether a and b are polynomials with rational
416 * coefficients (defaults to "true")
417 * @return remainder of a(x) and b(x) in Q[x] */
418 ex rem(const ex &a, const ex &b, const ex &x, bool check_args)
421 throw(std::overflow_error("rem: division by zero"));
422 if (is_exactly_a<numeric>(a)) {
423 if (is_exactly_a<numeric>(b))
432 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
433 throw(std::invalid_argument("rem: arguments must be polynomials over the rationals"));
435 // Polynomial long division
439 int bdeg = b.degree(x);
440 int rdeg = r.degree(x);
441 ex blcoeff = b.expand().coeff(x, bdeg);
442 bool blcoeff_is_numeric = is_exactly_a<numeric>(blcoeff);
443 while (rdeg >= bdeg) {
444 ex term, rcoeff = r.coeff(x, rdeg);
445 if (blcoeff_is_numeric)
446 term = rcoeff / blcoeff;
448 if (!divide(rcoeff, blcoeff, term, false))
449 return (new fail())->setflag(status_flags::dynallocated);
451 term *= power(x, rdeg - bdeg);
452 r -= (term * b).expand();
461 /** Decompose rational function a(x)=N(x)/D(x) into P(x)+n(x)/D(x)
462 * with degree(n, x) < degree(D, x).
464 * @param a rational function in x
465 * @param x a is a function of x
466 * @return decomposed function. */
467 ex decomp_rational(const ex &a, const ex &x)
469 ex nd = numer_denom(a);
470 ex numer = nd.op(0), denom = nd.op(1);
471 ex q = quo(numer, denom, x);
472 if (is_exactly_a<fail>(q))
475 return q + rem(numer, denom, x) / denom;
479 /** Pseudo-remainder of polynomials a(x) and b(x) in Q[x].
481 * @param a first polynomial in x (dividend)
482 * @param b second polynomial in x (divisor)
483 * @param x a and b are polynomials in x
484 * @param check_args check whether a and b are polynomials with rational
485 * coefficients (defaults to "true")
486 * @return pseudo-remainder of a(x) and b(x) in Q[x] */
487 ex prem(const ex &a, const ex &b, const ex &x, bool check_args)
490 throw(std::overflow_error("prem: division by zero"));
491 if (is_exactly_a<numeric>(a)) {
492 if (is_exactly_a<numeric>(b))
497 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
498 throw(std::invalid_argument("prem: arguments must be polynomials over the rationals"));
500 // Polynomial long division
503 int rdeg = r.degree(x);
504 int bdeg = eb.degree(x);
507 blcoeff = eb.coeff(x, bdeg);
511 eb -= blcoeff * power(x, bdeg);
515 int delta = rdeg - bdeg + 1, i = 0;
516 while (rdeg >= bdeg && !r.is_zero()) {
517 ex rlcoeff = r.coeff(x, rdeg);
518 ex term = (power(x, rdeg - bdeg) * eb * rlcoeff).expand();
522 r -= rlcoeff * power(x, rdeg);
523 r = (blcoeff * r).expand() - term;
527 return power(blcoeff, delta - i) * r;
531 /** Sparse pseudo-remainder of polynomials a(x) and b(x) in Q[x].
533 * @param a first polynomial in x (dividend)
534 * @param b second polynomial in x (divisor)
535 * @param x a and b are polynomials in x
536 * @param check_args check whether a and b are polynomials with rational
537 * coefficients (defaults to "true")
538 * @return sparse pseudo-remainder of a(x) and b(x) in Q[x] */
539 ex sprem(const ex &a, const ex &b, const ex &x, bool check_args)
542 throw(std::overflow_error("prem: division by zero"));
543 if (is_exactly_a<numeric>(a)) {
544 if (is_exactly_a<numeric>(b))
549 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
550 throw(std::invalid_argument("prem: arguments must be polynomials over the rationals"));
552 // Polynomial long division
555 int rdeg = r.degree(x);
556 int bdeg = eb.degree(x);
559 blcoeff = eb.coeff(x, bdeg);
563 eb -= blcoeff * power(x, bdeg);
567 while (rdeg >= bdeg && !r.is_zero()) {
568 ex rlcoeff = r.coeff(x, rdeg);
569 ex term = (power(x, rdeg - bdeg) * eb * rlcoeff).expand();
573 r -= rlcoeff * power(x, rdeg);
574 r = (blcoeff * r).expand() - term;
581 /** Exact polynomial division of a(X) by b(X) in Q[X].
583 * @param a first multivariate polynomial (dividend)
584 * @param b second multivariate polynomial (divisor)
585 * @param q quotient (returned)
586 * @param check_args check whether a and b are polynomials with rational
587 * coefficients (defaults to "true")
588 * @return "true" when exact division succeeds (quotient returned in q),
589 * "false" otherwise (q left untouched) */
590 bool divide(const ex &a, const ex &b, ex &q, bool check_args)
593 throw(std::overflow_error("divide: division by zero"));
598 if (is_exactly_a<numeric>(b)) {
601 } else if (is_exactly_a<numeric>(a))
609 if (check_args && (!a.info(info_flags::rational_polynomial) ||
610 !b.info(info_flags::rational_polynomial)))
611 throw(std::invalid_argument("divide: arguments must be polynomials over the rationals"));
615 if (!get_first_symbol(a, x) && !get_first_symbol(b, x))
616 throw(std::invalid_argument("invalid expression in divide()"));
618 // Polynomial long division (recursive)
624 int bdeg = b.degree(x);
625 int rdeg = r.degree(x);
626 ex blcoeff = b.expand().coeff(x, bdeg);
627 bool blcoeff_is_numeric = is_exactly_a<numeric>(blcoeff);
628 exvector v; v.reserve(std::max(rdeg - bdeg + 1, 0));
629 while (rdeg >= bdeg) {
630 ex term, rcoeff = r.coeff(x, rdeg);
631 if (blcoeff_is_numeric)
632 term = rcoeff / blcoeff;
634 if (!divide(rcoeff, blcoeff, term, false))
636 term *= power(x, rdeg - bdeg);
638 r -= (term * b).expand();
640 q = (new add(v))->setflag(status_flags::dynallocated);
654 typedef std::pair<ex, ex> ex2;
655 typedef std::pair<ex, bool> exbool;
658 bool operator() (const ex2 &p, const ex2 &q) const
660 int cmp = p.first.compare(q.first);
661 return ((cmp<0) || (!(cmp>0) && p.second.compare(q.second)<0));
665 typedef std::map<ex2, exbool, ex2_less> ex2_exbool_remember;
669 /** Exact polynomial division of a(X) by b(X) in Z[X].
670 * This functions works like divide() but the input and output polynomials are
671 * in Z[X] instead of Q[X] (i.e. they have integer coefficients). Unlike
672 * divide(), it doesn't check whether the input polynomials really are integer
673 * polynomials, so be careful of what you pass in. Also, you have to run
674 * get_symbol_stats() over the input polynomials before calling this function
675 * and pass an iterator to the first element of the sym_desc vector. This
676 * function is used internally by the heur_gcd().
678 * @param a first multivariate polynomial (dividend)
679 * @param b second multivariate polynomial (divisor)
680 * @param q quotient (returned)
681 * @param var iterator to first element of vector of sym_desc structs
682 * @return "true" when exact division succeeds (the quotient is returned in
683 * q), "false" otherwise.
684 * @see get_symbol_stats, heur_gcd */
685 static bool divide_in_z(const ex &a, const ex &b, ex &q, sym_desc_vec::const_iterator var)
689 throw(std::overflow_error("divide_in_z: division by zero"));
690 if (b.is_equal(_ex1)) {
694 if (is_exactly_a<numeric>(a)) {
695 if (is_exactly_a<numeric>(b)) {
697 return q.info(info_flags::integer);
710 static ex2_exbool_remember dr_remember;
711 ex2_exbool_remember::const_iterator remembered = dr_remember.find(ex2(a, b));
712 if (remembered != dr_remember.end()) {
713 q = remembered->second.first;
714 return remembered->second.second;
718 if (is_exactly_a<power>(b)) {
719 const ex& bb(b.op(0));
721 int exp_b = ex_to<numeric>(b.op(1)).to_int();
722 for (int i=exp_b; i>0; i--) {
723 if (!divide_in_z(qbar, bb, q, var))
730 if (is_exactly_a<mul>(b)) {
732 for (const_iterator itrb = b.begin(); itrb != b.end(); ++itrb) {
733 sym_desc_vec sym_stats;
734 get_symbol_stats(a, *itrb, sym_stats);
735 if (!divide_in_z(qbar, *itrb, q, sym_stats.begin()))
744 const ex &x = var->sym;
747 int adeg = a.degree(x), bdeg = b.degree(x);
751 #if USE_TRIAL_DIVISION
753 // Trial division with polynomial interpolation
756 // Compute values at evaluation points 0..adeg
757 vector<numeric> alpha; alpha.reserve(adeg + 1);
758 exvector u; u.reserve(adeg + 1);
759 numeric point = *_num0_p;
761 for (i=0; i<=adeg; i++) {
762 ex bs = b.subs(x == point, subs_options::no_pattern);
763 while (bs.is_zero()) {
765 bs = b.subs(x == point, subs_options::no_pattern);
767 if (!divide_in_z(a.subs(x == point, subs_options::no_pattern), bs, c, var+1))
769 alpha.push_back(point);
775 vector<numeric> rcp; rcp.reserve(adeg + 1);
776 rcp.push_back(*_num0_p);
777 for (k=1; k<=adeg; k++) {
778 numeric product = alpha[k] - alpha[0];
780 product *= alpha[k] - alpha[i];
781 rcp.push_back(product.inverse());
784 // Compute Newton coefficients
785 exvector v; v.reserve(adeg + 1);
787 for (k=1; k<=adeg; k++) {
789 for (i=k-2; i>=0; i--)
790 temp = temp * (alpha[k] - alpha[i]) + v[i];
791 v.push_back((u[k] - temp) * rcp[k]);
794 // Convert from Newton form to standard form
796 for (k=adeg-1; k>=0; k--)
797 c = c * (x - alpha[k]) + v[k];
799 if (c.degree(x) == (adeg - bdeg)) {
807 // Polynomial long division (recursive)
813 ex blcoeff = eb.coeff(x, bdeg);
814 exvector v; v.reserve(std::max(rdeg - bdeg + 1, 0));
815 while (rdeg >= bdeg) {
816 ex term, rcoeff = r.coeff(x, rdeg);
817 if (!divide_in_z(rcoeff, blcoeff, term, var+1))
819 term = (term * power(x, rdeg - bdeg)).expand();
821 r -= (term * eb).expand();
823 q = (new add(v))->setflag(status_flags::dynallocated);
825 dr_remember[ex2(a, b)] = exbool(q, true);
832 dr_remember[ex2(a, b)] = exbool(q, false);
841 * Separation of unit part, content part and primitive part of polynomials
844 /** Compute unit part (= sign of leading coefficient) of a multivariate
845 * polynomial in Q[x]. The product of unit part, content part, and primitive
846 * part is the polynomial itself.
848 * @param x main variable
850 * @see ex::content, ex::primpart, ex::unitcontprim */
851 ex ex::unit(const ex &x) const
853 ex c = expand().lcoeff(x);
854 if (is_exactly_a<numeric>(c))
855 return c.info(info_flags::negative) ?_ex_1 : _ex1;
858 if (get_first_symbol(c, y))
861 throw(std::invalid_argument("invalid expression in unit()"));
866 /** Compute content part (= unit normal GCD of all coefficients) of a
867 * multivariate polynomial in Q[x]. The product of unit part, content part,
868 * and primitive part is the polynomial itself.
870 * @param x main variable
871 * @return content part
872 * @see ex::unit, ex::primpart, ex::unitcontprim */
873 ex ex::content(const ex &x) const
875 if (is_exactly_a<numeric>(*this))
876 return info(info_flags::negative) ? -*this : *this;
882 // First, divide out the integer content (which we can calculate very efficiently).
883 // If the leading coefficient of the quotient is an integer, we are done.
884 ex c = e.integer_content();
886 int deg = r.degree(x);
887 ex lcoeff = r.coeff(x, deg);
888 if (lcoeff.info(info_flags::integer))
891 // GCD of all coefficients
892 int ldeg = r.ldegree(x);
894 return lcoeff * c / lcoeff.unit(x);
896 for (int i=ldeg; i<=deg; i++)
897 cont = gcd(r.coeff(x, i), cont, NULL, NULL, false);
902 /** Compute primitive part of a multivariate polynomial in Q[x]. The result
903 * will be a unit-normal polynomial with a content part of 1. The product
904 * of unit part, content part, and primitive part is the polynomial itself.
906 * @param x main variable
907 * @return primitive part
908 * @see ex::unit, ex::content, ex::unitcontprim */
909 ex ex::primpart(const ex &x) const
911 // We need to compute the unit and content anyway, so call unitcontprim()
913 unitcontprim(x, u, c, p);
918 /** Compute primitive part of a multivariate polynomial in Q[x] when the
919 * content part is already known. This function is faster in computing the
920 * primitive part than the previous function.
922 * @param x main variable
923 * @param c previously computed content part
924 * @return primitive part */
925 ex ex::primpart(const ex &x, const ex &c) const
927 if (is_zero() || c.is_zero())
929 if (is_exactly_a<numeric>(*this))
932 // Divide by unit and content to get primitive part
934 if (is_exactly_a<numeric>(c))
935 return *this / (c * u);
937 return quo(*this, c * u, x, false);
941 /** Compute unit part, content part, and primitive part of a multivariate
942 * polynomial in Q[x]. The product of the three parts is the polynomial
945 * @param x main variable
946 * @param u unit part (returned)
947 * @param c content part (returned)
948 * @param p primitive part (returned)
949 * @see ex::unit, ex::content, ex::primpart */
950 void ex::unitcontprim(const ex &x, ex &u, ex &c, ex &p) const
952 // Quick check for zero (avoid expanding)
959 // Special case: input is a number
960 if (is_exactly_a<numeric>(*this)) {
961 if (info(info_flags::negative)) {
963 c = abs_function::eval_numeric(ex_to<numeric>(*this));
972 // Expand input polynomial
980 // Compute unit and content
984 // Divide by unit and content to get primitive part
989 if (is_exactly_a<numeric>(c))
992 p = quo(e, c * u, x, false);
997 * GCD of multivariate polynomials
1000 /** Compute GCD of multivariate polynomials using the subresultant PRS
1001 * algorithm. This function is used internally by gcd().
1003 * @param a first multivariate polynomial
1004 * @param b second multivariate polynomial
1005 * @param var iterator to first element of vector of sym_desc structs
1006 * @return the GCD as a new expression
1009 static ex sr_gcd(const ex &a, const ex &b, sym_desc_vec::const_iterator var)
1015 // The first symbol is our main variable
1016 const ex &x = var->sym;
1018 // Sort c and d so that c has higher degree
1020 int adeg = a.degree(x), bdeg = b.degree(x);
1034 // Remove content from c and d, to be attached to GCD later
1035 ex cont_c = c.content(x);
1036 ex cont_d = d.content(x);
1037 ex gamma = gcd(cont_c, cont_d, NULL, NULL, false);
1040 c = c.primpart(x, cont_c);
1041 d = d.primpart(x, cont_d);
1043 // First element of subresultant sequence
1044 ex r = _ex0, ri = _ex1, psi = _ex1;
1045 int delta = cdeg - ddeg;
1049 // Calculate polynomial pseudo-remainder
1050 r = prem(c, d, x, false);
1052 return gamma * d.primpart(x);
1056 if (!divide_in_z(r, ri * pow(psi, delta), d, var))
1057 throw(std::runtime_error("invalid expression in sr_gcd(), division failed"));
1060 if (is_exactly_a<numeric>(r))
1063 return gamma * r.primpart(x);
1066 // Next element of subresultant sequence
1067 ri = c.expand().lcoeff(x);
1071 divide_in_z(pow(ri, delta), pow(psi, delta-1), psi, var+1);
1072 delta = cdeg - ddeg;
1077 /** Return maximum (absolute value) coefficient of a polynomial.
1078 * This function is used internally by heur_gcd().
1080 * @return maximum coefficient
1082 numeric ex::max_coefficient() const
1084 return bp->max_coefficient();
1087 /** Implementation ex::max_coefficient().
1089 numeric basic::max_coefficient() const
1094 numeric numeric::max_coefficient() const
1096 return abs_function::eval_numeric(*this);
1099 numeric add::max_coefficient() const
1101 epvector::const_iterator it = seq.begin();
1102 epvector::const_iterator itend = seq.end();
1103 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
1104 numeric cur_max = abs_function::eval_numeric(ex_to<numeric>(overall_coeff));
1105 while (it != itend) {
1107 GINAC_ASSERT(!is_exactly_a<numeric>(it->rest));
1108 a = abs_function::eval_numeric(ex_to<numeric>(it->coeff));
1116 numeric mul::max_coefficient() const
1118 #ifdef DO_GINAC_ASSERT
1119 epvector::const_iterator it = seq.begin();
1120 epvector::const_iterator itend = seq.end();
1121 while (it != itend) {
1122 GINAC_ASSERT(!is_exactly_a<numeric>(recombine_pair_to_ex(*it)));
1125 #endif // def DO_GINAC_ASSERT
1126 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
1127 return abs_function::eval_numeric(ex_to<numeric>(overall_coeff));
1131 /** Apply symmetric modular homomorphism to an expanded multivariate
1132 * polynomial. This function is usually used internally by heur_gcd().
1135 * @return mapped polynomial
1137 ex basic::smod(const numeric &xi) const
1142 ex numeric::smod(const numeric &xi) const
1144 return GiNaC::smod(*this, xi);
1147 ex add::smod(const numeric &xi) const
1150 newseq.reserve(seq.size()+1);
1151 epvector::const_iterator it = seq.begin();
1152 epvector::const_iterator itend = seq.end();
1153 while (it != itend) {
1154 GINAC_ASSERT(!is_exactly_a<numeric>(it->rest));
1155 numeric coeff = GiNaC::smod(ex_to<numeric>(it->coeff), xi);
1156 if (!coeff.is_zero())
1157 newseq.push_back(expair(it->rest, coeff));
1160 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
1161 numeric coeff = GiNaC::smod(ex_to<numeric>(overall_coeff), xi);
1162 return (new add(newseq,coeff))->setflag(status_flags::dynallocated);
1165 ex mul::smod(const numeric &xi) const
1167 #ifdef DO_GINAC_ASSERT
1168 epvector::const_iterator it = seq.begin();
1169 epvector::const_iterator itend = seq.end();
1170 while (it != itend) {
1171 GINAC_ASSERT(!is_exactly_a<numeric>(recombine_pair_to_ex(*it)));
1174 #endif // def DO_GINAC_ASSERT
1175 mul * mulcopyp = new mul(*this);
1176 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
1177 mulcopyp->overall_coeff = GiNaC::smod(ex_to<numeric>(overall_coeff),xi);
1178 mulcopyp->clearflag(status_flags::evaluated);
1179 mulcopyp->clearflag(status_flags::hash_calculated);
1180 return mulcopyp->setflag(status_flags::dynallocated);
1184 /** xi-adic polynomial interpolation */
1185 static ex interpolate(const ex &gamma, const numeric &xi, const ex &x, int degree_hint = 1)
1187 exvector g; g.reserve(degree_hint);
1189 numeric rxi = xi.inverse();
1190 for (int i=0; !e.is_zero(); i++) {
1192 g.push_back(gi * power(x, i));
1195 return (new add(g))->setflag(status_flags::dynallocated);
1198 /** Exception thrown by heur_gcd() to signal failure. */
1199 class gcdheu_failed {};
1201 /** Compute GCD of multivariate polynomials using the heuristic GCD algorithm.
1202 * get_symbol_stats() must have been called previously with the input
1203 * polynomials and an iterator to the first element of the sym_desc vector
1204 * passed in. This function is used internally by gcd().
1206 * @param a first multivariate polynomial (expanded)
1207 * @param b second multivariate polynomial (expanded)
1208 * @param ca cofactor of polynomial a (returned), NULL to suppress
1209 * calculation of cofactor
1210 * @param cb cofactor of polynomial b (returned), NULL to suppress
1211 * calculation of cofactor
1212 * @param var iterator to first element of vector of sym_desc structs
1213 * @return the GCD as a new expression
1215 * @exception gcdheu_failed() */
1216 static ex heur_gcd(const ex &a, const ex &b, ex *ca, ex *cb, sym_desc_vec::const_iterator var)
1222 // Algorithm only works for non-vanishing input polynomials
1223 if (a.is_zero() || b.is_zero())
1224 return (new fail())->setflag(status_flags::dynallocated);
1226 // GCD of two numeric values -> CLN
1227 if (is_exactly_a<numeric>(a) && is_exactly_a<numeric>(b)) {
1228 numeric g = gcd(ex_to<numeric>(a), ex_to<numeric>(b));
1230 *ca = ex_to<numeric>(a) / g;
1232 *cb = ex_to<numeric>(b) / g;
1236 // The first symbol is our main variable
1237 const ex &x = var->sym;
1239 // Remove integer content
1240 numeric gc = gcd(a.integer_content(), b.integer_content());
1241 numeric rgc = gc.inverse();
1244 int maxdeg = std::max(p.degree(x), q.degree(x));
1246 // Find evaluation point
1247 numeric mp = p.max_coefficient();
1248 numeric mq = q.max_coefficient();
1251 xi = mq * (*_num2_p) + (*_num2_p);
1253 xi = mp * (*_num2_p) + (*_num2_p);
1256 for (int t=0; t<6; t++) {
1257 if (xi.int_length() * maxdeg > 100000) {
1258 throw gcdheu_failed();
1261 // Apply evaluation homomorphism and calculate GCD
1263 ex gamma = heur_gcd(p.subs(x == xi, subs_options::no_pattern), q.subs(x == xi, subs_options::no_pattern), &cp, &cq, var+1).expand();
1264 if (!is_exactly_a<fail>(gamma)) {
1266 // Reconstruct polynomial from GCD of mapped polynomials
1267 ex g = interpolate(gamma, xi, x, maxdeg);
1269 // Remove integer content
1270 g /= g.integer_content();
1272 // If the calculated polynomial divides both p and q, this is the GCD
1274 if (divide_in_z(p, g, ca ? *ca : dummy, var) && divide_in_z(q, g, cb ? *cb : dummy, var)) {
1280 // Next evaluation point
1281 xi = iquo(xi * isqrt(isqrt(xi)) * numeric(73794), numeric(27011));
1283 return (new fail())->setflag(status_flags::dynallocated);
1287 /** Compute GCD (Greatest Common Divisor) of multivariate polynomials a(X)
1288 * and b(X) in Z[X]. Optionally also compute the cofactors of a and b,
1289 * defined by a = ca * gcd(a, b) and b = cb * gcd(a, b).
1291 * @param a first multivariate polynomial
1292 * @param b second multivariate polynomial
1293 * @param ca pointer to expression that will receive the cofactor of a, or NULL
1294 * @param cb pointer to expression that will receive the cofactor of b, or NULL
1295 * @param check_args check whether a and b are polynomials with rational
1296 * coefficients (defaults to "true")
1297 * @return the GCD as a new expression */
1298 ex gcd(const ex &a, const ex &b, ex *ca, ex *cb, bool check_args)
1304 // GCD of numerics -> CLN
1305 if (is_exactly_a<numeric>(a) && is_exactly_a<numeric>(b)) {
1306 numeric g = gcd(ex_to<numeric>(a), ex_to<numeric>(b));
1315 *ca = ex_to<numeric>(a) / g;
1317 *cb = ex_to<numeric>(b) / g;
1324 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial))) {
1325 throw(std::invalid_argument("gcd: arguments must be polynomials over the rationals"));
1328 // Partially factored cases (to avoid expanding large expressions)
1329 if (is_exactly_a<mul>(a)) {
1330 if (is_exactly_a<mul>(b) && b.nops() > a.nops())
1333 size_t num = a.nops();
1334 exvector g; g.reserve(num);
1335 exvector acc_ca; acc_ca.reserve(num);
1337 for (size_t i=0; i<num; i++) {
1338 ex part_ca, part_cb;
1339 g.push_back(gcd(a.op(i), part_b, &part_ca, &part_cb, check_args));
1340 acc_ca.push_back(part_ca);
1344 *ca = (new mul(acc_ca))->setflag(status_flags::dynallocated);
1347 return (new mul(g))->setflag(status_flags::dynallocated);
1348 } else if (is_exactly_a<mul>(b)) {
1349 if (is_exactly_a<mul>(a) && a.nops() > b.nops())
1352 size_t num = b.nops();
1353 exvector g; g.reserve(num);
1354 exvector acc_cb; acc_cb.reserve(num);
1356 for (size_t i=0; i<num; i++) {
1357 ex part_ca, part_cb;
1358 g.push_back(gcd(part_a, b.op(i), &part_ca, &part_cb, check_args));
1359 acc_cb.push_back(part_cb);
1365 *cb = (new mul(acc_cb))->setflag(status_flags::dynallocated);
1366 return (new mul(g))->setflag(status_flags::dynallocated);
1370 // Input polynomials of the form poly^n are sometimes also trivial
1371 if (is_exactly_a<power>(a)) {
1373 const ex& exp_a = a.op(1);
1374 if (is_exactly_a<power>(b)) {
1376 const ex& exp_b = b.op(1);
1377 if (p.is_equal(pb)) {
1378 // a = p^n, b = p^m, gcd = p^min(n, m)
1379 if (exp_a < exp_b) {
1383 *cb = power(p, exp_b - exp_a);
1384 return power(p, exp_a);
1387 *ca = power(p, exp_a - exp_b);
1390 return power(p, exp_b);
1394 ex p_gcd = gcd(p, pb, &p_co, &pb_co, check_args);
1395 if (p_gcd.is_equal(_ex1)) {
1396 // a(x) = p(x)^n, b(x) = p_b(x)^m, gcd (p, p_b) = 1 ==>
1403 // XXX: do I need to check for p_gcd = -1?
1405 // there are common factors:
1406 // a(x) = g(x)^n A(x)^n, b(x) = g(x)^m B(x)^m ==>
1407 // gcd(a, b) = g(x)^n gcd(A(x)^n, g(x)^(n-m) B(x)^m
1408 if (exp_a < exp_b) {
1409 return power(p_gcd, exp_a)*
1410 gcd(power(p_co, exp_a), power(p_gcd, exp_b-exp_a)*power(pb_co, exp_b), ca, cb, false);
1412 return power(p_gcd, exp_b)*
1413 gcd(power(p_gcd, exp_a - exp_b)*power(p_co, exp_a), power(pb_co, exp_b), ca, cb, false);
1415 } // p_gcd.is_equal(_ex1)
1419 if (p.is_equal(b)) {
1420 // a = p^n, b = p, gcd = p
1422 *ca = power(p, a.op(1) - 1);
1429 ex p_gcd = gcd(p, b, &p_co, &bpart_co, false);
1431 if (p_gcd.is_equal(_ex1)) {
1432 // a(x) = p(x)^n, gcd(p, b) = 1 ==> gcd(a, b) = 1
1439 // a(x) = g(x)^n A(x)^n, b(x) = g(x) B(x) ==> gcd(a, b) = g(x) gcd(g(x)^(n-1) A(x)^n, B(x))
1440 return p_gcd*gcd(power(p_gcd, exp_a-1)*power(p_co, exp_a), bpart_co, ca, cb, false);
1442 } // is_exactly_a<power>(b)
1444 } else if (is_exactly_a<power>(b)) {
1446 if (p.is_equal(a)) {
1447 // a = p, b = p^n, gcd = p
1451 *cb = power(p, b.op(1) - 1);
1456 const ex& exp_b(b.op(1));
1457 ex p_gcd = gcd(a, p, &apart_co, &p_co, false);
1458 if (p_gcd.is_equal(_ex1)) {
1459 // b=p(x)^n, gcd(a, p) = 1 ==> gcd(a, b) == 1
1466 // there are common factors:
1467 // a(x) = g(x) A(x), b(x) = g(x)^n B(x)^n ==> gcd = g(x) gcd(g(x)^(n-1) A(x)^n, B(x))
1469 return p_gcd*gcd(apart_co, power(p_gcd, exp_b-1)*power(p_co, exp_b), ca, cb, false);
1470 } // p_gcd.is_equal(_ex1)
1474 // Some trivial cases
1475 ex aex = a.expand(), bex = b.expand();
1476 if (aex.is_zero()) {
1483 if (bex.is_zero()) {
1490 if (aex.is_equal(_ex1) || bex.is_equal(_ex1)) {
1498 if (a.is_equal(b)) {
1507 if (is_a<symbol>(aex)) {
1508 if (! bex.subs(aex==_ex0, subs_options::no_pattern).is_zero()) {
1517 if (is_a<symbol>(bex)) {
1518 if (! aex.subs(bex==_ex0, subs_options::no_pattern).is_zero()) {
1527 // Gather symbol statistics
1528 sym_desc_vec sym_stats;
1529 get_symbol_stats(a, b, sym_stats);
1531 // The symbol with least degree is our main variable
1532 sym_desc_vec::const_iterator var = sym_stats.begin();
1533 const ex &x = var->sym;
1535 // Cancel trivial common factor
1536 int ldeg_a = var->ldeg_a;
1537 int ldeg_b = var->ldeg_b;
1538 int min_ldeg = std::min(ldeg_a,ldeg_b);
1540 ex common = power(x, min_ldeg);
1541 return gcd((aex / common).expand(), (bex / common).expand(), ca, cb, false) * common;
1544 // Try to eliminate variables
1545 if (var->deg_a == 0) {
1546 ex bex_u, bex_c, bex_p;
1547 bex.unitcontprim(x, bex_u, bex_c, bex_p);
1548 ex g = gcd(aex, bex_c, ca, cb, false);
1550 *cb *= bex_u * bex_p;
1552 } else if (var->deg_b == 0) {
1553 ex aex_u, aex_c, aex_p;
1554 aex.unitcontprim(x, aex_u, aex_c, aex_p);
1555 ex g = gcd(aex_c, bex, ca, cb, false);
1557 *ca *= aex_u * aex_p;
1561 // Try heuristic algorithm first, fall back to PRS if that failed
1564 g = heur_gcd(aex, bex, ca, cb, var);
1565 } catch (gcdheu_failed) {
1568 if (is_exactly_a<fail>(g)) {
1572 g = sr_gcd(aex, bex, var);
1573 if (g.is_equal(_ex1)) {
1574 // Keep cofactors factored if possible
1581 divide(aex, g, *ca, false);
1583 divide(bex, g, *cb, false);
1586 if (g.is_equal(_ex1)) {
1587 // Keep cofactors factored if possible
1599 /** Compute LCM (Least Common Multiple) of multivariate polynomials in Z[X].
1601 * @param a first multivariate polynomial
1602 * @param b second multivariate polynomial
1603 * @param check_args check whether a and b are polynomials with rational
1604 * coefficients (defaults to "true")
1605 * @return the LCM as a new expression */
1606 ex lcm(const ex &a, const ex &b, bool check_args)
1608 if (is_exactly_a<numeric>(a) && is_exactly_a<numeric>(b))
1609 return lcm(ex_to<numeric>(a), ex_to<numeric>(b));
1610 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
1611 throw(std::invalid_argument("lcm: arguments must be polynomials over the rationals"));
1614 ex g = gcd(a, b, &ca, &cb, false);
1620 * Square-free factorization
1623 /** Compute square-free factorization of multivariate polynomial a(x) using
1624 * Yun's algorithm. Used internally by sqrfree().
1626 * @param a multivariate polynomial over Z[X], treated here as univariate
1628 * @param x variable to factor in
1629 * @return vector of factors sorted in ascending degree */
1630 static exvector sqrfree_yun(const ex &a, const symbol &x)
1636 if (g.is_equal(_ex1)) {
1647 } while (!z.is_zero());
1652 /** Compute a square-free factorization of a multivariate polynomial in Q[X].
1654 * @param a multivariate polynomial over Q[X]
1655 * @param l lst of variables to factor in, may be left empty for autodetection
1656 * @return a square-free factorization of \p a.
1659 * A polynomial \f$p(X) \in C[X]\f$ is said <EM>square-free</EM>
1660 * if, whenever any two polynomials \f$q(X)\f$ and \f$r(X)\f$
1663 * p(X) = q(X)^2 r(X),
1665 * we have \f$q(X) \in C\f$.
1666 * This means that \f$p(X)\f$ has no repeated factors, apart
1667 * eventually from constants.
1668 * Given a polynomial \f$p(X) \in C[X]\f$, we say that the
1671 * p(X) = b \cdot p_1(X)^{a_1} \cdot p_2(X)^{a_2} \cdots p_r(X)^{a_r}
1673 * is a <EM>square-free factorization</EM> of \f$p(X)\f$ if the
1674 * following conditions hold:
1675 * -# \f$b \in C\f$ and \f$b \neq 0\f$;
1676 * -# \f$a_i\f$ is a positive integer for \f$i = 1, \ldots, r\f$;
1677 * -# the degree of the polynomial \f$p_i\f$ is strictly positive
1678 * for \f$i = 1, \ldots, r\f$;
1679 * -# the polynomial \f$\Pi_{i=1}^r p_i(X)\f$ is square-free.
1681 * Square-free factorizations need not be unique. For example, if
1682 * \f$a_i\f$ is even, we could change the polynomial \f$p_i(X)\f$
1683 * into \f$-p_i(X)\f$.
1684 * Observe also that the factors \f$p_i(X)\f$ need not be irreducible
1687 ex sqrfree(const ex &a, const lst &l)
1689 if (is_exactly_a<numeric>(a) || // algorithm does not trap a==0
1690 is_a<symbol>(a)) // shortcut
1693 // If no lst of variables to factorize in was specified we have to
1694 // invent one now. Maybe one can optimize here by reversing the order
1695 // or so, I don't know.
1699 get_symbol_stats(a, _ex0, sdv);
1700 sym_desc_vec::const_iterator it = sdv.begin(), itend = sdv.end();
1701 while (it != itend) {
1702 args.append(it->sym);
1709 // Find the symbol to factor in at this stage
1710 if (!is_a<symbol>(args.op(0)))
1711 throw (std::runtime_error("sqrfree(): invalid factorization variable"));
1712 const symbol &x = ex_to<symbol>(args.op(0));
1714 // convert the argument from something in Q[X] to something in Z[X]
1715 const numeric lcm = lcm_of_coefficients_denominators(a);
1716 const ex tmp = multiply_lcm(a,lcm);
1719 exvector factors = sqrfree_yun(tmp, x);
1721 // construct the next list of symbols with the first element popped
1723 newargs.remove_first();
1725 // recurse down the factors in remaining variables
1726 if (newargs.nops()>0) {
1727 exvector::iterator i = factors.begin();
1728 while (i != factors.end()) {
1729 *i = sqrfree(*i, newargs);
1734 // Done with recursion, now construct the final result
1736 exvector::const_iterator it = factors.begin(), itend = factors.end();
1737 for (int p = 1; it!=itend; ++it, ++p)
1738 result *= power(*it, p);
1740 // Yun's algorithm does not account for constant factors. (For univariate
1741 // polynomials it works only in the monic case.) We can correct this by
1742 // inserting what has been lost back into the result. For completeness
1743 // we'll also have to recurse down that factor in the remaining variables.
1744 if (newargs.nops()>0)
1745 result *= sqrfree(quo(tmp, result, x), newargs);
1747 result *= quo(tmp, result, x);
1749 // Put in the reational overall factor again and return
1750 return result * lcm.inverse();
1754 /** Compute square-free partial fraction decomposition of rational function
1757 * @param a rational function over Z[x], treated as univariate polynomial
1759 * @param x variable to factor in
1760 * @return decomposed rational function */
1761 ex sqrfree_parfrac(const ex & a, const symbol & x)
1763 // Find numerator and denominator
1764 ex nd = numer_denom(a);
1765 ex numer = nd.op(0), denom = nd.op(1);
1766 //clog << "numer = " << numer << ", denom = " << denom << endl;
1768 // Convert N(x)/D(x) -> Q(x) + R(x)/D(x), so degree(R) < degree(D)
1769 ex red_poly = quo(numer, denom, x), red_numer = rem(numer, denom, x).expand();
1770 //clog << "red_poly = " << red_poly << ", red_numer = " << red_numer << endl;
1772 // Factorize denominator and compute cofactors
1773 exvector yun = sqrfree_yun(denom, x);
1774 //clog << "yun factors: " << exprseq(yun) << endl;
1775 size_t num_yun = yun.size();
1776 exvector factor; factor.reserve(num_yun);
1777 exvector cofac; cofac.reserve(num_yun);
1778 for (size_t i=0; i<num_yun; i++) {
1779 if (!yun[i].is_equal(_ex1)) {
1780 for (size_t j=0; j<=i; j++) {
1781 factor.push_back(pow(yun[i], j+1));
1783 for (size_t k=0; k<num_yun; k++) {
1785 prod *= pow(yun[k], i-j);
1787 prod *= pow(yun[k], k+1);
1789 cofac.push_back(prod.expand());
1793 size_t num_factors = factor.size();
1794 //clog << "factors : " << exprseq(factor) << endl;
1795 //clog << "cofactors: " << exprseq(cofac) << endl;
1797 // Construct coefficient matrix for decomposition
1798 int max_denom_deg = denom.degree(x);
1799 matrix sys(max_denom_deg + 1, num_factors);
1800 matrix rhs(max_denom_deg + 1, 1);
1801 for (int i=0; i<=max_denom_deg; i++) {
1802 for (size_t j=0; j<num_factors; j++)
1803 sys(i, j) = cofac[j].coeff(x, i);
1804 rhs(i, 0) = red_numer.coeff(x, i);
1806 //clog << "coeffs: " << sys << endl;
1807 //clog << "rhs : " << rhs << endl;
1809 // Solve resulting linear system
1810 matrix vars(num_factors, 1);
1811 for (size_t i=0; i<num_factors; i++)
1812 vars(i, 0) = symbol();
1813 matrix sol = sys.solve(vars, rhs);
1815 // Sum up decomposed fractions
1817 for (size_t i=0; i<num_factors; i++)
1818 sum += sol(i, 0) / factor[i];
1820 return red_poly + sum;
1825 * Normal form of rational functions
1829 * Note: The internal normal() functions (= basic::normal() and overloaded
1830 * functions) all return lists of the form {numerator, denominator}. This
1831 * is to get around mul::eval()'s automatic expansion of numeric coefficients.
1832 * E.g. (a+b)/3 is automatically converted to a/3+b/3 but we want to keep
1833 * the information that (a+b) is the numerator and 3 is the denominator.
1837 /** Create a symbol for replacing the expression "e" (or return a previously
1838 * assigned symbol). The symbol and expression are appended to repl, for
1839 * a later application of subs().
1840 * @see ex::normal */
1841 static ex replace_with_symbol(const ex & e, exmap & repl, exmap & rev_lookup)
1843 // Expression already replaced? Then return the assigned symbol
1844 exmap::const_iterator it = rev_lookup.find(e);
1845 if (it != rev_lookup.end())
1848 // Otherwise create new symbol and add to list, taking care that the
1849 // replacement expression doesn't itself contain symbols from repl,
1850 // because subs() is not recursive
1851 ex es = (new symbol)->setflag(status_flags::dynallocated);
1852 ex e_replaced = e.subs(repl, subs_options::no_pattern);
1853 repl.insert(std::make_pair(es, e_replaced));
1854 rev_lookup.insert(std::make_pair(e_replaced, es));
1858 /** Create a symbol for replacing the expression "e" (or return a previously
1859 * assigned symbol). The symbol and expression are appended to repl, and the
1860 * symbol is returned.
1861 * @see basic::to_rational
1862 * @see basic::to_polynomial */
1863 static ex replace_with_symbol(const ex & e, exmap & repl)
1865 // Expression already replaced? Then return the assigned symbol
1866 for (exmap::const_iterator it = repl.begin(); it != repl.end(); ++it)
1867 if (it->second.is_equal(e))
1870 // Otherwise create new symbol and add to list, taking care that the
1871 // replacement expression doesn't itself contain symbols from repl,
1872 // because subs() is not recursive
1873 ex es = (new symbol)->setflag(status_flags::dynallocated);
1874 ex e_replaced = e.subs(repl, subs_options::no_pattern);
1875 repl.insert(std::make_pair(es, e_replaced));
1880 /** Function object to be applied by basic::normal(). */
1881 struct normal_map_function : public map_function {
1883 normal_map_function(int l) : level(l) {}
1884 ex operator()(const ex & e) { return normal(e, level); }
1887 /** Default implementation of ex::normal(). It normalizes the children and
1888 * replaces the object with a temporary symbol.
1889 * @see ex::normal */
1890 ex basic::normal(exmap & repl, exmap & rev_lookup, int level) const
1893 return (new lst(replace_with_symbol(*this, repl, rev_lookup), _ex1))->setflag(status_flags::dynallocated);
1896 return (new lst(replace_with_symbol(*this, repl, rev_lookup), _ex1))->setflag(status_flags::dynallocated);
1897 else if (level == -max_recursion_level)
1898 throw(std::runtime_error("max recursion level reached"));
1900 normal_map_function map_normal(level - 1);
1901 return (new lst(replace_with_symbol(map(map_normal), repl, rev_lookup), _ex1))->setflag(status_flags::dynallocated);
1907 /** Implementation of ex::normal() for symbols. This returns the unmodified symbol.
1908 * @see ex::normal */
1909 ex symbol::normal(exmap & repl, exmap & rev_lookup, int level) const
1911 return (new lst(*this, _ex1))->setflag(status_flags::dynallocated);
1915 /** Implementation of ex::normal() for a numeric. It splits complex numbers
1916 * into re+I*im and replaces I and non-rational real numbers with a temporary
1918 * @see ex::normal */
1919 ex numeric::normal(exmap & repl, exmap & rev_lookup, int level) const
1921 numeric num = numer();
1924 if (num.is_real()) {
1925 if (!num.is_integer())
1926 numex = replace_with_symbol(numex, repl, rev_lookup);
1928 numeric re = num.real(), im = num.imag();
1929 ex re_ex = re.is_rational() ? re : replace_with_symbol(re, repl, rev_lookup);
1930 ex im_ex = im.is_rational() ? im : replace_with_symbol(im, repl, rev_lookup);
1931 numex = re_ex + im_ex * replace_with_symbol(I, repl, rev_lookup);
1934 // Denominator is always a real integer (see numeric::denom())
1935 return (new lst(numex, denom()))->setflag(status_flags::dynallocated);
1939 /** Fraction cancellation.
1940 * @param n numerator
1941 * @param d denominator
1942 * @return cancelled fraction {n, d} as a list */
1943 static ex frac_cancel(const ex &n, const ex &d)
1947 numeric pre_factor = *_num1_p;
1949 //std::clog << "frac_cancel num = " << num << ", den = " << den << std::endl;
1951 // Handle trivial case where denominator is 1
1952 if (den.is_equal(_ex1))
1953 return (new lst(num, den))->setflag(status_flags::dynallocated);
1955 // Handle special cases where numerator or denominator is 0
1957 return (new lst(num, _ex1))->setflag(status_flags::dynallocated);
1958 if (den.expand().is_zero())
1959 throw(std::overflow_error("frac_cancel: division by zero in frac_cancel"));
1961 // Bring numerator and denominator to Z[X] by multiplying with
1962 // LCM of all coefficients' denominators
1963 numeric num_lcm = lcm_of_coefficients_denominators(num);
1964 numeric den_lcm = lcm_of_coefficients_denominators(den);
1965 num = multiply_lcm(num, num_lcm);
1966 den = multiply_lcm(den, den_lcm);
1967 pre_factor = den_lcm / num_lcm;
1969 // Cancel GCD from numerator and denominator
1971 if (gcd(num, den, &cnum, &cden, false) != _ex1) {
1976 // Make denominator unit normal (i.e. coefficient of first symbol
1977 // as defined by get_first_symbol() is made positive)
1978 if (is_exactly_a<numeric>(den)) {
1979 if (ex_to<numeric>(den).is_negative()) {
1985 if (get_first_symbol(den, x)) {
1986 GINAC_ASSERT(is_exactly_a<numeric>(den.unit(x)));
1987 if (ex_to<numeric>(den.unit(x)).is_negative()) {
1994 // Return result as list
1995 //std::clog << " returns num = " << num << ", den = " << den << ", pre_factor = " << pre_factor << std::endl;
1996 return (new lst(num * pre_factor.numer(), den * pre_factor.denom()))->setflag(status_flags::dynallocated);
2000 /** Implementation of ex::normal() for a sum. It expands terms and performs
2001 * fractional addition.
2002 * @see ex::normal */
2003 ex add::normal(exmap & repl, exmap & rev_lookup, int level) const
2006 return (new lst(replace_with_symbol(*this, repl, rev_lookup), _ex1))->setflag(status_flags::dynallocated);
2007 else if (level == -max_recursion_level)
2008 throw(std::runtime_error("max recursion level reached"));
2010 // Normalize children and split each one into numerator and denominator
2011 exvector nums, dens;
2012 nums.reserve(seq.size()+1);
2013 dens.reserve(seq.size()+1);
2014 epvector::const_iterator it = seq.begin(), itend = seq.end();
2015 while (it != itend) {
2016 ex n = ex_to<basic>(recombine_pair_to_ex(*it)).normal(repl, rev_lookup, level-1);
2017 nums.push_back(n.op(0));
2018 dens.push_back(n.op(1));
2021 ex n = ex_to<numeric>(overall_coeff).normal(repl, rev_lookup, level-1);
2022 nums.push_back(n.op(0));
2023 dens.push_back(n.op(1));
2024 GINAC_ASSERT(nums.size() == dens.size());
2026 // Now, nums is a vector of all numerators and dens is a vector of
2028 //std::clog << "add::normal uses " << nums.size() << " summands:\n";
2030 // Add fractions sequentially
2031 exvector::const_iterator num_it = nums.begin(), num_itend = nums.end();
2032 exvector::const_iterator den_it = dens.begin(), den_itend = dens.end();
2033 //std::clog << " num = " << *num_it << ", den = " << *den_it << std::endl;
2034 ex num = *num_it++, den = *den_it++;
2035 while (num_it != num_itend) {
2036 //std::clog << " num = " << *num_it << ", den = " << *den_it << std::endl;
2037 ex next_num = *num_it++, next_den = *den_it++;
2039 // Trivially add sequences of fractions with identical denominators
2040 while ((den_it != den_itend) && next_den.is_equal(*den_it)) {
2041 next_num += *num_it;
2045 // Additiion of two fractions, taking advantage of the fact that
2046 // the heuristic GCD algorithm computes the cofactors at no extra cost
2047 ex co_den1, co_den2;
2048 ex g = gcd(den, next_den, &co_den1, &co_den2, false);
2049 num = ((num * co_den2) + (next_num * co_den1)).expand();
2050 den *= co_den2; // this is the lcm(den, next_den)
2052 //std::clog << " common denominator = " << den << std::endl;
2054 // Cancel common factors from num/den
2055 return frac_cancel(num, den);
2059 /** Implementation of ex::normal() for a product. It cancels common factors
2061 * @see ex::normal() */
2062 ex mul::normal(exmap & repl, exmap & rev_lookup, int level) const
2065 return (new lst(replace_with_symbol(*this, repl, rev_lookup), _ex1))->setflag(status_flags::dynallocated);
2066 else if (level == -max_recursion_level)
2067 throw(std::runtime_error("max recursion level reached"));
2069 // Normalize children, separate into numerator and denominator
2070 exvector num; num.reserve(seq.size());
2071 exvector den; den.reserve(seq.size());
2073 epvector::const_iterator it = seq.begin(), itend = seq.end();
2074 while (it != itend) {
2075 n = ex_to<basic>(recombine_pair_to_ex(*it)).normal(repl, rev_lookup, level-1);
2076 num.push_back(n.op(0));
2077 den.push_back(n.op(1));
2080 n = ex_to<numeric>(overall_coeff).normal(repl, rev_lookup, level-1);
2081 num.push_back(n.op(0));
2082 den.push_back(n.op(1));
2084 // Perform fraction cancellation
2085 return frac_cancel((new mul(num))->setflag(status_flags::dynallocated),
2086 (new mul(den))->setflag(status_flags::dynallocated));
2090 /** Implementation of ex::normal([B) for powers. It normalizes the basis,
2091 * distributes integer exponents to numerator and denominator, and replaces
2092 * non-integer powers by temporary symbols.
2093 * @see ex::normal */
2094 ex power::normal(exmap & repl, exmap & rev_lookup, int level) const
2097 return (new lst(replace_with_symbol(*this, repl, rev_lookup), _ex1))->setflag(status_flags::dynallocated);
2098 else if (level == -max_recursion_level)
2099 throw(std::runtime_error("max recursion level reached"));
2101 // Normalize basis and exponent (exponent gets reassembled)
2102 ex n_basis = ex_to<basic>(basis).normal(repl, rev_lookup, level-1);
2103 ex n_exponent = ex_to<basic>(exponent).normal(repl, rev_lookup, level-1);
2104 n_exponent = n_exponent.op(0) / n_exponent.op(1);
2106 if (n_exponent.info(info_flags::integer)) {
2108 if (n_exponent.info(info_flags::positive)) {
2110 // (a/b)^n -> {a^n, b^n}
2111 return (new lst(power(n_basis.op(0), n_exponent), power(n_basis.op(1), n_exponent)))->setflag(status_flags::dynallocated);
2113 } else if (n_exponent.info(info_flags::negative)) {
2115 // (a/b)^-n -> {b^n, a^n}
2116 return (new lst(power(n_basis.op(1), -n_exponent), power(n_basis.op(0), -n_exponent)))->setflag(status_flags::dynallocated);
2121 if (n_exponent.info(info_flags::positive)) {
2123 // (a/b)^x -> {sym((a/b)^x), 1}
2124 return (new lst(replace_with_symbol(power(n_basis.op(0) / n_basis.op(1), n_exponent), repl, rev_lookup), _ex1))->setflag(status_flags::dynallocated);
2126 } else if (n_exponent.info(info_flags::negative)) {
2128 if (n_basis.op(1).is_equal(_ex1)) {
2130 // a^-x -> {1, sym(a^x)}
2131 return (new lst(_ex1, replace_with_symbol(power(n_basis.op(0), -n_exponent), repl, rev_lookup)))->setflag(status_flags::dynallocated);
2135 // (a/b)^-x -> {sym((b/a)^x), 1}
2136 return (new lst(replace_with_symbol(power(n_basis.op(1) / n_basis.op(0), -n_exponent), repl, rev_lookup), _ex1))->setflag(status_flags::dynallocated);
2141 // (a/b)^x -> {sym((a/b)^x, 1}
2142 return (new lst(replace_with_symbol(power(n_basis.op(0) / n_basis.op(1), n_exponent), repl, rev_lookup), _ex1))->setflag(status_flags::dynallocated);
2146 /** Implementation of ex::normal() for pseries. It normalizes each coefficient
2147 * and replaces the series by a temporary symbol.
2148 * @see ex::normal */
2149 ex pseries::normal(exmap & repl, exmap & rev_lookup, int level) const
2152 epvector::const_iterator i = seq.begin(), end = seq.end();
2154 ex restexp = i->rest.normal();
2155 if (!restexp.is_zero())
2156 newseq.push_back(expair(restexp, i->coeff));
2159 ex n = pseries(relational(var,point), newseq);
2160 return (new lst(replace_with_symbol(n, repl, rev_lookup), _ex1))->setflag(status_flags::dynallocated);
2164 /** Normalization of rational functions.
2165 * This function converts an expression to its normal form
2166 * "numerator/denominator", where numerator and denominator are (relatively
2167 * prime) polynomials. Any subexpressions which are not rational functions
2168 * (like non-rational numbers, non-integer powers or functions like sin(),
2169 * cos() etc.) are replaced by temporary symbols which are re-substituted by
2170 * the (normalized) subexpressions before normal() returns (this way, any
2171 * expression can be treated as a rational function). normal() is applied
2172 * recursively to arguments of functions etc.
2174 * @param level maximum depth of recursion
2175 * @return normalized expression */
2176 ex ex::normal(int level) const
2178 exmap repl, rev_lookup;
2180 ex e = bp->normal(repl, rev_lookup, level);
2181 GINAC_ASSERT(is_a<lst>(e));
2183 // Re-insert replaced symbols
2185 e = e.subs(repl, subs_options::no_pattern);
2187 // Convert {numerator, denominator} form back to fraction
2188 return e.op(0) / e.op(1);
2191 /** Get numerator of an expression. If the expression is not of the normal
2192 * form "numerator/denominator", it is first converted to this form and
2193 * then the numerator is returned.
2196 * @return numerator */
2197 ex ex::numer() const
2199 exmap repl, rev_lookup;
2201 ex e = bp->normal(repl, rev_lookup, 0);
2202 GINAC_ASSERT(is_a<lst>(e));
2204 // Re-insert replaced symbols
2208 return e.op(0).subs(repl, subs_options::no_pattern);
2211 /** Get denominator of an expression. If the expression is not of the normal
2212 * form "numerator/denominator", it is first converted to this form and
2213 * then the denominator is returned.
2216 * @return denominator */
2217 ex ex::denom() const
2219 exmap repl, rev_lookup;
2221 ex e = bp->normal(repl, rev_lookup, 0);
2222 GINAC_ASSERT(is_a<lst>(e));
2224 // Re-insert replaced symbols
2228 return e.op(1).subs(repl, subs_options::no_pattern);
2231 /** Get numerator and denominator of an expression. If the expresison is not
2232 * of the normal form "numerator/denominator", it is first converted to this
2233 * form and then a list [numerator, denominator] is returned.
2236 * @return a list [numerator, denominator] */
2237 ex ex::numer_denom() const
2239 exmap repl, rev_lookup;
2241 ex e = bp->normal(repl, rev_lookup, 0);
2242 GINAC_ASSERT(is_a<lst>(e));
2244 // Re-insert replaced symbols
2248 return e.subs(repl, subs_options::no_pattern);
2252 /** Rationalization of non-rational functions.
2253 * This function converts a general expression to a rational function
2254 * by replacing all non-rational subexpressions (like non-rational numbers,
2255 * non-integer powers or functions like sin(), cos() etc.) to temporary
2256 * symbols. This makes it possible to use functions like gcd() and divide()
2257 * on non-rational functions by applying to_rational() on the arguments,
2258 * calling the desired function and re-substituting the temporary symbols
2259 * in the result. To make the last step possible, all temporary symbols and
2260 * their associated expressions are collected in the map specified by the
2261 * repl parameter, ready to be passed as an argument to ex::subs().
2263 * @param repl collects all temporary symbols and their replacements
2264 * @return rationalized expression */
2265 ex ex::to_rational(exmap & repl) const
2267 return bp->to_rational(repl);
2270 // GiNaC 1.1 compatibility function
2271 ex ex::to_rational(lst & repl_lst) const
2273 // Convert lst to exmap
2275 for (lst::const_iterator it = repl_lst.begin(); it != repl_lst.end(); ++it)
2276 m.insert(std::make_pair(it->op(0), it->op(1)));
2278 ex ret = bp->to_rational(m);
2280 // Convert exmap back to lst
2281 repl_lst.remove_all();
2282 for (exmap::const_iterator it = m.begin(); it != m.end(); ++it)
2283 repl_lst.append(it->first == it->second);
2288 ex ex::to_polynomial(exmap & repl) const
2290 return bp->to_polynomial(repl);
2293 // GiNaC 1.1 compatibility function
2294 ex ex::to_polynomial(lst & repl_lst) const
2296 // Convert lst to exmap
2298 for (lst::const_iterator it = repl_lst.begin(); it != repl_lst.end(); ++it)
2299 m.insert(std::make_pair(it->op(0), it->op(1)));
2301 ex ret = bp->to_polynomial(m);
2303 // Convert exmap back to lst
2304 repl_lst.remove_all();
2305 for (exmap::const_iterator it = m.begin(); it != m.end(); ++it)
2306 repl_lst.append(it->first == it->second);
2311 /** Default implementation of ex::to_rational(). This replaces the object with
2312 * a temporary symbol. */
2313 ex basic::to_rational(exmap & repl) const
2315 return replace_with_symbol(*this, repl);
2318 ex basic::to_polynomial(exmap & repl) const
2320 return replace_with_symbol(*this, repl);
2324 /** Implementation of ex::to_rational() for symbols. This returns the
2325 * unmodified symbol. */
2326 ex symbol::to_rational(exmap & repl) const
2331 /** Implementation of ex::to_polynomial() for symbols. This returns the
2332 * unmodified symbol. */
2333 ex symbol::to_polynomial(exmap & repl) const
2339 /** Implementation of ex::to_rational() for a numeric. It splits complex
2340 * numbers into re+I*im and replaces I and non-rational real numbers with a
2341 * temporary symbol. */
2342 ex numeric::to_rational(exmap & repl) const
2346 return replace_with_symbol(*this, repl);
2348 numeric re = real();
2349 numeric im = imag();
2350 ex re_ex = re.is_rational() ? re : replace_with_symbol(re, repl);
2351 ex im_ex = im.is_rational() ? im : replace_with_symbol(im, repl);
2352 return re_ex + im_ex * replace_with_symbol(I, repl);
2357 /** Implementation of ex::to_polynomial() for a numeric. It splits complex
2358 * numbers into re+I*im and replaces I and non-integer real numbers with a
2359 * temporary symbol. */
2360 ex numeric::to_polynomial(exmap & repl) const
2364 return replace_with_symbol(*this, repl);
2366 numeric re = real();
2367 numeric im = imag();
2368 ex re_ex = re.is_integer() ? re : replace_with_symbol(re, repl);
2369 ex im_ex = im.is_integer() ? im : replace_with_symbol(im, repl);
2370 return re_ex + im_ex * replace_with_symbol(I, repl);
2376 /** Implementation of ex::to_rational() for powers. It replaces non-integer
2377 * powers by temporary symbols. */
2378 ex power::to_rational(exmap & repl) const
2380 if (exponent.info(info_flags::integer))
2381 return power(basis.to_rational(repl), exponent);
2383 return replace_with_symbol(*this, repl);
2386 /** Implementation of ex::to_polynomial() for powers. It replaces non-posint
2387 * powers by temporary symbols. */
2388 ex power::to_polynomial(exmap & repl) const
2390 if (exponent.info(info_flags::posint))
2391 return power(basis.to_rational(repl), exponent);
2392 else if (exponent.info(info_flags::negint))
2393 return power(replace_with_symbol(power(basis, _ex_1), repl), -exponent);
2395 return replace_with_symbol(*this, repl);
2399 /** Implementation of ex::to_rational() for expairseqs. */
2400 ex expairseq::to_rational(exmap & repl) 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)));
2409 ex oc = overall_coeff.to_rational(repl);
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());
2417 /** Implementation of ex::to_polynomial() for expairseqs. */
2418 ex expairseq::to_polynomial(exmap & repl) const
2421 s.reserve(seq.size());
2422 epvector::const_iterator i = seq.begin(), end = seq.end();
2424 s.push_back(split_ex_to_pair(recombine_pair_to_ex(*i).to_polynomial(repl)));
2427 ex oc = overall_coeff.to_polynomial(repl);
2428 if (oc.info(info_flags::numeric))
2429 return thisexpairseq(s, overall_coeff);
2431 s.push_back(combine_ex_with_coeff_to_pair(oc, _ex1));
2432 return thisexpairseq(s, default_overall_coeff());
2436 /** Remove the common factor in the terms of a sum 'e' by calculating the GCD,
2437 * and multiply it into the expression 'factor' (which needs to be initialized
2438 * to 1, unless you're accumulating factors). */
2439 static ex find_common_factor(const ex & e, ex & factor, exmap & repl)
2441 if (is_exactly_a<add>(e)) {
2443 size_t num = e.nops();
2444 exvector terms; terms.reserve(num);
2447 // Find the common GCD
2448 for (size_t i=0; i<num; i++) {
2449 ex x = e.op(i).to_polynomial(repl);
2451 if (is_exactly_a<add>(x) || is_exactly_a<mul>(x)) {
2453 x = find_common_factor(x, f, repl);
2465 if (gc.is_equal(_ex1))
2468 // The GCD is the factor we pull out
2471 // Now divide all terms by the GCD
2472 for (size_t i=0; i<num; i++) {
2475 // Try to avoid divide() because it expands the polynomial
2477 if (is_exactly_a<mul>(t)) {
2478 for (size_t j=0; j<t.nops(); j++) {
2479 if (t.op(j).is_equal(gc)) {
2480 exvector v; v.reserve(t.nops());
2481 for (size_t k=0; k<t.nops(); k++) {
2485 v.push_back(t.op(k));
2487 t = (new mul(v))->setflag(status_flags::dynallocated);
2497 return (new add(terms))->setflag(status_flags::dynallocated);
2499 } else if (is_exactly_a<mul>(e)) {
2501 size_t num = e.nops();
2502 exvector v; v.reserve(num);
2504 for (size_t i=0; i<num; i++)
2505 v.push_back(find_common_factor(e.op(i), factor, repl));
2507 return (new mul(v))->setflag(status_flags::dynallocated);
2509 } else if (is_exactly_a<power>(e)) {
2510 const ex e_exp(e.op(1));
2511 if (e_exp.info(info_flags::posint)) {
2512 ex eb = e.op(0).to_polynomial(repl);
2513 ex factor_local(_ex1);
2514 ex pre_res = find_common_factor(eb, factor_local, repl);
2515 factor *= power(factor_local, e_exp);
2516 return power(pre_res, e_exp);
2519 return e.to_polynomial(repl);
2526 /** Collect common factors in sums. This converts expressions like
2527 * 'a*(b*x+b*y)' to 'a*b*(x+y)'. */
2528 ex collect_common_factors(const ex & e)
2530 if (is_exactly_a<add>(e) || is_exactly_a<mul>(e) || is_exactly_a<power>(e)) {
2534 ex r = find_common_factor(e, factor, repl);
2535 return factor.subs(repl, subs_options::no_pattern) * r.subs(repl, subs_options::no_pattern);
2542 /** Resultant of two expressions e1,e2 with respect to symbol s.
2543 * Method: Compute determinant of Sylvester matrix of e1,e2,s. */
2544 ex resultant(const ex & e1, const ex & e2, const ex & s)
2546 const ex ee1 = e1.expand();
2547 const ex ee2 = e2.expand();
2548 if (!ee1.info(info_flags::polynomial) ||
2549 !ee2.info(info_flags::polynomial))
2550 throw(std::runtime_error("resultant(): arguments must be polynomials"));
2552 const int h1 = ee1.degree(s);
2553 const int l1 = ee1.ldegree(s);
2554 const int h2 = ee2.degree(s);
2555 const int l2 = ee2.ldegree(s);
2557 const int msize = h1 + h2;
2558 matrix m(msize, msize);
2560 for (int l = h1; l >= l1; --l) {
2561 const ex e = ee1.coeff(s, l);
2562 for (int k = 0; k < h2; ++k)
2565 for (int l = h2; l >= l2; --l) {
2566 const ex e = ee2.coeff(s, l);
2567 for (int k = 0; k < h1; ++k)
2568 m(k+h2, k+h2-l) = e;
2571 return m.determinant();
2575 } // namespace GiNaC