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-2008 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
34 #include "expairseq.h"
41 #include "relational.h"
42 #include "operators.h"
50 // If comparing expressions (ex::compare()) is fast, you can set this to 1.
51 // Some routines like quo(), rem() and gcd() will then return a quick answer
52 // when they are called with two identical arguments.
53 #define FAST_COMPARE 1
55 // Set this if you want divide_in_z() to use remembering
56 #define USE_REMEMBER 0
58 // Set this if you want divide_in_z() to use trial division followed by
59 // polynomial interpolation (always slower except for completely dense
61 #define USE_TRIAL_DIVISION 0
63 // Set this to enable some statistical output for the GCD routines
68 // Statistics variables
69 static int gcd_called = 0;
70 static int sr_gcd_called = 0;
71 static int heur_gcd_called = 0;
72 static int heur_gcd_failed = 0;
74 // Print statistics at end of program
75 static struct _stat_print {
78 std::cout << "gcd() called " << gcd_called << " times\n";
79 std::cout << "sr_gcd() called " << sr_gcd_called << " times\n";
80 std::cout << "heur_gcd() called " << heur_gcd_called << " times\n";
81 std::cout << "heur_gcd() failed " << heur_gcd_failed << " times\n";
87 /** Return pointer to first symbol found in expression. Due to GiNaC's
88 * internal ordering of terms, it may not be obvious which symbol this
89 * function returns for a given expression.
91 * @param e expression to search
92 * @param x first symbol found (returned)
93 * @return "false" if no symbol was found, "true" otherwise */
94 static bool get_first_symbol(const ex &e, ex &x)
96 if (is_a<symbol>(e)) {
99 } else if (is_exactly_a<add>(e) || is_exactly_a<mul>(e)) {
100 for (size_t i=0; i<e.nops(); i++)
101 if (get_first_symbol(e.op(i), x))
103 } else if (is_exactly_a<power>(e)) {
104 if (get_first_symbol(e.op(0), x))
112 * Statistical information about symbols in polynomials
115 /** This structure holds information about the highest and lowest degrees
116 * in which a symbol appears in two multivariate polynomials "a" and "b".
117 * A vector of these structures with information about all symbols in
118 * two polynomials can be created with the function get_symbol_stats().
120 * @see get_symbol_stats */
122 /** Reference to symbol */
125 /** Highest degree of symbol in polynomial "a" */
128 /** Highest degree of symbol in polynomial "b" */
131 /** Lowest degree of symbol in polynomial "a" */
134 /** Lowest degree of symbol in polynomial "b" */
137 /** Maximum of deg_a and deg_b (Used for sorting) */
140 /** Maximum number of terms of leading coefficient of symbol in both polynomials */
143 /** Commparison operator for sorting */
144 bool operator<(const sym_desc &x) const
146 if (max_deg == x.max_deg)
147 return max_lcnops < x.max_lcnops;
149 return max_deg < x.max_deg;
153 // Vector of sym_desc structures
154 typedef std::vector<sym_desc> sym_desc_vec;
156 // Add symbol the sym_desc_vec (used internally by get_symbol_stats())
157 static void add_symbol(const ex &s, sym_desc_vec &v)
159 sym_desc_vec::const_iterator it = v.begin(), itend = v.end();
160 while (it != itend) {
161 if (it->sym.is_equal(s)) // If it's already in there, don't add it a second time
170 // Collect all symbols of an expression (used internally by get_symbol_stats())
171 static void collect_symbols(const ex &e, sym_desc_vec &v)
173 if (is_a<symbol>(e)) {
175 } else if (is_exactly_a<add>(e) || is_exactly_a<mul>(e)) {
176 for (size_t i=0; i<e.nops(); i++)
177 collect_symbols(e.op(i), v);
178 } else if (is_exactly_a<power>(e)) {
179 collect_symbols(e.op(0), v);
183 /** Collect statistical information about symbols in polynomials.
184 * This function fills in a vector of "sym_desc" structs which contain
185 * information about the highest and lowest degrees of all symbols that
186 * appear in two polynomials. The vector is then sorted by minimum
187 * degree (lowest to highest). The information gathered by this
188 * function is used by the GCD routines to identify trivial factors
189 * and to determine which variable to choose as the main variable
190 * for GCD computation.
192 * @param a first multivariate polynomial
193 * @param b second multivariate polynomial
194 * @param v vector of sym_desc structs (filled in) */
195 static void get_symbol_stats(const ex &a, const ex &b, sym_desc_vec &v)
197 collect_symbols(a.eval(), v); // eval() to expand assigned symbols
198 collect_symbols(b.eval(), v);
199 sym_desc_vec::iterator it = v.begin(), itend = v.end();
200 while (it != itend) {
201 int deg_a = a.degree(it->sym);
202 int deg_b = b.degree(it->sym);
205 it->max_deg = std::max(deg_a, deg_b);
206 it->max_lcnops = std::max(a.lcoeff(it->sym).nops(), b.lcoeff(it->sym).nops());
207 it->ldeg_a = a.ldegree(it->sym);
208 it->ldeg_b = b.ldegree(it->sym);
211 std::sort(v.begin(), v.end());
214 std::clog << "Symbols:\n";
215 it = v.begin(); itend = v.end();
216 while (it != itend) {
217 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;
218 std::clog << " lcoeff_a=" << a.lcoeff(it->sym) << ", lcoeff_b=" << b.lcoeff(it->sym) << endl;
226 * Computation of LCM of denominators of coefficients of a polynomial
229 // Compute LCM of denominators of coefficients by going through the
230 // expression recursively (used internally by lcm_of_coefficients_denominators())
231 static numeric lcmcoeff(const ex &e, const numeric &l)
233 if (e.info(info_flags::rational))
234 return lcm(ex_to<numeric>(e).denom(), l);
235 else if (is_exactly_a<add>(e)) {
236 numeric c = *_num1_p;
237 for (size_t i=0; i<e.nops(); i++)
238 c = lcmcoeff(e.op(i), c);
240 } else if (is_exactly_a<mul>(e)) {
241 numeric c = *_num1_p;
242 for (size_t i=0; i<e.nops(); i++)
243 c *= lcmcoeff(e.op(i), *_num1_p);
245 } else if (is_exactly_a<power>(e)) {
246 if (is_a<symbol>(e.op(0)))
249 return pow(lcmcoeff(e.op(0), l), ex_to<numeric>(e.op(1)));
254 /** Compute LCM of denominators of coefficients of a polynomial.
255 * Given a polynomial with rational coefficients, this function computes
256 * the LCM of the denominators of all coefficients. This can be used
257 * to bring a polynomial from Q[X] to Z[X].
259 * @param e multivariate polynomial (need not be expanded)
260 * @return LCM of denominators of coefficients */
261 static numeric lcm_of_coefficients_denominators(const ex &e)
263 return lcmcoeff(e, *_num1_p);
266 /** Bring polynomial from Q[X] to Z[X] by multiplying in the previously
267 * determined LCM of the coefficient's denominators.
269 * @param e multivariate polynomial (need not be expanded)
270 * @param lcm LCM to multiply in */
271 static ex multiply_lcm(const ex &e, const numeric &lcm)
273 if (is_exactly_a<mul>(e)) {
274 size_t num = e.nops();
275 exvector v; v.reserve(num + 1);
276 numeric lcm_accum = *_num1_p;
277 for (size_t i=0; i<num; i++) {
278 numeric op_lcm = lcmcoeff(e.op(i), *_num1_p);
279 v.push_back(multiply_lcm(e.op(i), op_lcm));
282 v.push_back(lcm / lcm_accum);
283 return (new mul(v))->setflag(status_flags::dynallocated);
284 } else if (is_exactly_a<add>(e)) {
285 size_t num = e.nops();
286 exvector v; v.reserve(num);
287 for (size_t i=0; i<num; i++)
288 v.push_back(multiply_lcm(e.op(i), lcm));
289 return (new add(v))->setflag(status_flags::dynallocated);
290 } else if (is_exactly_a<power>(e)) {
291 if (is_a<symbol>(e.op(0)))
294 return pow(multiply_lcm(e.op(0), lcm.power(ex_to<numeric>(e.op(1)).inverse())), e.op(1));
300 /** Compute the integer content (= GCD of all numeric coefficients) of an
301 * expanded polynomial. For a polynomial with rational coefficients, this
302 * returns g/l where g is the GCD of the coefficients' numerators and l
303 * is the LCM of the coefficients' denominators.
305 * @return integer content */
306 numeric ex::integer_content() const
308 return bp->integer_content();
311 numeric basic::integer_content() const
316 numeric numeric::integer_content() const
321 numeric add::integer_content() const
323 epvector::const_iterator it = seq.begin();
324 epvector::const_iterator itend = seq.end();
325 numeric c = *_num0_p, l = *_num1_p;
326 while (it != itend) {
327 GINAC_ASSERT(!is_exactly_a<numeric>(it->rest));
328 GINAC_ASSERT(is_exactly_a<numeric>(it->coeff));
329 c = gcd(ex_to<numeric>(it->coeff).numer(), c);
330 l = lcm(ex_to<numeric>(it->coeff).denom(), l);
333 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
334 c = gcd(ex_to<numeric>(overall_coeff).numer(), c);
335 l = lcm(ex_to<numeric>(overall_coeff).denom(), l);
339 numeric mul::integer_content() const
341 #ifdef DO_GINAC_ASSERT
342 epvector::const_iterator it = seq.begin();
343 epvector::const_iterator itend = seq.end();
344 while (it != itend) {
345 GINAC_ASSERT(!is_exactly_a<numeric>(recombine_pair_to_ex(*it)));
348 #endif // def DO_GINAC_ASSERT
349 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
350 return abs(ex_to<numeric>(overall_coeff));
355 * Polynomial quotients and remainders
358 /** Quotient q(x) of polynomials a(x) and b(x) in Q[x].
359 * It satisfies a(x)=b(x)*q(x)+r(x).
361 * @param a first polynomial in x (dividend)
362 * @param b second polynomial in x (divisor)
363 * @param x a and b are polynomials in x
364 * @param check_args check whether a and b are polynomials with rational
365 * coefficients (defaults to "true")
366 * @return quotient of a and b in Q[x] */
367 ex quo(const ex &a, const ex &b, const ex &x, bool check_args)
370 throw(std::overflow_error("quo: division by zero"));
371 if (is_exactly_a<numeric>(a) && is_exactly_a<numeric>(b))
377 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
378 throw(std::invalid_argument("quo: arguments must be polynomials over the rationals"));
380 // Polynomial long division
384 int bdeg = b.degree(x);
385 int rdeg = r.degree(x);
386 ex blcoeff = b.expand().coeff(x, bdeg);
387 bool blcoeff_is_numeric = is_exactly_a<numeric>(blcoeff);
388 exvector v; v.reserve(std::max(rdeg - bdeg + 1, 0));
389 while (rdeg >= bdeg) {
390 ex term, rcoeff = r.coeff(x, rdeg);
391 if (blcoeff_is_numeric)
392 term = rcoeff / blcoeff;
394 if (!divide(rcoeff, blcoeff, term, false))
395 return (new fail())->setflag(status_flags::dynallocated);
397 term *= power(x, rdeg - bdeg);
399 r -= (term * b).expand();
404 return (new add(v))->setflag(status_flags::dynallocated);
408 /** Remainder r(x) of polynomials a(x) and b(x) in Q[x].
409 * It satisfies a(x)=b(x)*q(x)+r(x).
411 * @param a first polynomial in x (dividend)
412 * @param b second polynomial in x (divisor)
413 * @param x a and b are polynomials in x
414 * @param check_args check whether a and b are polynomials with rational
415 * coefficients (defaults to "true")
416 * @return remainder of a(x) and b(x) in Q[x] */
417 ex rem(const ex &a, const ex &b, const ex &x, bool check_args)
420 throw(std::overflow_error("rem: division by zero"));
421 if (is_exactly_a<numeric>(a)) {
422 if (is_exactly_a<numeric>(b))
431 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
432 throw(std::invalid_argument("rem: arguments must be polynomials over the rationals"));
434 // Polynomial long division
438 int bdeg = b.degree(x);
439 int rdeg = r.degree(x);
440 ex blcoeff = b.expand().coeff(x, bdeg);
441 bool blcoeff_is_numeric = is_exactly_a<numeric>(blcoeff);
442 while (rdeg >= bdeg) {
443 ex term, rcoeff = r.coeff(x, rdeg);
444 if (blcoeff_is_numeric)
445 term = rcoeff / blcoeff;
447 if (!divide(rcoeff, blcoeff, term, false))
448 return (new fail())->setflag(status_flags::dynallocated);
450 term *= power(x, rdeg - bdeg);
451 r -= (term * b).expand();
460 /** Decompose rational function a(x)=N(x)/D(x) into P(x)+n(x)/D(x)
461 * with degree(n, x) < degree(D, x).
463 * @param a rational function in x
464 * @param x a is a function of x
465 * @return decomposed function. */
466 ex decomp_rational(const ex &a, const ex &x)
468 ex nd = numer_denom(a);
469 ex numer = nd.op(0), denom = nd.op(1);
470 ex q = quo(numer, denom, x);
471 if (is_exactly_a<fail>(q))
474 return q + rem(numer, denom, x) / denom;
478 /** Pseudo-remainder of polynomials a(x) and b(x) in Q[x].
480 * @param a first polynomial in x (dividend)
481 * @param b second polynomial in x (divisor)
482 * @param x a and b are polynomials in x
483 * @param check_args check whether a and b are polynomials with rational
484 * coefficients (defaults to "true")
485 * @return pseudo-remainder of a(x) and b(x) in Q[x] */
486 ex prem(const ex &a, const ex &b, const ex &x, bool check_args)
489 throw(std::overflow_error("prem: division by zero"));
490 if (is_exactly_a<numeric>(a)) {
491 if (is_exactly_a<numeric>(b))
496 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
497 throw(std::invalid_argument("prem: arguments must be polynomials over the rationals"));
499 // Polynomial long division
502 int rdeg = r.degree(x);
503 int bdeg = eb.degree(x);
506 blcoeff = eb.coeff(x, bdeg);
510 eb -= blcoeff * power(x, bdeg);
514 int delta = rdeg - bdeg + 1, i = 0;
515 while (rdeg >= bdeg && !r.is_zero()) {
516 ex rlcoeff = r.coeff(x, rdeg);
517 ex term = (power(x, rdeg - bdeg) * eb * rlcoeff).expand();
521 r -= rlcoeff * power(x, rdeg);
522 r = (blcoeff * r).expand() - term;
526 return power(blcoeff, delta - i) * r;
530 /** Sparse pseudo-remainder of polynomials a(x) and b(x) in Q[x].
532 * @param a first polynomial in x (dividend)
533 * @param b second polynomial in x (divisor)
534 * @param x a and b are polynomials in x
535 * @param check_args check whether a and b are polynomials with rational
536 * coefficients (defaults to "true")
537 * @return sparse pseudo-remainder of a(x) and b(x) in Q[x] */
538 ex sprem(const ex &a, const ex &b, const ex &x, bool check_args)
541 throw(std::overflow_error("prem: division by zero"));
542 if (is_exactly_a<numeric>(a)) {
543 if (is_exactly_a<numeric>(b))
548 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
549 throw(std::invalid_argument("prem: arguments must be polynomials over the rationals"));
551 // Polynomial long division
554 int rdeg = r.degree(x);
555 int bdeg = eb.degree(x);
558 blcoeff = eb.coeff(x, bdeg);
562 eb -= blcoeff * power(x, bdeg);
566 while (rdeg >= bdeg && !r.is_zero()) {
567 ex rlcoeff = r.coeff(x, rdeg);
568 ex term = (power(x, rdeg - bdeg) * eb * rlcoeff).expand();
572 r -= rlcoeff * power(x, rdeg);
573 r = (blcoeff * r).expand() - term;
580 /** Exact polynomial division of a(X) by b(X) in Q[X].
582 * @param a first multivariate polynomial (dividend)
583 * @param b second multivariate polynomial (divisor)
584 * @param q quotient (returned)
585 * @param check_args check whether a and b are polynomials with rational
586 * coefficients (defaults to "true")
587 * @return "true" when exact division succeeds (quotient returned in q),
588 * "false" otherwise (q left untouched) */
589 bool divide(const ex &a, const ex &b, ex &q, bool check_args)
592 throw(std::overflow_error("divide: division by zero"));
597 if (is_exactly_a<numeric>(b)) {
600 } else if (is_exactly_a<numeric>(a))
608 if (check_args && (!a.info(info_flags::rational_polynomial) ||
609 !b.info(info_flags::rational_polynomial)))
610 throw(std::invalid_argument("divide: arguments must be polynomials over the rationals"));
614 if (!get_first_symbol(a, x) && !get_first_symbol(b, x))
615 throw(std::invalid_argument("invalid expression in divide()"));
617 // Try to avoid expanding partially factored expressions.
618 if (is_exactly_a<mul>(b)) {
619 // Divide sequentially by each term
620 ex rem_new, rem_old = a;
621 for (size_t i=0; i < b.nops(); i++) {
622 if (! divide(rem_old, b.op(i), rem_new, false))
628 } else if (is_exactly_a<power>(b)) {
629 const ex& bb(b.op(0));
630 int exp_b = ex_to<numeric>(b.op(1)).to_int();
631 ex rem_new, rem_old = a;
632 for (int i=exp_b; i>0; i--) {
633 if (! divide(rem_old, bb, rem_new, false))
641 if (is_exactly_a<mul>(a)) {
642 // Divide sequentially each term. If some term in a is divisible
643 // by b we are done... and if not, we can't really say anything.
646 bool divisible_p = false;
647 for (i=0; i < a.nops(); ++i) {
648 if (divide(a.op(i), b, rem_i, false)) {
655 resv.reserve(a.nops());
656 for (size_t j=0; j < a.nops(); j++) {
658 resv.push_back(rem_i);
660 resv.push_back(a.op(j));
662 q = (new mul(resv))->setflag(status_flags::dynallocated);
665 } else if (is_exactly_a<power>(a)) {
666 // The base itself might be divisible by b, in that case we don't
668 const ex& ab(a.op(0));
669 int a_exp = ex_to<numeric>(a.op(1)).to_int();
671 if (divide(ab, b, rem_i, false)) {
672 q = rem_i*power(ab, a_exp - 1);
675 for (int i=2; i < a_exp; i++) {
676 if (divide(power(ab, i), b, rem_i, false)) {
677 q = rem_i*power(ab, a_exp - i);
680 } // ... so we *really* need to expand expression.
683 // Polynomial long division (recursive)
689 int bdeg = b.degree(x);
690 int rdeg = r.degree(x);
691 ex blcoeff = b.expand().coeff(x, bdeg);
692 bool blcoeff_is_numeric = is_exactly_a<numeric>(blcoeff);
693 exvector v; v.reserve(std::max(rdeg - bdeg + 1, 0));
694 while (rdeg >= bdeg) {
695 ex term, rcoeff = r.coeff(x, rdeg);
696 if (blcoeff_is_numeric)
697 term = rcoeff / blcoeff;
699 if (!divide(rcoeff, blcoeff, term, false))
701 term *= power(x, rdeg - bdeg);
703 r -= (term * b).expand();
705 q = (new add(v))->setflag(status_flags::dynallocated);
719 typedef std::pair<ex, ex> ex2;
720 typedef std::pair<ex, bool> exbool;
723 bool operator() (const ex2 &p, const ex2 &q) const
725 int cmp = p.first.compare(q.first);
726 return ((cmp<0) || (!(cmp>0) && p.second.compare(q.second)<0));
730 typedef std::map<ex2, exbool, ex2_less> ex2_exbool_remember;
734 /** Exact polynomial division of a(X) by b(X) in Z[X].
735 * This functions works like divide() but the input and output polynomials are
736 * in Z[X] instead of Q[X] (i.e. they have integer coefficients). Unlike
737 * divide(), it doesn't check whether the input polynomials really are integer
738 * polynomials, so be careful of what you pass in. Also, you have to run
739 * get_symbol_stats() over the input polynomials before calling this function
740 * and pass an iterator to the first element of the sym_desc vector. This
741 * function is used internally by the heur_gcd().
743 * @param a first multivariate polynomial (dividend)
744 * @param b second multivariate polynomial (divisor)
745 * @param q quotient (returned)
746 * @param var iterator to first element of vector of sym_desc structs
747 * @return "true" when exact division succeeds (the quotient is returned in
748 * q), "false" otherwise.
749 * @see get_symbol_stats, heur_gcd */
750 static bool divide_in_z(const ex &a, const ex &b, ex &q, sym_desc_vec::const_iterator var)
754 throw(std::overflow_error("divide_in_z: division by zero"));
755 if (b.is_equal(_ex1)) {
759 if (is_exactly_a<numeric>(a)) {
760 if (is_exactly_a<numeric>(b)) {
762 return q.info(info_flags::integer);
775 static ex2_exbool_remember dr_remember;
776 ex2_exbool_remember::const_iterator remembered = dr_remember.find(ex2(a, b));
777 if (remembered != dr_remember.end()) {
778 q = remembered->second.first;
779 return remembered->second.second;
783 if (is_exactly_a<power>(b)) {
784 const ex& bb(b.op(0));
786 int exp_b = ex_to<numeric>(b.op(1)).to_int();
787 for (int i=exp_b; i>0; i--) {
788 if (!divide_in_z(qbar, bb, q, var))
795 if (is_exactly_a<mul>(b)) {
797 for (const_iterator itrb = b.begin(); itrb != b.end(); ++itrb) {
798 sym_desc_vec sym_stats;
799 get_symbol_stats(a, *itrb, sym_stats);
800 if (!divide_in_z(qbar, *itrb, q, sym_stats.begin()))
809 const ex &x = var->sym;
812 int adeg = a.degree(x), bdeg = b.degree(x);
816 #if USE_TRIAL_DIVISION
818 // Trial division with polynomial interpolation
821 // Compute values at evaluation points 0..adeg
822 vector<numeric> alpha; alpha.reserve(adeg + 1);
823 exvector u; u.reserve(adeg + 1);
824 numeric point = *_num0_p;
826 for (i=0; i<=adeg; i++) {
827 ex bs = b.subs(x == point, subs_options::no_pattern);
828 while (bs.is_zero()) {
830 bs = b.subs(x == point, subs_options::no_pattern);
832 if (!divide_in_z(a.subs(x == point, subs_options::no_pattern), bs, c, var+1))
834 alpha.push_back(point);
840 vector<numeric> rcp; rcp.reserve(adeg + 1);
841 rcp.push_back(*_num0_p);
842 for (k=1; k<=adeg; k++) {
843 numeric product = alpha[k] - alpha[0];
845 product *= alpha[k] - alpha[i];
846 rcp.push_back(product.inverse());
849 // Compute Newton coefficients
850 exvector v; v.reserve(adeg + 1);
852 for (k=1; k<=adeg; k++) {
854 for (i=k-2; i>=0; i--)
855 temp = temp * (alpha[k] - alpha[i]) + v[i];
856 v.push_back((u[k] - temp) * rcp[k]);
859 // Convert from Newton form to standard form
861 for (k=adeg-1; k>=0; k--)
862 c = c * (x - alpha[k]) + v[k];
864 if (c.degree(x) == (adeg - bdeg)) {
872 // Polynomial long division (recursive)
878 ex blcoeff = eb.coeff(x, bdeg);
879 exvector v; v.reserve(std::max(rdeg - bdeg + 1, 0));
880 while (rdeg >= bdeg) {
881 ex term, rcoeff = r.coeff(x, rdeg);
882 if (!divide_in_z(rcoeff, blcoeff, term, var+1))
884 term = (term * power(x, rdeg - bdeg)).expand();
886 r -= (term * eb).expand();
888 q = (new add(v))->setflag(status_flags::dynallocated);
890 dr_remember[ex2(a, b)] = exbool(q, true);
897 dr_remember[ex2(a, b)] = exbool(q, false);
906 * Separation of unit part, content part and primitive part of polynomials
909 /** Compute unit part (= sign of leading coefficient) of a multivariate
910 * polynomial in Q[x]. The product of unit part, content part, and primitive
911 * part is the polynomial itself.
913 * @param x main variable
915 * @see ex::content, ex::primpart, ex::unitcontprim */
916 ex ex::unit(const ex &x) const
918 ex c = expand().lcoeff(x);
919 if (is_exactly_a<numeric>(c))
920 return c.info(info_flags::negative) ?_ex_1 : _ex1;
923 if (get_first_symbol(c, y))
926 throw(std::invalid_argument("invalid expression in unit()"));
931 /** Compute content part (= unit normal GCD of all coefficients) of a
932 * multivariate polynomial in Q[x]. The product of unit part, content part,
933 * and primitive part is the polynomial itself.
935 * @param x main variable
936 * @return content part
937 * @see ex::unit, ex::primpart, ex::unitcontprim */
938 ex ex::content(const ex &x) const
940 if (is_exactly_a<numeric>(*this))
941 return info(info_flags::negative) ? -*this : *this;
947 // First, divide out the integer content (which we can calculate very efficiently).
948 // If the leading coefficient of the quotient is an integer, we are done.
949 ex c = e.integer_content();
951 int deg = r.degree(x);
952 ex lcoeff = r.coeff(x, deg);
953 if (lcoeff.info(info_flags::integer))
956 // GCD of all coefficients
957 int ldeg = r.ldegree(x);
959 return lcoeff * c / lcoeff.unit(x);
961 for (int i=ldeg; i<=deg; i++)
962 cont = gcd(r.coeff(x, i), cont, NULL, NULL, false);
967 /** Compute primitive part of a multivariate polynomial in Q[x]. The result
968 * will be a unit-normal polynomial with a content part of 1. The product
969 * of unit part, content part, and primitive part is the polynomial itself.
971 * @param x main variable
972 * @return primitive part
973 * @see ex::unit, ex::content, ex::unitcontprim */
974 ex ex::primpart(const ex &x) const
976 // We need to compute the unit and content anyway, so call unitcontprim()
978 unitcontprim(x, u, c, p);
983 /** Compute primitive part of a multivariate polynomial in Q[x] when the
984 * content part is already known. This function is faster in computing the
985 * primitive part than the previous function.
987 * @param x main variable
988 * @param c previously computed content part
989 * @return primitive part */
990 ex ex::primpart(const ex &x, const ex &c) const
992 if (is_zero() || c.is_zero())
994 if (is_exactly_a<numeric>(*this))
997 // Divide by unit and content to get primitive part
999 if (is_exactly_a<numeric>(c))
1000 return *this / (c * u);
1002 return quo(*this, c * u, x, false);
1006 /** Compute unit part, content part, and primitive part of a multivariate
1007 * polynomial in Q[x]. The product of the three parts is the polynomial
1010 * @param x main variable
1011 * @param u unit part (returned)
1012 * @param c content part (returned)
1013 * @param p primitive part (returned)
1014 * @see ex::unit, ex::content, ex::primpart */
1015 void ex::unitcontprim(const ex &x, ex &u, ex &c, ex &p) const
1017 // Quick check for zero (avoid expanding)
1024 // Special case: input is a number
1025 if (is_exactly_a<numeric>(*this)) {
1026 if (info(info_flags::negative)) {
1028 c = abs(ex_to<numeric>(*this));
1037 // Expand input polynomial
1045 // Compute unit and content
1049 // Divide by unit and content to get primitive part
1054 if (is_exactly_a<numeric>(c))
1055 p = *this / (c * u);
1057 p = quo(e, c * u, x, false);
1062 * GCD of multivariate polynomials
1065 /** Compute GCD of multivariate polynomials using the subresultant PRS
1066 * algorithm. This function is used internally by gcd().
1068 * @param a first multivariate polynomial
1069 * @param b second multivariate polynomial
1070 * @param var iterator to first element of vector of sym_desc structs
1071 * @return the GCD as a new expression
1074 static ex sr_gcd(const ex &a, const ex &b, sym_desc_vec::const_iterator var)
1080 // The first symbol is our main variable
1081 const ex &x = var->sym;
1083 // Sort c and d so that c has higher degree
1085 int adeg = a.degree(x), bdeg = b.degree(x);
1099 // Remove content from c and d, to be attached to GCD later
1100 ex cont_c = c.content(x);
1101 ex cont_d = d.content(x);
1102 ex gamma = gcd(cont_c, cont_d, NULL, NULL, false);
1105 c = c.primpart(x, cont_c);
1106 d = d.primpart(x, cont_d);
1108 // First element of subresultant sequence
1109 ex r = _ex0, ri = _ex1, psi = _ex1;
1110 int delta = cdeg - ddeg;
1114 // Calculate polynomial pseudo-remainder
1115 r = prem(c, d, x, false);
1117 return gamma * d.primpart(x);
1121 if (!divide_in_z(r, ri * pow(psi, delta), d, var))
1122 throw(std::runtime_error("invalid expression in sr_gcd(), division failed"));
1125 if (is_exactly_a<numeric>(r))
1128 return gamma * r.primpart(x);
1131 // Next element of subresultant sequence
1132 ri = c.expand().lcoeff(x);
1136 divide_in_z(pow(ri, delta), pow(psi, delta-1), psi, var+1);
1137 delta = cdeg - ddeg;
1142 /** Return maximum (absolute value) coefficient of a polynomial.
1143 * This function is used internally by heur_gcd().
1145 * @return maximum coefficient
1147 numeric ex::max_coefficient() const
1149 return bp->max_coefficient();
1152 /** Implementation ex::max_coefficient().
1154 numeric basic::max_coefficient() const
1159 numeric numeric::max_coefficient() const
1164 numeric add::max_coefficient() const
1166 epvector::const_iterator it = seq.begin();
1167 epvector::const_iterator itend = seq.end();
1168 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
1169 numeric cur_max = abs(ex_to<numeric>(overall_coeff));
1170 while (it != itend) {
1172 GINAC_ASSERT(!is_exactly_a<numeric>(it->rest));
1173 a = abs(ex_to<numeric>(it->coeff));
1181 numeric mul::max_coefficient() const
1183 #ifdef DO_GINAC_ASSERT
1184 epvector::const_iterator it = seq.begin();
1185 epvector::const_iterator itend = seq.end();
1186 while (it != itend) {
1187 GINAC_ASSERT(!is_exactly_a<numeric>(recombine_pair_to_ex(*it)));
1190 #endif // def DO_GINAC_ASSERT
1191 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
1192 return abs(ex_to<numeric>(overall_coeff));
1196 /** Apply symmetric modular homomorphism to an expanded multivariate
1197 * polynomial. This function is usually used internally by heur_gcd().
1200 * @return mapped polynomial
1202 ex basic::smod(const numeric &xi) const
1207 ex numeric::smod(const numeric &xi) const
1209 return GiNaC::smod(*this, xi);
1212 ex add::smod(const numeric &xi) const
1215 newseq.reserve(seq.size()+1);
1216 epvector::const_iterator it = seq.begin();
1217 epvector::const_iterator itend = seq.end();
1218 while (it != itend) {
1219 GINAC_ASSERT(!is_exactly_a<numeric>(it->rest));
1220 numeric coeff = GiNaC::smod(ex_to<numeric>(it->coeff), xi);
1221 if (!coeff.is_zero())
1222 newseq.push_back(expair(it->rest, coeff));
1225 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
1226 numeric coeff = GiNaC::smod(ex_to<numeric>(overall_coeff), xi);
1227 return (new add(newseq,coeff))->setflag(status_flags::dynallocated);
1230 ex mul::smod(const numeric &xi) const
1232 #ifdef DO_GINAC_ASSERT
1233 epvector::const_iterator it = seq.begin();
1234 epvector::const_iterator itend = seq.end();
1235 while (it != itend) {
1236 GINAC_ASSERT(!is_exactly_a<numeric>(recombine_pair_to_ex(*it)));
1239 #endif // def DO_GINAC_ASSERT
1240 mul * mulcopyp = new mul(*this);
1241 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
1242 mulcopyp->overall_coeff = GiNaC::smod(ex_to<numeric>(overall_coeff),xi);
1243 mulcopyp->clearflag(status_flags::evaluated);
1244 mulcopyp->clearflag(status_flags::hash_calculated);
1245 return mulcopyp->setflag(status_flags::dynallocated);
1249 /** xi-adic polynomial interpolation */
1250 static ex interpolate(const ex &gamma, const numeric &xi, const ex &x, int degree_hint = 1)
1252 exvector g; g.reserve(degree_hint);
1254 numeric rxi = xi.inverse();
1255 for (int i=0; !e.is_zero(); i++) {
1257 g.push_back(gi * power(x, i));
1260 return (new add(g))->setflag(status_flags::dynallocated);
1263 /** Exception thrown by heur_gcd() to signal failure. */
1264 class gcdheu_failed {};
1266 /** Compute GCD of multivariate polynomials using the heuristic GCD algorithm.
1267 * get_symbol_stats() must have been called previously with the input
1268 * polynomials and an iterator to the first element of the sym_desc vector
1269 * passed in. This function is used internally by gcd().
1271 * @param a first integer multivariate polynomial (expanded)
1272 * @param b second integer multivariate polynomial (expanded)
1273 * @param ca cofactor of polynomial a (returned), NULL to suppress
1274 * calculation of cofactor
1275 * @param cb cofactor of polynomial b (returned), NULL to suppress
1276 * calculation of cofactor
1277 * @param var iterator to first element of vector of sym_desc structs
1278 * @param res the GCD (returned)
1279 * @return true if GCD was computed, false otherwise.
1281 * @exception gcdheu_failed() */
1282 static bool heur_gcd_z(ex& res, const ex &a, const ex &b, ex *ca, ex *cb,
1283 sym_desc_vec::const_iterator var)
1289 // Algorithm only works for non-vanishing input polynomials
1290 if (a.is_zero() || b.is_zero())
1293 // GCD of two numeric values -> CLN
1294 if (is_exactly_a<numeric>(a) && is_exactly_a<numeric>(b)) {
1295 numeric g = gcd(ex_to<numeric>(a), ex_to<numeric>(b));
1297 *ca = ex_to<numeric>(a) / g;
1299 *cb = ex_to<numeric>(b) / g;
1304 // The first symbol is our main variable
1305 const ex &x = var->sym;
1307 // Remove integer content
1308 numeric gc = gcd(a.integer_content(), b.integer_content());
1309 numeric rgc = gc.inverse();
1312 int maxdeg = std::max(p.degree(x), q.degree(x));
1314 // Find evaluation point
1315 numeric mp = p.max_coefficient();
1316 numeric mq = q.max_coefficient();
1319 xi = mq * (*_num2_p) + (*_num2_p);
1321 xi = mp * (*_num2_p) + (*_num2_p);
1324 for (int t=0; t<6; t++) {
1325 if (xi.int_length() * maxdeg > 100000) {
1326 throw gcdheu_failed();
1329 // Apply evaluation homomorphism and calculate GCD
1332 bool found = heur_gcd_z(gamma,
1333 p.subs(x == xi, subs_options::no_pattern),
1334 q.subs(x == xi, subs_options::no_pattern),
1337 gamma = gamma.expand();
1338 // Reconstruct polynomial from GCD of mapped polynomials
1339 ex g = interpolate(gamma, xi, x, maxdeg);
1341 // Remove integer content
1342 g /= g.integer_content();
1344 // If the calculated polynomial divides both p and q, this is the GCD
1346 if (divide_in_z(p, g, ca ? *ca : dummy, var) && divide_in_z(q, g, cb ? *cb : dummy, var)) {
1353 // Next evaluation point
1354 xi = iquo(xi * isqrt(isqrt(xi)) * numeric(73794), numeric(27011));
1359 /** Compute GCD of multivariate polynomials using the heuristic GCD algorithm.
1360 * get_symbol_stats() must have been called previously with the input
1361 * polynomials and an iterator to the first element of the sym_desc vector
1362 * passed in. This function is used internally by gcd().
1364 * @param a first rational multivariate polynomial (expanded)
1365 * @param b second rational multivariate polynomial (expanded)
1366 * @param ca cofactor of polynomial a (returned), NULL to suppress
1367 * calculation of cofactor
1368 * @param cb cofactor of polynomial b (returned), NULL to suppress
1369 * calculation of cofactor
1370 * @param var iterator to first element of vector of sym_desc structs
1371 * @param res the GCD (returned)
1372 * @return true if GCD was computed, false otherwise.
1376 static bool heur_gcd(ex& res, const ex& a, const ex& b, ex *ca, ex *cb,
1377 sym_desc_vec::const_iterator var)
1379 if (a.info(info_flags::integer_polynomial) &&
1380 b.info(info_flags::integer_polynomial)) {
1382 return heur_gcd_z(res, a, b, ca, cb, var);
1383 } catch (gcdheu_failed) {
1388 // convert polynomials to Z[X]
1389 const numeric a_lcm = lcm_of_coefficients_denominators(a);
1390 const numeric ab_lcm = lcmcoeff(b, a_lcm);
1392 const ex ai = a*ab_lcm;
1393 const ex bi = b*ab_lcm;
1394 if (!ai.info(info_flags::integer_polynomial))
1395 throw std::logic_error("heur_gcd: not an integer polynomial [1]");
1397 if (!bi.info(info_flags::integer_polynomial))
1398 throw std::logic_error("heur_gcd: not an integer polynomial [2]");
1402 found = heur_gcd_z(res, ai, bi, ca, cb, var);
1403 } catch (gcdheu_failed) {
1407 // GCD is not unique, it's defined up to a unit (i.e. invertible
1408 // element). If the coefficient ring is a field, every its element is
1409 // invertible, so one can multiply the polynomial GCD with any element
1410 // of the coefficient field. We use this ambiguity to make cofactors
1411 // integer polynomials.
1418 // gcd helper to handle partially factored polynomials (to avoid expanding
1419 // large expressions). At least one of the arguments should be a power.
1420 static ex gcd_pf_pow(const ex& a, const ex& b, ex* ca, ex* cb);
1422 // gcd helper to handle partially factored polynomials (to avoid expanding
1423 // large expressions). At least one of the arguments should be a product.
1424 static ex gcd_pf_mul(const ex& a, const ex& b, ex* ca, ex* cb);
1426 /** Compute GCD (Greatest Common Divisor) of multivariate polynomials a(X)
1427 * and b(X) in Z[X]. Optionally also compute the cofactors of a and b,
1428 * defined by a = ca * gcd(a, b) and b = cb * gcd(a, b).
1430 * @param a first multivariate polynomial
1431 * @param b second multivariate polynomial
1432 * @param ca pointer to expression that will receive the cofactor of a, or NULL
1433 * @param cb pointer to expression that will receive the cofactor of b, or NULL
1434 * @param check_args check whether a and b are polynomials with rational
1435 * coefficients (defaults to "true")
1436 * @return the GCD as a new expression */
1437 ex gcd(const ex &a, const ex &b, ex *ca, ex *cb, bool check_args, unsigned options)
1443 // GCD of numerics -> CLN
1444 if (is_exactly_a<numeric>(a) && is_exactly_a<numeric>(b)) {
1445 numeric g = gcd(ex_to<numeric>(a), ex_to<numeric>(b));
1454 *ca = ex_to<numeric>(a) / g;
1456 *cb = ex_to<numeric>(b) / g;
1463 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial))) {
1464 throw(std::invalid_argument("gcd: arguments must be polynomials over the rationals"));
1467 // Partially factored cases (to avoid expanding large expressions)
1468 if (!(options & gcd_options::no_part_factored)) {
1469 if (is_exactly_a<mul>(a) || is_exactly_a<mul>(b))
1470 return gcd_pf_mul(a, b, ca, cb);
1472 if (is_exactly_a<power>(a) || is_exactly_a<power>(b))
1473 return gcd_pf_pow(a, b, ca, cb);
1477 // Some trivial cases
1478 ex aex = a.expand(), bex = b.expand();
1479 if (aex.is_zero()) {
1486 if (bex.is_zero()) {
1493 if (aex.is_equal(_ex1) || bex.is_equal(_ex1)) {
1501 if (a.is_equal(b)) {
1510 if (is_a<symbol>(aex)) {
1511 if (! bex.subs(aex==_ex0, subs_options::no_pattern).is_zero()) {
1520 if (is_a<symbol>(bex)) {
1521 if (! aex.subs(bex==_ex0, subs_options::no_pattern).is_zero()) {
1530 if (is_exactly_a<numeric>(aex)) {
1531 numeric bcont = bex.integer_content();
1532 numeric g = gcd(ex_to<numeric>(aex), bcont);
1534 *ca = ex_to<numeric>(aex)/g;
1540 if (is_exactly_a<numeric>(bex)) {
1541 numeric acont = aex.integer_content();
1542 numeric g = gcd(ex_to<numeric>(bex), acont);
1546 *cb = ex_to<numeric>(bex)/g;
1550 // Gather symbol statistics
1551 sym_desc_vec sym_stats;
1552 get_symbol_stats(a, b, sym_stats);
1554 // The symbol with least degree which is contained in both polynomials
1555 // is our main variable
1556 sym_desc_vec::iterator vari = sym_stats.begin();
1557 while ((vari != sym_stats.end()) &&
1558 (((vari->ldeg_b == 0) && (vari->deg_b == 0)) ||
1559 ((vari->ldeg_a == 0) && (vari->deg_a == 0))))
1562 // No common symbols at all, just return 1:
1563 if (vari == sym_stats.end()) {
1564 // N.B: keep cofactors factored
1571 // move symbols which contained only in one of the polynomials
1573 rotate(sym_stats.begin(), vari, sym_stats.end());
1575 sym_desc_vec::const_iterator var = sym_stats.begin();
1576 const ex &x = var->sym;
1578 // Cancel trivial common factor
1579 int ldeg_a = var->ldeg_a;
1580 int ldeg_b = var->ldeg_b;
1581 int min_ldeg = std::min(ldeg_a,ldeg_b);
1583 ex common = power(x, min_ldeg);
1584 return gcd((aex / common).expand(), (bex / common).expand(), ca, cb, false) * common;
1587 // Try to eliminate variables
1588 if (var->deg_a == 0 && var->deg_b != 0 ) {
1589 ex bex_u, bex_c, bex_p;
1590 bex.unitcontprim(x, bex_u, bex_c, bex_p);
1591 ex g = gcd(aex, bex_c, ca, cb, false);
1593 *cb *= bex_u * bex_p;
1595 } else if (var->deg_b == 0 && var->deg_a != 0) {
1596 ex aex_u, aex_c, aex_p;
1597 aex.unitcontprim(x, aex_u, aex_c, aex_p);
1598 ex g = gcd(aex_c, bex, ca, cb, false);
1600 *ca *= aex_u * aex_p;
1604 // Try heuristic algorithm first, fall back to PRS if that failed
1606 if (!(options & gcd_options::no_heur_gcd)) {
1607 bool found = heur_gcd(g, aex, bex, ca, cb, var);
1609 // heur_gcd have already computed cofactors...
1610 if (g.is_equal(_ex1)) {
1611 // ... but we want to keep them factored if possible.
1626 g = sr_gcd(aex, bex, var);
1627 if (g.is_equal(_ex1)) {
1628 // Keep cofactors factored if possible
1635 divide(aex, g, *ca, false);
1637 divide(bex, g, *cb, false);
1642 // gcd helper to handle partially factored polynomials (to avoid expanding
1643 // large expressions). Both arguments should be powers.
1644 static ex gcd_pf_pow_pow(const ex& a, const ex& b, ex* ca, ex* cb)
1647 const ex& exp_a = a.op(1);
1649 const ex& exp_b = b.op(1);
1650 if (p.is_equal(pb)) {
1651 // a = p^n, b = p^m, gcd = p^min(n, m)
1652 if (exp_a < exp_b) {
1656 *cb = power(p, exp_b - exp_a);
1657 return power(p, exp_a);
1660 *ca = power(p, exp_a - exp_b);
1663 return power(p, exp_b);
1667 ex p_gcd = gcd(p, pb, &p_co, &pb_co, false);
1668 if (p_gcd.is_equal(_ex1)) {
1669 // a(x) = p(x)^n, b(x) = p_b(x)^m, gcd (p, p_b) = 1 ==>
1676 // XXX: do I need to check for p_gcd = -1?
1678 // there are common factors:
1679 // a(x) = g(x)^n A(x)^n, b(x) = g(x)^m B(x)^m ==>
1680 // gcd(a, b) = g(x)^n gcd(A(x)^n, g(x)^(n-m) B(x)^m
1681 if (exp_a < exp_b) {
1682 return power(p_gcd, exp_a)*
1683 gcd(power(p_co, exp_a), power(p_gcd, exp_b-exp_a)*power(pb_co, exp_b), ca, cb, false);
1685 return power(p_gcd, exp_b)*
1686 gcd(power(p_gcd, exp_a - exp_b)*power(p_co, exp_a), power(pb_co, exp_b), ca, cb, false);
1688 } // p_gcd.is_equal(_ex1)
1692 static ex gcd_pf_pow(const ex& a, const ex& b, ex* ca, ex* cb)
1694 if (is_exactly_a<power>(a)) {
1696 const ex& exp_a = a.op(1);
1697 if (is_exactly_a<power>(b))
1698 return gcd_pf_pow_pow(a, b, ca, cb);
1700 if (p.is_equal(b)) {
1701 // a = p^n, b = p, gcd = p
1703 *ca = power(p, a.op(1) - 1);
1710 ex p_gcd = gcd(p, b, &p_co, &bpart_co, false);
1712 if (p_gcd.is_equal(_ex1)) {
1713 // a(x) = p(x)^n, gcd(p, b) = 1 ==> gcd(a, b) = 1
1720 // 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))
1721 return p_gcd*gcd(power(p_gcd, exp_a-1)*power(p_co, exp_a), bpart_co, ca, cb, false);
1723 } // is_exactly_a<power>(b)
1725 } else if (is_exactly_a<power>(b)) {
1727 if (p.is_equal(a)) {
1728 // a = p, b = p^n, gcd = p
1732 *cb = power(p, b.op(1) - 1);
1737 const ex& exp_b(b.op(1));
1738 ex p_gcd = gcd(a, p, &apart_co, &p_co, false);
1739 if (p_gcd.is_equal(_ex1)) {
1740 // b=p(x)^n, gcd(a, p) = 1 ==> gcd(a, b) == 1
1747 // there are common factors:
1748 // 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))
1750 return p_gcd*gcd(apart_co, power(p_gcd, exp_b-1)*power(p_co, exp_b), ca, cb, false);
1751 } // p_gcd.is_equal(_ex1)
1755 static ex gcd_pf_mul(const ex& a, const ex& b, ex* ca, ex* cb)
1757 if (is_exactly_a<mul>(a) && is_exactly_a<mul>(b)
1758 && (b.nops() > a.nops()))
1759 return gcd_pf_mul(b, a, cb, ca);
1761 if (is_exactly_a<mul>(b) && (!is_exactly_a<mul>(a)))
1762 return gcd_pf_mul(b, a, cb, ca);
1764 GINAC_ASSERT(is_exactly_a<mul>(a));
1765 size_t num = a.nops();
1766 exvector g; g.reserve(num);
1767 exvector acc_ca; acc_ca.reserve(num);
1769 for (size_t i=0; i<num; i++) {
1770 ex part_ca, part_cb;
1771 g.push_back(gcd(a.op(i), part_b, &part_ca, &part_cb, false));
1772 acc_ca.push_back(part_ca);
1776 *ca = (new mul(acc_ca))->setflag(status_flags::dynallocated);
1779 return (new mul(g))->setflag(status_flags::dynallocated);
1782 /** Compute LCM (Least Common Multiple) of multivariate polynomials in Z[X].
1784 * @param a first multivariate polynomial
1785 * @param b second multivariate polynomial
1786 * @param check_args check whether a and b are polynomials with rational
1787 * coefficients (defaults to "true")
1788 * @return the LCM as a new expression */
1789 ex lcm(const ex &a, const ex &b, bool check_args)
1791 if (is_exactly_a<numeric>(a) && is_exactly_a<numeric>(b))
1792 return lcm(ex_to<numeric>(a), ex_to<numeric>(b));
1793 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
1794 throw(std::invalid_argument("lcm: arguments must be polynomials over the rationals"));
1797 ex g = gcd(a, b, &ca, &cb, false);
1803 * Square-free factorization
1806 /** Compute square-free factorization of multivariate polynomial a(x) using
1807 * Yun's algorithm. Used internally by sqrfree().
1809 * @param a multivariate polynomial over Z[X], treated here as univariate
1811 * @param x variable to factor in
1812 * @return vector of factors sorted in ascending degree */
1813 static exvector sqrfree_yun(const ex &a, const symbol &x)
1819 if (g.is_equal(_ex1)) {
1830 } while (!z.is_zero());
1835 /** Compute a square-free factorization of a multivariate polynomial in Q[X].
1837 * @param a multivariate polynomial over Q[X]
1838 * @param l lst of variables to factor in, may be left empty for autodetection
1839 * @return a square-free factorization of \p a.
1842 * A polynomial \f$p(X) \in C[X]\f$ is said <EM>square-free</EM>
1843 * if, whenever any two polynomials \f$q(X)\f$ and \f$r(X)\f$
1846 * p(X) = q(X)^2 r(X),
1848 * we have \f$q(X) \in C\f$.
1849 * This means that \f$p(X)\f$ has no repeated factors, apart
1850 * eventually from constants.
1851 * Given a polynomial \f$p(X) \in C[X]\f$, we say that the
1854 * p(X) = b \cdot p_1(X)^{a_1} \cdot p_2(X)^{a_2} \cdots p_r(X)^{a_r}
1856 * is a <EM>square-free factorization</EM> of \f$p(X)\f$ if the
1857 * following conditions hold:
1858 * -# \f$b \in C\f$ and \f$b \neq 0\f$;
1859 * -# \f$a_i\f$ is a positive integer for \f$i = 1, \ldots, r\f$;
1860 * -# the degree of the polynomial \f$p_i\f$ is strictly positive
1861 * for \f$i = 1, \ldots, r\f$;
1862 * -# the polynomial \f$\Pi_{i=1}^r p_i(X)\f$ is square-free.
1864 * Square-free factorizations need not be unique. For example, if
1865 * \f$a_i\f$ is even, we could change the polynomial \f$p_i(X)\f$
1866 * into \f$-p_i(X)\f$.
1867 * Observe also that the factors \f$p_i(X)\f$ need not be irreducible
1870 ex sqrfree(const ex &a, const lst &l)
1872 if (is_exactly_a<numeric>(a) || // algorithm does not trap a==0
1873 is_a<symbol>(a)) // shortcut
1876 // If no lst of variables to factorize in was specified we have to
1877 // invent one now. Maybe one can optimize here by reversing the order
1878 // or so, I don't know.
1882 get_symbol_stats(a, _ex0, sdv);
1883 sym_desc_vec::const_iterator it = sdv.begin(), itend = sdv.end();
1884 while (it != itend) {
1885 args.append(it->sym);
1892 // Find the symbol to factor in at this stage
1893 if (!is_a<symbol>(args.op(0)))
1894 throw (std::runtime_error("sqrfree(): invalid factorization variable"));
1895 const symbol &x = ex_to<symbol>(args.op(0));
1897 // convert the argument from something in Q[X] to something in Z[X]
1898 const numeric lcm = lcm_of_coefficients_denominators(a);
1899 const ex tmp = multiply_lcm(a,lcm);
1902 exvector factors = sqrfree_yun(tmp, x);
1904 // construct the next list of symbols with the first element popped
1906 newargs.remove_first();
1908 // recurse down the factors in remaining variables
1909 if (newargs.nops()>0) {
1910 exvector::iterator i = factors.begin();
1911 while (i != factors.end()) {
1912 *i = sqrfree(*i, newargs);
1917 // Done with recursion, now construct the final result
1919 exvector::const_iterator it = factors.begin(), itend = factors.end();
1920 for (int p = 1; it!=itend; ++it, ++p)
1921 result *= power(*it, p);
1923 // Yun's algorithm does not account for constant factors. (For univariate
1924 // polynomials it works only in the monic case.) We can correct this by
1925 // inserting what has been lost back into the result. For completeness
1926 // we'll also have to recurse down that factor in the remaining variables.
1927 if (newargs.nops()>0)
1928 result *= sqrfree(quo(tmp, result, x), newargs);
1930 result *= quo(tmp, result, x);
1932 // Put in the reational overall factor again and return
1933 return result * lcm.inverse();
1937 /** Compute square-free partial fraction decomposition of rational function
1940 * @param a rational function over Z[x], treated as univariate polynomial
1942 * @param x variable to factor in
1943 * @return decomposed rational function */
1944 ex sqrfree_parfrac(const ex & a, const symbol & x)
1946 // Find numerator and denominator
1947 ex nd = numer_denom(a);
1948 ex numer = nd.op(0), denom = nd.op(1);
1949 //clog << "numer = " << numer << ", denom = " << denom << endl;
1951 // Convert N(x)/D(x) -> Q(x) + R(x)/D(x), so degree(R) < degree(D)
1952 ex red_poly = quo(numer, denom, x), red_numer = rem(numer, denom, x).expand();
1953 //clog << "red_poly = " << red_poly << ", red_numer = " << red_numer << endl;
1955 // Factorize denominator and compute cofactors
1956 exvector yun = sqrfree_yun(denom, x);
1957 //clog << "yun factors: " << exprseq(yun) << endl;
1958 size_t num_yun = yun.size();
1959 exvector factor; factor.reserve(num_yun);
1960 exvector cofac; cofac.reserve(num_yun);
1961 for (size_t i=0; i<num_yun; i++) {
1962 if (!yun[i].is_equal(_ex1)) {
1963 for (size_t j=0; j<=i; j++) {
1964 factor.push_back(pow(yun[i], j+1));
1966 for (size_t k=0; k<num_yun; k++) {
1968 prod *= pow(yun[k], i-j);
1970 prod *= pow(yun[k], k+1);
1972 cofac.push_back(prod.expand());
1976 size_t num_factors = factor.size();
1977 //clog << "factors : " << exprseq(factor) << endl;
1978 //clog << "cofactors: " << exprseq(cofac) << endl;
1980 // Construct coefficient matrix for decomposition
1981 int max_denom_deg = denom.degree(x);
1982 matrix sys(max_denom_deg + 1, num_factors);
1983 matrix rhs(max_denom_deg + 1, 1);
1984 for (int i=0; i<=max_denom_deg; i++) {
1985 for (size_t j=0; j<num_factors; j++)
1986 sys(i, j) = cofac[j].coeff(x, i);
1987 rhs(i, 0) = red_numer.coeff(x, i);
1989 //clog << "coeffs: " << sys << endl;
1990 //clog << "rhs : " << rhs << endl;
1992 // Solve resulting linear system
1993 matrix vars(num_factors, 1);
1994 for (size_t i=0; i<num_factors; i++)
1995 vars(i, 0) = symbol();
1996 matrix sol = sys.solve(vars, rhs);
1998 // Sum up decomposed fractions
2000 for (size_t i=0; i<num_factors; i++)
2001 sum += sol(i, 0) / factor[i];
2003 return red_poly + sum;
2008 * Normal form of rational functions
2012 * Note: The internal normal() functions (= basic::normal() and overloaded
2013 * functions) all return lists of the form {numerator, denominator}. This
2014 * is to get around mul::eval()'s automatic expansion of numeric coefficients.
2015 * E.g. (a+b)/3 is automatically converted to a/3+b/3 but we want to keep
2016 * the information that (a+b) is the numerator and 3 is the denominator.
2020 /** Create a symbol for replacing the expression "e" (or return a previously
2021 * assigned symbol). The symbol and expression are appended to repl, for
2022 * a later application of subs().
2023 * @see ex::normal */
2024 static ex replace_with_symbol(const ex & e, exmap & repl, exmap & rev_lookup)
2026 // Expression already replaced? Then return the assigned symbol
2027 exmap::const_iterator it = rev_lookup.find(e);
2028 if (it != rev_lookup.end())
2031 // Otherwise create new symbol and add to list, taking care that the
2032 // replacement expression doesn't itself contain symbols from repl,
2033 // because subs() is not recursive
2034 ex es = (new symbol)->setflag(status_flags::dynallocated);
2035 ex e_replaced = e.subs(repl, subs_options::no_pattern);
2036 repl.insert(std::make_pair(es, e_replaced));
2037 rev_lookup.insert(std::make_pair(e_replaced, es));
2041 /** Create a symbol for replacing the expression "e" (or return a previously
2042 * assigned symbol). The symbol and expression are appended to repl, and the
2043 * symbol is returned.
2044 * @see basic::to_rational
2045 * @see basic::to_polynomial */
2046 static ex replace_with_symbol(const ex & e, exmap & repl)
2048 // Expression already replaced? Then return the assigned symbol
2049 for (exmap::const_iterator it = repl.begin(); it != repl.end(); ++it)
2050 if (it->second.is_equal(e))
2053 // Otherwise create new symbol and add to list, taking care that the
2054 // replacement expression doesn't itself contain symbols from repl,
2055 // because subs() is not recursive
2056 ex es = (new symbol)->setflag(status_flags::dynallocated);
2057 ex e_replaced = e.subs(repl, subs_options::no_pattern);
2058 repl.insert(std::make_pair(es, e_replaced));
2063 /** Function object to be applied by basic::normal(). */
2064 struct normal_map_function : public map_function {
2066 normal_map_function(int l) : level(l) {}
2067 ex operator()(const ex & e) { return normal(e, level); }
2070 /** Default implementation of ex::normal(). It normalizes the children and
2071 * replaces the object with a temporary symbol.
2072 * @see ex::normal */
2073 ex basic::normal(exmap & repl, exmap & rev_lookup, int level) const
2076 return (new lst(replace_with_symbol(*this, repl, rev_lookup), _ex1))->setflag(status_flags::dynallocated);
2079 return (new lst(replace_with_symbol(*this, repl, rev_lookup), _ex1))->setflag(status_flags::dynallocated);
2080 else if (level == -max_recursion_level)
2081 throw(std::runtime_error("max recursion level reached"));
2083 normal_map_function map_normal(level - 1);
2084 return (new lst(replace_with_symbol(map(map_normal), repl, rev_lookup), _ex1))->setflag(status_flags::dynallocated);
2090 /** Implementation of ex::normal() for symbols. This returns the unmodified symbol.
2091 * @see ex::normal */
2092 ex symbol::normal(exmap & repl, exmap & rev_lookup, int level) const
2094 return (new lst(*this, _ex1))->setflag(status_flags::dynallocated);
2098 /** Implementation of ex::normal() for a numeric. It splits complex numbers
2099 * into re+I*im and replaces I and non-rational real numbers with a temporary
2101 * @see ex::normal */
2102 ex numeric::normal(exmap & repl, exmap & rev_lookup, int level) const
2104 numeric num = numer();
2107 if (num.is_real()) {
2108 if (!num.is_integer())
2109 numex = replace_with_symbol(numex, repl, rev_lookup);
2111 numeric re = num.real(), im = num.imag();
2112 ex re_ex = re.is_rational() ? re : replace_with_symbol(re, repl, rev_lookup);
2113 ex im_ex = im.is_rational() ? im : replace_with_symbol(im, repl, rev_lookup);
2114 numex = re_ex + im_ex * replace_with_symbol(I, repl, rev_lookup);
2117 // Denominator is always a real integer (see numeric::denom())
2118 return (new lst(numex, denom()))->setflag(status_flags::dynallocated);
2122 /** Fraction cancellation.
2123 * @param n numerator
2124 * @param d denominator
2125 * @return cancelled fraction {n, d} as a list */
2126 static ex frac_cancel(const ex &n, const ex &d)
2130 numeric pre_factor = *_num1_p;
2132 //std::clog << "frac_cancel num = " << num << ", den = " << den << std::endl;
2134 // Handle trivial case where denominator is 1
2135 if (den.is_equal(_ex1))
2136 return (new lst(num, den))->setflag(status_flags::dynallocated);
2138 // Handle special cases where numerator or denominator is 0
2140 return (new lst(num, _ex1))->setflag(status_flags::dynallocated);
2141 if (den.expand().is_zero())
2142 throw(std::overflow_error("frac_cancel: division by zero in frac_cancel"));
2144 // Bring numerator and denominator to Z[X] by multiplying with
2145 // LCM of all coefficients' denominators
2146 numeric num_lcm = lcm_of_coefficients_denominators(num);
2147 numeric den_lcm = lcm_of_coefficients_denominators(den);
2148 num = multiply_lcm(num, num_lcm);
2149 den = multiply_lcm(den, den_lcm);
2150 pre_factor = den_lcm / num_lcm;
2152 // Cancel GCD from numerator and denominator
2154 if (gcd(num, den, &cnum, &cden, false) != _ex1) {
2159 // Make denominator unit normal (i.e. coefficient of first symbol
2160 // as defined by get_first_symbol() is made positive)
2161 if (is_exactly_a<numeric>(den)) {
2162 if (ex_to<numeric>(den).is_negative()) {
2168 if (get_first_symbol(den, x)) {
2169 GINAC_ASSERT(is_exactly_a<numeric>(den.unit(x)));
2170 if (ex_to<numeric>(den.unit(x)).is_negative()) {
2177 // Return result as list
2178 //std::clog << " returns num = " << num << ", den = " << den << ", pre_factor = " << pre_factor << std::endl;
2179 return (new lst(num * pre_factor.numer(), den * pre_factor.denom()))->setflag(status_flags::dynallocated);
2183 /** Implementation of ex::normal() for a sum. It expands terms and performs
2184 * fractional addition.
2185 * @see ex::normal */
2186 ex add::normal(exmap & repl, exmap & rev_lookup, int level) const
2189 return (new lst(replace_with_symbol(*this, repl, rev_lookup), _ex1))->setflag(status_flags::dynallocated);
2190 else if (level == -max_recursion_level)
2191 throw(std::runtime_error("max recursion level reached"));
2193 // Normalize children and split each one into numerator and denominator
2194 exvector nums, dens;
2195 nums.reserve(seq.size()+1);
2196 dens.reserve(seq.size()+1);
2197 epvector::const_iterator it = seq.begin(), itend = seq.end();
2198 while (it != itend) {
2199 ex n = ex_to<basic>(recombine_pair_to_ex(*it)).normal(repl, rev_lookup, level-1);
2200 nums.push_back(n.op(0));
2201 dens.push_back(n.op(1));
2204 ex n = ex_to<numeric>(overall_coeff).normal(repl, rev_lookup, level-1);
2205 nums.push_back(n.op(0));
2206 dens.push_back(n.op(1));
2207 GINAC_ASSERT(nums.size() == dens.size());
2209 // Now, nums is a vector of all numerators and dens is a vector of
2211 //std::clog << "add::normal uses " << nums.size() << " summands:\n";
2213 // Add fractions sequentially
2214 exvector::const_iterator num_it = nums.begin(), num_itend = nums.end();
2215 exvector::const_iterator den_it = dens.begin(), den_itend = dens.end();
2216 //std::clog << " num = " << *num_it << ", den = " << *den_it << std::endl;
2217 ex num = *num_it++, den = *den_it++;
2218 while (num_it != num_itend) {
2219 //std::clog << " num = " << *num_it << ", den = " << *den_it << std::endl;
2220 ex next_num = *num_it++, next_den = *den_it++;
2222 // Trivially add sequences of fractions with identical denominators
2223 while ((den_it != den_itend) && next_den.is_equal(*den_it)) {
2224 next_num += *num_it;
2228 // Additiion of two fractions, taking advantage of the fact that
2229 // the heuristic GCD algorithm computes the cofactors at no extra cost
2230 ex co_den1, co_den2;
2231 ex g = gcd(den, next_den, &co_den1, &co_den2, false);
2232 num = ((num * co_den2) + (next_num * co_den1)).expand();
2233 den *= co_den2; // this is the lcm(den, next_den)
2235 //std::clog << " common denominator = " << den << std::endl;
2237 // Cancel common factors from num/den
2238 return frac_cancel(num, den);
2242 /** Implementation of ex::normal() for a product. It cancels common factors
2244 * @see ex::normal() */
2245 ex mul::normal(exmap & repl, exmap & rev_lookup, int level) const
2248 return (new lst(replace_with_symbol(*this, repl, rev_lookup), _ex1))->setflag(status_flags::dynallocated);
2249 else if (level == -max_recursion_level)
2250 throw(std::runtime_error("max recursion level reached"));
2252 // Normalize children, separate into numerator and denominator
2253 exvector num; num.reserve(seq.size());
2254 exvector den; den.reserve(seq.size());
2256 epvector::const_iterator it = seq.begin(), itend = seq.end();
2257 while (it != itend) {
2258 n = ex_to<basic>(recombine_pair_to_ex(*it)).normal(repl, rev_lookup, level-1);
2259 num.push_back(n.op(0));
2260 den.push_back(n.op(1));
2263 n = ex_to<numeric>(overall_coeff).normal(repl, rev_lookup, level-1);
2264 num.push_back(n.op(0));
2265 den.push_back(n.op(1));
2267 // Perform fraction cancellation
2268 return frac_cancel((new mul(num))->setflag(status_flags::dynallocated),
2269 (new mul(den))->setflag(status_flags::dynallocated));
2273 /** Implementation of ex::normal([B) for powers. It normalizes the basis,
2274 * distributes integer exponents to numerator and denominator, and replaces
2275 * non-integer powers by temporary symbols.
2276 * @see ex::normal */
2277 ex power::normal(exmap & repl, exmap & rev_lookup, int level) const
2280 return (new lst(replace_with_symbol(*this, repl, rev_lookup), _ex1))->setflag(status_flags::dynallocated);
2281 else if (level == -max_recursion_level)
2282 throw(std::runtime_error("max recursion level reached"));
2284 // Normalize basis and exponent (exponent gets reassembled)
2285 ex n_basis = ex_to<basic>(basis).normal(repl, rev_lookup, level-1);
2286 ex n_exponent = ex_to<basic>(exponent).normal(repl, rev_lookup, level-1);
2287 n_exponent = n_exponent.op(0) / n_exponent.op(1);
2289 if (n_exponent.info(info_flags::integer)) {
2291 if (n_exponent.info(info_flags::positive)) {
2293 // (a/b)^n -> {a^n, b^n}
2294 return (new lst(power(n_basis.op(0), n_exponent), power(n_basis.op(1), n_exponent)))->setflag(status_flags::dynallocated);
2296 } else if (n_exponent.info(info_flags::negative)) {
2298 // (a/b)^-n -> {b^n, a^n}
2299 return (new lst(power(n_basis.op(1), -n_exponent), power(n_basis.op(0), -n_exponent)))->setflag(status_flags::dynallocated);
2304 if (n_exponent.info(info_flags::positive)) {
2306 // (a/b)^x -> {sym((a/b)^x), 1}
2307 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);
2309 } else if (n_exponent.info(info_flags::negative)) {
2311 if (n_basis.op(1).is_equal(_ex1)) {
2313 // a^-x -> {1, sym(a^x)}
2314 return (new lst(_ex1, replace_with_symbol(power(n_basis.op(0), -n_exponent), repl, rev_lookup)))->setflag(status_flags::dynallocated);
2318 // (a/b)^-x -> {sym((b/a)^x), 1}
2319 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);
2324 // (a/b)^x -> {sym((a/b)^x, 1}
2325 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);
2329 /** Implementation of ex::normal() for pseries. It normalizes each coefficient
2330 * and replaces the series by a temporary symbol.
2331 * @see ex::normal */
2332 ex pseries::normal(exmap & repl, exmap & rev_lookup, int level) const
2335 epvector::const_iterator i = seq.begin(), end = seq.end();
2337 ex restexp = i->rest.normal();
2338 if (!restexp.is_zero())
2339 newseq.push_back(expair(restexp, i->coeff));
2342 ex n = pseries(relational(var,point), newseq);
2343 return (new lst(replace_with_symbol(n, repl, rev_lookup), _ex1))->setflag(status_flags::dynallocated);
2347 /** Normalization of rational functions.
2348 * This function converts an expression to its normal form
2349 * "numerator/denominator", where numerator and denominator are (relatively
2350 * prime) polynomials. Any subexpressions which are not rational functions
2351 * (like non-rational numbers, non-integer powers or functions like sin(),
2352 * cos() etc.) are replaced by temporary symbols which are re-substituted by
2353 * the (normalized) subexpressions before normal() returns (this way, any
2354 * expression can be treated as a rational function). normal() is applied
2355 * recursively to arguments of functions etc.
2357 * @param level maximum depth of recursion
2358 * @return normalized expression */
2359 ex ex::normal(int level) const
2361 exmap repl, rev_lookup;
2363 ex e = bp->normal(repl, rev_lookup, level);
2364 GINAC_ASSERT(is_a<lst>(e));
2366 // Re-insert replaced symbols
2368 e = e.subs(repl, subs_options::no_pattern);
2370 // Convert {numerator, denominator} form back to fraction
2371 return e.op(0) / e.op(1);
2374 /** Get numerator of an expression. If the expression is not of the normal
2375 * form "numerator/denominator", it is first converted to this form and
2376 * then the numerator is returned.
2379 * @return numerator */
2380 ex ex::numer() const
2382 exmap repl, rev_lookup;
2384 ex e = bp->normal(repl, rev_lookup, 0);
2385 GINAC_ASSERT(is_a<lst>(e));
2387 // Re-insert replaced symbols
2391 return e.op(0).subs(repl, subs_options::no_pattern);
2394 /** Get denominator of an expression. If the expression is not of the normal
2395 * form "numerator/denominator", it is first converted to this form and
2396 * then the denominator is returned.
2399 * @return denominator */
2400 ex ex::denom() const
2402 exmap repl, rev_lookup;
2404 ex e = bp->normal(repl, rev_lookup, 0);
2405 GINAC_ASSERT(is_a<lst>(e));
2407 // Re-insert replaced symbols
2411 return e.op(1).subs(repl, subs_options::no_pattern);
2414 /** Get numerator and denominator of an expression. If the expresison is not
2415 * of the normal form "numerator/denominator", it is first converted to this
2416 * form and then a list [numerator, denominator] is returned.
2419 * @return a list [numerator, denominator] */
2420 ex ex::numer_denom() const
2422 exmap repl, rev_lookup;
2424 ex e = bp->normal(repl, rev_lookup, 0);
2425 GINAC_ASSERT(is_a<lst>(e));
2427 // Re-insert replaced symbols
2431 return e.subs(repl, subs_options::no_pattern);
2435 /** Rationalization of non-rational functions.
2436 * This function converts a general expression to a rational function
2437 * by replacing all non-rational subexpressions (like non-rational numbers,
2438 * non-integer powers or functions like sin(), cos() etc.) to temporary
2439 * symbols. This makes it possible to use functions like gcd() and divide()
2440 * on non-rational functions by applying to_rational() on the arguments,
2441 * calling the desired function and re-substituting the temporary symbols
2442 * in the result. To make the last step possible, all temporary symbols and
2443 * their associated expressions are collected in the map specified by the
2444 * repl parameter, ready to be passed as an argument to ex::subs().
2446 * @param repl collects all temporary symbols and their replacements
2447 * @return rationalized expression */
2448 ex ex::to_rational(exmap & repl) const
2450 return bp->to_rational(repl);
2453 // GiNaC 1.1 compatibility function
2454 ex ex::to_rational(lst & repl_lst) const
2456 // Convert lst to exmap
2458 for (lst::const_iterator it = repl_lst.begin(); it != repl_lst.end(); ++it)
2459 m.insert(std::make_pair(it->op(0), it->op(1)));
2461 ex ret = bp->to_rational(m);
2463 // Convert exmap back to lst
2464 repl_lst.remove_all();
2465 for (exmap::const_iterator it = m.begin(); it != m.end(); ++it)
2466 repl_lst.append(it->first == it->second);
2471 ex ex::to_polynomial(exmap & repl) const
2473 return bp->to_polynomial(repl);
2476 // GiNaC 1.1 compatibility function
2477 ex ex::to_polynomial(lst & repl_lst) const
2479 // Convert lst to exmap
2481 for (lst::const_iterator it = repl_lst.begin(); it != repl_lst.end(); ++it)
2482 m.insert(std::make_pair(it->op(0), it->op(1)));
2484 ex ret = bp->to_polynomial(m);
2486 // Convert exmap back to lst
2487 repl_lst.remove_all();
2488 for (exmap::const_iterator it = m.begin(); it != m.end(); ++it)
2489 repl_lst.append(it->first == it->second);
2494 /** Default implementation of ex::to_rational(). This replaces the object with
2495 * a temporary symbol. */
2496 ex basic::to_rational(exmap & repl) const
2498 return replace_with_symbol(*this, repl);
2501 ex basic::to_polynomial(exmap & repl) const
2503 return replace_with_symbol(*this, repl);
2507 /** Implementation of ex::to_rational() for symbols. This returns the
2508 * unmodified symbol. */
2509 ex symbol::to_rational(exmap & repl) const
2514 /** Implementation of ex::to_polynomial() for symbols. This returns the
2515 * unmodified symbol. */
2516 ex symbol::to_polynomial(exmap & repl) const
2522 /** Implementation of ex::to_rational() for a numeric. It splits complex
2523 * numbers into re+I*im and replaces I and non-rational real numbers with a
2524 * temporary symbol. */
2525 ex numeric::to_rational(exmap & repl) const
2529 return replace_with_symbol(*this, repl);
2531 numeric re = real();
2532 numeric im = imag();
2533 ex re_ex = re.is_rational() ? re : replace_with_symbol(re, repl);
2534 ex im_ex = im.is_rational() ? im : replace_with_symbol(im, repl);
2535 return re_ex + im_ex * replace_with_symbol(I, repl);
2540 /** Implementation of ex::to_polynomial() for a numeric. It splits complex
2541 * numbers into re+I*im and replaces I and non-integer real numbers with a
2542 * temporary symbol. */
2543 ex numeric::to_polynomial(exmap & repl) const
2547 return replace_with_symbol(*this, repl);
2549 numeric re = real();
2550 numeric im = imag();
2551 ex re_ex = re.is_integer() ? re : replace_with_symbol(re, repl);
2552 ex im_ex = im.is_integer() ? im : replace_with_symbol(im, repl);
2553 return re_ex + im_ex * replace_with_symbol(I, repl);
2559 /** Implementation of ex::to_rational() for powers. It replaces non-integer
2560 * powers by temporary symbols. */
2561 ex power::to_rational(exmap & repl) const
2563 if (exponent.info(info_flags::integer))
2564 return power(basis.to_rational(repl), exponent);
2566 return replace_with_symbol(*this, repl);
2569 /** Implementation of ex::to_polynomial() for powers. It replaces non-posint
2570 * powers by temporary symbols. */
2571 ex power::to_polynomial(exmap & repl) const
2573 if (exponent.info(info_flags::posint))
2574 return power(basis.to_rational(repl), exponent);
2575 else if (exponent.info(info_flags::negint))
2577 ex basis_pref = collect_common_factors(basis);
2578 if (is_exactly_a<mul>(basis_pref) || is_exactly_a<power>(basis_pref)) {
2579 // (A*B)^n will be automagically transformed to A^n*B^n
2580 ex t = power(basis_pref, exponent);
2581 return t.to_polynomial(repl);
2584 return power(replace_with_symbol(power(basis, _ex_1), repl), -exponent);
2587 return replace_with_symbol(*this, repl);
2591 /** Implementation of ex::to_rational() for expairseqs. */
2592 ex expairseq::to_rational(exmap & repl) const
2595 s.reserve(seq.size());
2596 epvector::const_iterator i = seq.begin(), end = seq.end();
2598 s.push_back(split_ex_to_pair(recombine_pair_to_ex(*i).to_rational(repl)));
2601 ex oc = overall_coeff.to_rational(repl);
2602 if (oc.info(info_flags::numeric))
2603 return thisexpairseq(s, overall_coeff);
2605 s.push_back(combine_ex_with_coeff_to_pair(oc, _ex1));
2606 return thisexpairseq(s, default_overall_coeff());
2609 /** Implementation of ex::to_polynomial() for expairseqs. */
2610 ex expairseq::to_polynomial(exmap & repl) const
2613 s.reserve(seq.size());
2614 epvector::const_iterator i = seq.begin(), end = seq.end();
2616 s.push_back(split_ex_to_pair(recombine_pair_to_ex(*i).to_polynomial(repl)));
2619 ex oc = overall_coeff.to_polynomial(repl);
2620 if (oc.info(info_flags::numeric))
2621 return thisexpairseq(s, overall_coeff);
2623 s.push_back(combine_ex_with_coeff_to_pair(oc, _ex1));
2624 return thisexpairseq(s, default_overall_coeff());
2628 /** Remove the common factor in the terms of a sum 'e' by calculating the GCD,
2629 * and multiply it into the expression 'factor' (which needs to be initialized
2630 * to 1, unless you're accumulating factors). */
2631 static ex find_common_factor(const ex & e, ex & factor, exmap & repl)
2633 if (is_exactly_a<add>(e)) {
2635 size_t num = e.nops();
2636 exvector terms; terms.reserve(num);
2639 // Find the common GCD
2640 for (size_t i=0; i<num; i++) {
2641 ex x = e.op(i).to_polynomial(repl);
2643 if (is_exactly_a<add>(x) || is_exactly_a<mul>(x) || is_a<power>(x)) {
2645 x = find_common_factor(x, f, repl);
2657 if (gc.is_equal(_ex1))
2660 // The GCD is the factor we pull out
2663 // Now divide all terms by the GCD
2664 for (size_t i=0; i<num; i++) {
2667 // Try to avoid divide() because it expands the polynomial
2669 if (is_exactly_a<mul>(t)) {
2670 for (size_t j=0; j<t.nops(); j++) {
2671 if (t.op(j).is_equal(gc)) {
2672 exvector v; v.reserve(t.nops());
2673 for (size_t k=0; k<t.nops(); k++) {
2677 v.push_back(t.op(k));
2679 t = (new mul(v))->setflag(status_flags::dynallocated);
2689 return (new add(terms))->setflag(status_flags::dynallocated);
2691 } else if (is_exactly_a<mul>(e)) {
2693 size_t num = e.nops();
2694 exvector v; v.reserve(num);
2696 for (size_t i=0; i<num; i++)
2697 v.push_back(find_common_factor(e.op(i), factor, repl));
2699 return (new mul(v))->setflag(status_flags::dynallocated);
2701 } else if (is_exactly_a<power>(e)) {
2702 const ex e_exp(e.op(1));
2703 if (e_exp.info(info_flags::integer)) {
2704 ex eb = e.op(0).to_polynomial(repl);
2705 ex factor_local(_ex1);
2706 ex pre_res = find_common_factor(eb, factor_local, repl);
2707 factor *= power(factor_local, e_exp);
2708 return power(pre_res, e_exp);
2711 return e.to_polynomial(repl);
2718 /** Collect common factors in sums. This converts expressions like
2719 * 'a*(b*x+b*y)' to 'a*b*(x+y)'. */
2720 ex collect_common_factors(const ex & e)
2722 if (is_exactly_a<add>(e) || is_exactly_a<mul>(e) || is_exactly_a<power>(e)) {
2726 ex r = find_common_factor(e, factor, repl);
2727 return factor.subs(repl, subs_options::no_pattern) * r.subs(repl, subs_options::no_pattern);
2734 /** Resultant of two expressions e1,e2 with respect to symbol s.
2735 * Method: Compute determinant of Sylvester matrix of e1,e2,s. */
2736 ex resultant(const ex & e1, const ex & e2, const ex & s)
2738 const ex ee1 = e1.expand();
2739 const ex ee2 = e2.expand();
2740 if (!ee1.info(info_flags::polynomial) ||
2741 !ee2.info(info_flags::polynomial))
2742 throw(std::runtime_error("resultant(): arguments must be polynomials"));
2744 const int h1 = ee1.degree(s);
2745 const int l1 = ee1.ldegree(s);
2746 const int h2 = ee2.degree(s);
2747 const int l2 = ee2.ldegree(s);
2749 const int msize = h1 + h2;
2750 matrix m(msize, msize);
2752 for (int l = h1; l >= l1; --l) {
2753 const ex e = ee1.coeff(s, l);
2754 for (int k = 0; k < h2; ++k)
2757 for (int l = h2; l >= l2; --l) {
2758 const ex e = ee2.coeff(s, l);
2759 for (int k = 0; k < h1; ++k)
2760 m(k+h2, k+h2-l) = e;
2763 return m.determinant();
2767 } // namespace GiNaC