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-2015 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
31 #include "expairseq.h"
38 #include "relational.h"
39 #include "operators.h"
44 #include "polynomial/chinrem_gcd.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
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(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 // Try to avoid expanding partially factored expressions.
619 if (is_exactly_a<mul>(b)) {
620 // Divide sequentially by each term
621 ex rem_new, rem_old = a;
622 for (size_t i=0; i < b.nops(); i++) {
623 if (! divide(rem_old, b.op(i), rem_new, false))
629 } else if (is_exactly_a<power>(b)) {
630 const ex& bb(b.op(0));
631 int exp_b = ex_to<numeric>(b.op(1)).to_int();
632 ex rem_new, rem_old = a;
633 for (int i=exp_b; i>0; i--) {
634 if (! divide(rem_old, bb, rem_new, false))
642 if (is_exactly_a<mul>(a)) {
643 // Divide sequentially each term. If some term in a is divisible
644 // by b we are done... and if not, we can't really say anything.
647 bool divisible_p = false;
648 for (i=0; i < a.nops(); ++i) {
649 if (divide(a.op(i), b, rem_i, false)) {
656 resv.reserve(a.nops());
657 for (size_t j=0; j < a.nops(); j++) {
659 resv.push_back(rem_i);
661 resv.push_back(a.op(j));
663 q = (new mul(resv))->setflag(status_flags::dynallocated);
666 } else if (is_exactly_a<power>(a)) {
667 // The base itself might be divisible by b, in that case we don't
669 const ex& ab(a.op(0));
670 int a_exp = ex_to<numeric>(a.op(1)).to_int();
672 if (divide(ab, b, rem_i, false)) {
673 q = rem_i*power(ab, a_exp - 1);
676 // code below is commented-out because it leads to a significant slowdown
677 // for (int i=2; i < a_exp; i++) {
678 // if (divide(power(ab, i), b, rem_i, false)) {
679 // q = rem_i*power(ab, a_exp - i);
682 // } // ... so we *really* need to expand expression.
685 // Polynomial long division (recursive)
691 int bdeg = b.degree(x);
692 int rdeg = r.degree(x);
693 ex blcoeff = b.expand().coeff(x, bdeg);
694 bool blcoeff_is_numeric = is_exactly_a<numeric>(blcoeff);
695 exvector v; v.reserve(std::max(rdeg - bdeg + 1, 0));
696 while (rdeg >= bdeg) {
697 ex term, rcoeff = r.coeff(x, rdeg);
698 if (blcoeff_is_numeric)
699 term = rcoeff / blcoeff;
701 if (!divide(rcoeff, blcoeff, term, false))
703 term *= power(x, rdeg - bdeg);
705 r -= (term * b).expand();
707 q = (new add(v))->setflag(status_flags::dynallocated);
721 typedef std::pair<ex, ex> ex2;
722 typedef std::pair<ex, bool> exbool;
725 bool operator() (const ex2 &p, const ex2 &q) const
727 int cmp = p.first.compare(q.first);
728 return ((cmp<0) || (!(cmp>0) && p.second.compare(q.second)<0));
732 typedef std::map<ex2, exbool, ex2_less> ex2_exbool_remember;
736 /** Exact polynomial division of a(X) by b(X) in Z[X].
737 * This functions works like divide() but the input and output polynomials are
738 * in Z[X] instead of Q[X] (i.e. they have integer coefficients). Unlike
739 * divide(), it doesn't check whether the input polynomials really are integer
740 * polynomials, so be careful of what you pass in. Also, you have to run
741 * get_symbol_stats() over the input polynomials before calling this function
742 * and pass an iterator to the first element of the sym_desc vector. This
743 * function is used internally by the heur_gcd().
745 * @param a first multivariate polynomial (dividend)
746 * @param b second multivariate polynomial (divisor)
747 * @param q quotient (returned)
748 * @param var iterator to first element of vector of sym_desc structs
749 * @return "true" when exact division succeeds (the quotient is returned in
750 * q), "false" otherwise.
751 * @see get_symbol_stats, heur_gcd */
752 static bool divide_in_z(const ex &a, const ex &b, ex &q, sym_desc_vec::const_iterator var)
756 throw(std::overflow_error("divide_in_z: division by zero"));
757 if (b.is_equal(_ex1)) {
761 if (is_exactly_a<numeric>(a)) {
762 if (is_exactly_a<numeric>(b)) {
764 return q.info(info_flags::integer);
777 static ex2_exbool_remember dr_remember;
778 ex2_exbool_remember::const_iterator remembered = dr_remember.find(ex2(a, b));
779 if (remembered != dr_remember.end()) {
780 q = remembered->second.first;
781 return remembered->second.second;
785 if (is_exactly_a<power>(b)) {
786 const ex& bb(b.op(0));
788 int exp_b = ex_to<numeric>(b.op(1)).to_int();
789 for (int i=exp_b; i>0; i--) {
790 if (!divide_in_z(qbar, bb, q, var))
797 if (is_exactly_a<mul>(b)) {
799 for (const_iterator itrb = b.begin(); itrb != b.end(); ++itrb) {
800 sym_desc_vec sym_stats;
801 get_symbol_stats(a, *itrb, sym_stats);
802 if (!divide_in_z(qbar, *itrb, q, sym_stats.begin()))
811 const ex &x = var->sym;
814 int adeg = a.degree(x), bdeg = b.degree(x);
818 #if USE_TRIAL_DIVISION
820 // Trial division with polynomial interpolation
823 // Compute values at evaluation points 0..adeg
824 vector<numeric> alpha; alpha.reserve(adeg + 1);
825 exvector u; u.reserve(adeg + 1);
826 numeric point = *_num0_p;
828 for (i=0; i<=adeg; i++) {
829 ex bs = b.subs(x == point, subs_options::no_pattern);
830 while (bs.is_zero()) {
832 bs = b.subs(x == point, subs_options::no_pattern);
834 if (!divide_in_z(a.subs(x == point, subs_options::no_pattern), bs, c, var+1))
836 alpha.push_back(point);
842 vector<numeric> rcp; rcp.reserve(adeg + 1);
843 rcp.push_back(*_num0_p);
844 for (k=1; k<=adeg; k++) {
845 numeric product = alpha[k] - alpha[0];
847 product *= alpha[k] - alpha[i];
848 rcp.push_back(product.inverse());
851 // Compute Newton coefficients
852 exvector v; v.reserve(adeg + 1);
854 for (k=1; k<=adeg; k++) {
856 for (i=k-2; i>=0; i--)
857 temp = temp * (alpha[k] - alpha[i]) + v[i];
858 v.push_back((u[k] - temp) * rcp[k]);
861 // Convert from Newton form to standard form
863 for (k=adeg-1; k>=0; k--)
864 c = c * (x - alpha[k]) + v[k];
866 if (c.degree(x) == (adeg - bdeg)) {
874 // Polynomial long division (recursive)
880 ex blcoeff = eb.coeff(x, bdeg);
881 exvector v; v.reserve(std::max(rdeg - bdeg + 1, 0));
882 while (rdeg >= bdeg) {
883 ex term, rcoeff = r.coeff(x, rdeg);
884 if (!divide_in_z(rcoeff, blcoeff, term, var+1))
886 term = (term * power(x, rdeg - bdeg)).expand();
888 r -= (term * eb).expand();
890 q = (new add(v))->setflag(status_flags::dynallocated);
892 dr_remember[ex2(a, b)] = exbool(q, true);
899 dr_remember[ex2(a, b)] = exbool(q, false);
908 * Separation of unit part, content part and primitive part of polynomials
911 /** Compute unit part (= sign of leading coefficient) of a multivariate
912 * polynomial in Q[x]. The product of unit part, content part, and primitive
913 * part is the polynomial itself.
915 * @param x main variable
917 * @see ex::content, ex::primpart, ex::unitcontprim */
918 ex ex::unit(const ex &x) const
920 ex c = expand().lcoeff(x);
921 if (is_exactly_a<numeric>(c))
922 return c.info(info_flags::negative) ?_ex_1 : _ex1;
925 if (get_first_symbol(c, y))
928 throw(std::invalid_argument("invalid expression in unit()"));
933 /** Compute content part (= unit normal GCD of all coefficients) of a
934 * multivariate polynomial in Q[x]. The product of unit part, content part,
935 * and primitive part is the polynomial itself.
937 * @param x main variable
938 * @return content part
939 * @see ex::unit, ex::primpart, ex::unitcontprim */
940 ex ex::content(const ex &x) const
942 if (is_exactly_a<numeric>(*this))
943 return info(info_flags::negative) ? -*this : *this;
949 // First, divide out the integer content (which we can calculate very efficiently).
950 // If the leading coefficient of the quotient is an integer, we are done.
951 ex c = e.integer_content();
953 int deg = r.degree(x);
954 ex lcoeff = r.coeff(x, deg);
955 if (lcoeff.info(info_flags::integer))
958 // GCD of all coefficients
959 int ldeg = r.ldegree(x);
961 return lcoeff * c / lcoeff.unit(x);
963 for (int i=ldeg; i<=deg; i++)
964 cont = gcd(r.coeff(x, i), cont, NULL, NULL, false);
969 /** Compute primitive part of a multivariate polynomial in Q[x]. The result
970 * will be a unit-normal polynomial with a content part of 1. The product
971 * of unit part, content part, and primitive part is the polynomial itself.
973 * @param x main variable
974 * @return primitive part
975 * @see ex::unit, ex::content, ex::unitcontprim */
976 ex ex::primpart(const ex &x) const
978 // We need to compute the unit and content anyway, so call unitcontprim()
980 unitcontprim(x, u, c, p);
985 /** Compute primitive part of a multivariate polynomial in Q[x] when the
986 * content part is already known. This function is faster in computing the
987 * primitive part than the previous function.
989 * @param x main variable
990 * @param c previously computed content part
991 * @return primitive part */
992 ex ex::primpart(const ex &x, const ex &c) const
994 if (is_zero() || c.is_zero())
996 if (is_exactly_a<numeric>(*this))
999 // Divide by unit and content to get primitive part
1001 if (is_exactly_a<numeric>(c))
1002 return *this / (c * u);
1004 return quo(*this, c * u, x, false);
1008 /** Compute unit part, content part, and primitive part of a multivariate
1009 * polynomial in Q[x]. The product of the three parts is the polynomial
1012 * @param x main variable
1013 * @param u unit part (returned)
1014 * @param c content part (returned)
1015 * @param p primitive part (returned)
1016 * @see ex::unit, ex::content, ex::primpart */
1017 void ex::unitcontprim(const ex &x, ex &u, ex &c, ex &p) const
1019 // Quick check for zero (avoid expanding)
1026 // Special case: input is a number
1027 if (is_exactly_a<numeric>(*this)) {
1028 if (info(info_flags::negative)) {
1030 c = abs(ex_to<numeric>(*this));
1039 // Expand input polynomial
1047 // Compute unit and content
1051 // Divide by unit and content to get primitive part
1056 if (is_exactly_a<numeric>(c))
1057 p = *this / (c * u);
1059 p = quo(e, c * u, x, false);
1064 * GCD of multivariate polynomials
1067 /** Compute GCD of multivariate polynomials using the subresultant PRS
1068 * algorithm. This function is used internally by gcd().
1070 * @param a first multivariate polynomial
1071 * @param b second multivariate polynomial
1072 * @param var iterator to first element of vector of sym_desc structs
1073 * @return the GCD as a new expression
1076 static ex sr_gcd(const ex &a, const ex &b, sym_desc_vec::const_iterator var)
1082 // The first symbol is our main variable
1083 const ex &x = var->sym;
1085 // Sort c and d so that c has higher degree
1087 int adeg = a.degree(x), bdeg = b.degree(x);
1101 // Remove content from c and d, to be attached to GCD later
1102 ex cont_c = c.content(x);
1103 ex cont_d = d.content(x);
1104 ex gamma = gcd(cont_c, cont_d, NULL, NULL, false);
1107 c = c.primpart(x, cont_c);
1108 d = d.primpart(x, cont_d);
1110 // First element of subresultant sequence
1111 ex r = _ex0, ri = _ex1, psi = _ex1;
1112 int delta = cdeg - ddeg;
1116 // Calculate polynomial pseudo-remainder
1117 r = prem(c, d, x, false);
1119 return gamma * d.primpart(x);
1123 if (!divide_in_z(r, ri * pow(psi, delta), d, var))
1124 throw(std::runtime_error("invalid expression in sr_gcd(), division failed"));
1127 if (is_exactly_a<numeric>(r))
1130 return gamma * r.primpart(x);
1133 // Next element of subresultant sequence
1134 ri = c.expand().lcoeff(x);
1138 divide_in_z(pow(ri, delta), pow(psi, delta-1), psi, var+1);
1139 delta = cdeg - ddeg;
1144 /** Return maximum (absolute value) coefficient of a polynomial.
1145 * This function is used internally by heur_gcd().
1147 * @return maximum coefficient
1149 numeric ex::max_coefficient() const
1151 return bp->max_coefficient();
1154 /** Implementation ex::max_coefficient().
1156 numeric basic::max_coefficient() const
1161 numeric numeric::max_coefficient() const
1166 numeric add::max_coefficient() const
1168 epvector::const_iterator it = seq.begin();
1169 epvector::const_iterator itend = seq.end();
1170 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
1171 numeric cur_max = abs(ex_to<numeric>(overall_coeff));
1172 while (it != itend) {
1174 GINAC_ASSERT(!is_exactly_a<numeric>(it->rest));
1175 a = abs(ex_to<numeric>(it->coeff));
1183 numeric mul::max_coefficient() const
1185 #ifdef DO_GINAC_ASSERT
1186 epvector::const_iterator it = seq.begin();
1187 epvector::const_iterator itend = seq.end();
1188 while (it != itend) {
1189 GINAC_ASSERT(!is_exactly_a<numeric>(recombine_pair_to_ex(*it)));
1192 #endif // def DO_GINAC_ASSERT
1193 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
1194 return abs(ex_to<numeric>(overall_coeff));
1198 /** Apply symmetric modular homomorphism to an expanded multivariate
1199 * polynomial. This function is usually used internally by heur_gcd().
1202 * @return mapped polynomial
1204 ex basic::smod(const numeric &xi) const
1209 ex numeric::smod(const numeric &xi) const
1211 return GiNaC::smod(*this, xi);
1214 ex add::smod(const numeric &xi) const
1217 newseq.reserve(seq.size()+1);
1218 epvector::const_iterator it = seq.begin();
1219 epvector::const_iterator itend = seq.end();
1220 while (it != itend) {
1221 GINAC_ASSERT(!is_exactly_a<numeric>(it->rest));
1222 numeric coeff = GiNaC::smod(ex_to<numeric>(it->coeff), xi);
1223 if (!coeff.is_zero())
1224 newseq.push_back(expair(it->rest, coeff));
1227 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
1228 numeric coeff = GiNaC::smod(ex_to<numeric>(overall_coeff), xi);
1229 return (new add(newseq,coeff))->setflag(status_flags::dynallocated);
1232 ex mul::smod(const numeric &xi) const
1234 #ifdef DO_GINAC_ASSERT
1235 epvector::const_iterator it = seq.begin();
1236 epvector::const_iterator itend = seq.end();
1237 while (it != itend) {
1238 GINAC_ASSERT(!is_exactly_a<numeric>(recombine_pair_to_ex(*it)));
1241 #endif // def DO_GINAC_ASSERT
1242 mul * mulcopyp = new mul(*this);
1243 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
1244 mulcopyp->overall_coeff = GiNaC::smod(ex_to<numeric>(overall_coeff),xi);
1245 mulcopyp->clearflag(status_flags::evaluated);
1246 mulcopyp->clearflag(status_flags::hash_calculated);
1247 return mulcopyp->setflag(status_flags::dynallocated);
1251 /** xi-adic polynomial interpolation */
1252 static ex interpolate(const ex &gamma, const numeric &xi, const ex &x, int degree_hint = 1)
1254 exvector g; g.reserve(degree_hint);
1256 numeric rxi = xi.inverse();
1257 for (int i=0; !e.is_zero(); i++) {
1259 g.push_back(gi * power(x, i));
1262 return (new add(g))->setflag(status_flags::dynallocated);
1265 /** Exception thrown by heur_gcd() to signal failure. */
1266 class gcdheu_failed {};
1268 /** Compute GCD of multivariate polynomials using the heuristic GCD algorithm.
1269 * get_symbol_stats() must have been called previously with the input
1270 * polynomials and an iterator to the first element of the sym_desc vector
1271 * passed in. This function is used internally by gcd().
1273 * @param a first integer multivariate polynomial (expanded)
1274 * @param b second integer multivariate polynomial (expanded)
1275 * @param ca cofactor of polynomial a (returned), NULL to suppress
1276 * calculation of cofactor
1277 * @param cb cofactor of polynomial b (returned), NULL to suppress
1278 * calculation of cofactor
1279 * @param var iterator to first element of vector of sym_desc structs
1280 * @param res the GCD (returned)
1281 * @return true if GCD was computed, false otherwise.
1283 * @exception gcdheu_failed() */
1284 static bool heur_gcd_z(ex& res, const ex &a, const ex &b, ex *ca, ex *cb,
1285 sym_desc_vec::const_iterator var)
1291 // Algorithm only works for non-vanishing input polynomials
1292 if (a.is_zero() || b.is_zero())
1295 // GCD of two numeric values -> CLN
1296 if (is_exactly_a<numeric>(a) && is_exactly_a<numeric>(b)) {
1297 numeric g = gcd(ex_to<numeric>(a), ex_to<numeric>(b));
1299 *ca = ex_to<numeric>(a) / g;
1301 *cb = ex_to<numeric>(b) / g;
1306 // The first symbol is our main variable
1307 const ex &x = var->sym;
1309 // Remove integer content
1310 numeric gc = gcd(a.integer_content(), b.integer_content());
1311 numeric rgc = gc.inverse();
1314 int maxdeg = std::max(p.degree(x), q.degree(x));
1316 // Find evaluation point
1317 numeric mp = p.max_coefficient();
1318 numeric mq = q.max_coefficient();
1321 xi = mq * (*_num2_p) + (*_num2_p);
1323 xi = mp * (*_num2_p) + (*_num2_p);
1326 for (int t=0; t<6; t++) {
1327 if (xi.int_length() * maxdeg > 100000) {
1328 throw gcdheu_failed();
1331 // Apply evaluation homomorphism and calculate GCD
1334 bool found = heur_gcd_z(gamma,
1335 p.subs(x == xi, subs_options::no_pattern),
1336 q.subs(x == xi, subs_options::no_pattern),
1339 gamma = gamma.expand();
1340 // Reconstruct polynomial from GCD of mapped polynomials
1341 ex g = interpolate(gamma, xi, x, maxdeg);
1343 // Remove integer content
1344 g /= g.integer_content();
1346 // If the calculated polynomial divides both p and q, this is the GCD
1348 if (divide_in_z(p, g, ca ? *ca : dummy, var) && divide_in_z(q, g, cb ? *cb : dummy, var)) {
1355 // Next evaluation point
1356 xi = iquo(xi * isqrt(isqrt(xi)) * numeric(73794), numeric(27011));
1361 /** Compute GCD of multivariate polynomials using the heuristic GCD algorithm.
1362 * get_symbol_stats() must have been called previously with the input
1363 * polynomials and an iterator to the first element of the sym_desc vector
1364 * passed in. This function is used internally by gcd().
1366 * @param a first rational multivariate polynomial (expanded)
1367 * @param b second rational multivariate polynomial (expanded)
1368 * @param ca cofactor of polynomial a (returned), NULL to suppress
1369 * calculation of cofactor
1370 * @param cb cofactor of polynomial b (returned), NULL to suppress
1371 * calculation of cofactor
1372 * @param var iterator to first element of vector of sym_desc structs
1373 * @param res the GCD (returned)
1374 * @return true if GCD was computed, false otherwise.
1378 static bool heur_gcd(ex& res, const ex& a, const ex& b, ex *ca, ex *cb,
1379 sym_desc_vec::const_iterator var)
1381 if (a.info(info_flags::integer_polynomial) &&
1382 b.info(info_flags::integer_polynomial)) {
1384 return heur_gcd_z(res, a, b, ca, cb, var);
1385 } catch (gcdheu_failed) {
1390 // convert polynomials to Z[X]
1391 const numeric a_lcm = lcm_of_coefficients_denominators(a);
1392 const numeric ab_lcm = lcmcoeff(b, a_lcm);
1394 const ex ai = a*ab_lcm;
1395 const ex bi = b*ab_lcm;
1396 if (!ai.info(info_flags::integer_polynomial))
1397 throw std::logic_error("heur_gcd: not an integer polynomial [1]");
1399 if (!bi.info(info_flags::integer_polynomial))
1400 throw std::logic_error("heur_gcd: not an integer polynomial [2]");
1404 found = heur_gcd_z(res, ai, bi, ca, cb, var);
1405 } catch (gcdheu_failed) {
1409 // GCD is not unique, it's defined up to a unit (i.e. invertible
1410 // element). If the coefficient ring is a field, every its element is
1411 // invertible, so one can multiply the polynomial GCD with any element
1412 // of the coefficient field. We use this ambiguity to make cofactors
1413 // integer polynomials.
1420 // gcd helper to handle partially factored polynomials (to avoid expanding
1421 // large expressions). At least one of the arguments should be a power.
1422 static ex gcd_pf_pow(const ex& a, const ex& b, ex* ca, ex* cb);
1424 // gcd helper to handle partially factored polynomials (to avoid expanding
1425 // large expressions). At least one of the arguments should be a product.
1426 static ex gcd_pf_mul(const ex& a, const ex& b, ex* ca, ex* cb);
1428 /** Compute GCD (Greatest Common Divisor) of multivariate polynomials a(X)
1429 * and b(X) in Z[X]. Optionally also compute the cofactors of a and b,
1430 * defined by a = ca * gcd(a, b) and b = cb * gcd(a, b).
1432 * @param a first multivariate polynomial
1433 * @param b second multivariate polynomial
1434 * @param ca pointer to expression that will receive the cofactor of a, or NULL
1435 * @param cb pointer to expression that will receive the cofactor of b, or NULL
1436 * @param check_args check whether a and b are polynomials with rational
1437 * coefficients (defaults to "true")
1438 * @return the GCD as a new expression */
1439 ex gcd(const ex &a, const ex &b, ex *ca, ex *cb, bool check_args, unsigned options)
1445 // GCD of numerics -> CLN
1446 if (is_exactly_a<numeric>(a) && is_exactly_a<numeric>(b)) {
1447 numeric g = gcd(ex_to<numeric>(a), ex_to<numeric>(b));
1456 *ca = ex_to<numeric>(a) / g;
1458 *cb = ex_to<numeric>(b) / g;
1465 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial))) {
1466 throw(std::invalid_argument("gcd: arguments must be polynomials over the rationals"));
1469 // Partially factored cases (to avoid expanding large expressions)
1470 if (!(options & gcd_options::no_part_factored)) {
1471 if (is_exactly_a<mul>(a) || is_exactly_a<mul>(b))
1472 return gcd_pf_mul(a, b, ca, cb);
1474 if (is_exactly_a<power>(a) || is_exactly_a<power>(b))
1475 return gcd_pf_pow(a, b, ca, cb);
1479 // Some trivial cases
1480 ex aex = a.expand(), bex = b.expand();
1481 if (aex.is_zero()) {
1488 if (bex.is_zero()) {
1495 if (aex.is_equal(_ex1) || bex.is_equal(_ex1)) {
1503 if (a.is_equal(b)) {
1512 if (is_a<symbol>(aex)) {
1513 if (! bex.subs(aex==_ex0, subs_options::no_pattern).is_zero()) {
1522 if (is_a<symbol>(bex)) {
1523 if (! aex.subs(bex==_ex0, subs_options::no_pattern).is_zero()) {
1532 if (is_exactly_a<numeric>(aex)) {
1533 numeric bcont = bex.integer_content();
1534 numeric g = gcd(ex_to<numeric>(aex), bcont);
1536 *ca = ex_to<numeric>(aex)/g;
1542 if (is_exactly_a<numeric>(bex)) {
1543 numeric acont = aex.integer_content();
1544 numeric g = gcd(ex_to<numeric>(bex), acont);
1548 *cb = ex_to<numeric>(bex)/g;
1552 // Gather symbol statistics
1553 sym_desc_vec sym_stats;
1554 get_symbol_stats(a, b, sym_stats);
1556 // The symbol with least degree which is contained in both polynomials
1557 // is our main variable
1558 sym_desc_vec::iterator vari = sym_stats.begin();
1559 while ((vari != sym_stats.end()) &&
1560 (((vari->ldeg_b == 0) && (vari->deg_b == 0)) ||
1561 ((vari->ldeg_a == 0) && (vari->deg_a == 0))))
1564 // No common symbols at all, just return 1:
1565 if (vari == sym_stats.end()) {
1566 // N.B: keep cofactors factored
1573 // move symbols which contained only in one of the polynomials
1575 rotate(sym_stats.begin(), vari, sym_stats.end());
1577 sym_desc_vec::const_iterator var = sym_stats.begin();
1578 const ex &x = var->sym;
1580 // Cancel trivial common factor
1581 int ldeg_a = var->ldeg_a;
1582 int ldeg_b = var->ldeg_b;
1583 int min_ldeg = std::min(ldeg_a,ldeg_b);
1585 ex common = power(x, min_ldeg);
1586 return gcd((aex / common).expand(), (bex / common).expand(), ca, cb, false) * common;
1589 // Try to eliminate variables
1590 if (var->deg_a == 0 && var->deg_b != 0 ) {
1591 ex bex_u, bex_c, bex_p;
1592 bex.unitcontprim(x, bex_u, bex_c, bex_p);
1593 ex g = gcd(aex, bex_c, ca, cb, false);
1595 *cb *= bex_u * bex_p;
1597 } else if (var->deg_b == 0 && var->deg_a != 0) {
1598 ex aex_u, aex_c, aex_p;
1599 aex.unitcontprim(x, aex_u, aex_c, aex_p);
1600 ex g = gcd(aex_c, bex, ca, cb, false);
1602 *ca *= aex_u * aex_p;
1606 // Try heuristic algorithm first, fall back to PRS if that failed
1608 if (!(options & gcd_options::no_heur_gcd)) {
1609 bool found = heur_gcd(g, aex, bex, ca, cb, var);
1611 // heur_gcd have already computed cofactors...
1612 if (g.is_equal(_ex1)) {
1613 // ... but we want to keep them factored if possible.
1627 if (options & gcd_options::use_sr_gcd) {
1628 g = sr_gcd(aex, bex, var);
1631 for (std::size_t n = sym_stats.size(); n-- != 0; )
1632 vars.push_back(sym_stats[n].sym);
1633 g = chinrem_gcd(aex, bex, vars);
1636 if (g.is_equal(_ex1)) {
1637 // Keep cofactors factored if possible
1644 divide(aex, g, *ca, false);
1646 divide(bex, g, *cb, false);
1651 // gcd helper to handle partially factored polynomials (to avoid expanding
1652 // large expressions). Both arguments should be powers.
1653 static ex gcd_pf_pow_pow(const ex& a, const ex& b, ex* ca, ex* cb)
1656 const ex& exp_a = a.op(1);
1658 const ex& exp_b = b.op(1);
1660 // a = p^n, b = p^m, gcd = p^min(n, m)
1661 if (p.is_equal(pb)) {
1662 if (exp_a < exp_b) {
1666 *cb = power(p, exp_b - exp_a);
1667 return power(p, exp_a);
1670 *ca = power(p, exp_a - exp_b);
1673 return power(p, exp_b);
1678 ex p_gcd = gcd(p, pb, &p_co, &pb_co, false);
1679 // a(x) = p(x)^n, b(x) = p_b(x)^m, gcd (p, p_b) = 1 ==> gcd(a,b) = 1
1680 if (p_gcd.is_equal(_ex1)) {
1686 // XXX: do I need to check for p_gcd = -1?
1689 // there are common factors:
1690 // a(x) = g(x)^n A(x)^n, b(x) = g(x)^m B(x)^m ==>
1691 // gcd(a, b) = g(x)^n gcd(A(x)^n, g(x)^(n-m) B(x)^m
1692 if (exp_a < exp_b) {
1693 ex pg = gcd(power(p_co, exp_a), power(p_gcd, exp_b-exp_a)*power(pb_co, exp_b), ca, cb, false);
1694 return power(p_gcd, exp_a)*pg;
1696 ex pg = gcd(power(p_gcd, exp_a - exp_b)*power(p_co, exp_a), power(pb_co, exp_b), ca, cb, false);
1697 return power(p_gcd, exp_b)*pg;
1701 static ex gcd_pf_pow(const ex& a, const ex& b, ex* ca, ex* cb)
1703 if (is_exactly_a<power>(a) && is_exactly_a<power>(b))
1704 return gcd_pf_pow_pow(a, b, ca, cb);
1706 if (is_exactly_a<power>(b) && (! is_exactly_a<power>(a)))
1707 return gcd_pf_pow(b, a, cb, ca);
1709 GINAC_ASSERT(is_exactly_a<power>(a));
1712 const ex& exp_a = a.op(1);
1713 if (p.is_equal(b)) {
1714 // a = p^n, b = p, gcd = p
1716 *ca = power(p, a.op(1) - 1);
1723 ex p_gcd = gcd(p, b, &p_co, &bpart_co, false);
1725 // a(x) = p(x)^n, gcd(p, b) = 1 ==> gcd(a, b) = 1
1726 if (p_gcd.is_equal(_ex1)) {
1733 // 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))
1734 ex rg = gcd(power(p_gcd, exp_a-1)*power(p_co, exp_a), bpart_co, ca, cb, false);
1738 static ex gcd_pf_mul(const ex& a, const ex& b, ex* ca, ex* cb)
1740 if (is_exactly_a<mul>(a) && is_exactly_a<mul>(b)
1741 && (b.nops() > a.nops()))
1742 return gcd_pf_mul(b, a, cb, ca);
1744 if (is_exactly_a<mul>(b) && (!is_exactly_a<mul>(a)))
1745 return gcd_pf_mul(b, a, cb, ca);
1747 GINAC_ASSERT(is_exactly_a<mul>(a));
1748 size_t num = a.nops();
1749 exvector g; g.reserve(num);
1750 exvector acc_ca; acc_ca.reserve(num);
1752 for (size_t i=0; i<num; i++) {
1753 ex part_ca, part_cb;
1754 g.push_back(gcd(a.op(i), part_b, &part_ca, &part_cb, false));
1755 acc_ca.push_back(part_ca);
1759 *ca = (new mul(acc_ca))->setflag(status_flags::dynallocated);
1762 return (new mul(g))->setflag(status_flags::dynallocated);
1765 /** Compute LCM (Least Common Multiple) of multivariate polynomials in Z[X].
1767 * @param a first multivariate polynomial
1768 * @param b second multivariate polynomial
1769 * @param check_args check whether a and b are polynomials with rational
1770 * coefficients (defaults to "true")
1771 * @return the LCM as a new expression */
1772 ex lcm(const ex &a, const ex &b, bool check_args)
1774 if (is_exactly_a<numeric>(a) && is_exactly_a<numeric>(b))
1775 return lcm(ex_to<numeric>(a), ex_to<numeric>(b));
1776 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
1777 throw(std::invalid_argument("lcm: arguments must be polynomials over the rationals"));
1780 ex g = gcd(a, b, &ca, &cb, false);
1786 * Square-free factorization
1789 /** Compute square-free factorization of multivariate polynomial a(x) using
1790 * Yun's algorithm. Used internally by sqrfree().
1792 * @param a multivariate polynomial over Z[X], treated here as univariate
1794 * @param x variable to factor in
1795 * @return vector of factors sorted in ascending degree */
1796 static exvector sqrfree_yun(const ex &a, const symbol &x)
1802 if (g.is_equal(_ex1)) {
1813 } while (!z.is_zero());
1818 /** Compute a square-free factorization of a multivariate polynomial in Q[X].
1820 * @param a multivariate polynomial over Q[X]
1821 * @param l lst of variables to factor in, may be left empty for autodetection
1822 * @return a square-free factorization of \p a.
1825 * A polynomial \f$p(X) \in C[X]\f$ is said <EM>square-free</EM>
1826 * if, whenever any two polynomials \f$q(X)\f$ and \f$r(X)\f$
1829 * p(X) = q(X)^2 r(X),
1831 * we have \f$q(X) \in C\f$.
1832 * This means that \f$p(X)\f$ has no repeated factors, apart
1833 * eventually from constants.
1834 * Given a polynomial \f$p(X) \in C[X]\f$, we say that the
1837 * p(X) = b \cdot p_1(X)^{a_1} \cdot p_2(X)^{a_2} \cdots p_r(X)^{a_r}
1839 * is a <EM>square-free factorization</EM> of \f$p(X)\f$ if the
1840 * following conditions hold:
1841 * -# \f$b \in C\f$ and \f$b \neq 0\f$;
1842 * -# \f$a_i\f$ is a positive integer for \f$i = 1, \ldots, r\f$;
1843 * -# the degree of the polynomial \f$p_i\f$ is strictly positive
1844 * for \f$i = 1, \ldots, r\f$;
1845 * -# the polynomial \f$\Pi_{i=1}^r p_i(X)\f$ is square-free.
1847 * Square-free factorizations need not be unique. For example, if
1848 * \f$a_i\f$ is even, we could change the polynomial \f$p_i(X)\f$
1849 * into \f$-p_i(X)\f$.
1850 * Observe also that the factors \f$p_i(X)\f$ need not be irreducible
1853 ex sqrfree(const ex &a, const lst &l)
1855 if (is_exactly_a<numeric>(a) || // algorithm does not trap a==0
1856 is_a<symbol>(a)) // shortcut
1859 // If no lst of variables to factorize in was specified we have to
1860 // invent one now. Maybe one can optimize here by reversing the order
1861 // or so, I don't know.
1865 get_symbol_stats(a, _ex0, sdv);
1866 sym_desc_vec::const_iterator it = sdv.begin(), itend = sdv.end();
1867 while (it != itend) {
1868 args.append(it->sym);
1875 // Find the symbol to factor in at this stage
1876 if (!is_a<symbol>(args.op(0)))
1877 throw (std::runtime_error("sqrfree(): invalid factorization variable"));
1878 const symbol &x = ex_to<symbol>(args.op(0));
1880 // convert the argument from something in Q[X] to something in Z[X]
1881 const numeric lcm = lcm_of_coefficients_denominators(a);
1882 const ex tmp = multiply_lcm(a,lcm);
1885 exvector factors = sqrfree_yun(tmp, x);
1887 // construct the next list of symbols with the first element popped
1889 newargs.remove_first();
1891 // recurse down the factors in remaining variables
1892 if (newargs.nops()>0) {
1893 exvector::iterator i = factors.begin();
1894 while (i != factors.end()) {
1895 *i = sqrfree(*i, newargs);
1900 // Done with recursion, now construct the final result
1902 exvector::const_iterator it = factors.begin(), itend = factors.end();
1903 for (int p = 1; it!=itend; ++it, ++p)
1904 result *= power(*it, p);
1906 // Yun's algorithm does not account for constant factors. (For univariate
1907 // polynomials it works only in the monic case.) We can correct this by
1908 // inserting what has been lost back into the result. For completeness
1909 // we'll also have to recurse down that factor in the remaining variables.
1910 if (newargs.nops()>0)
1911 result *= sqrfree(quo(tmp, result, x), newargs);
1913 result *= quo(tmp, result, x);
1915 // Put in the rational overall factor again and return
1916 return result * lcm.inverse();
1920 /** Compute square-free partial fraction decomposition of rational function
1923 * @param a rational function over Z[x], treated as univariate polynomial
1925 * @param x variable to factor in
1926 * @return decomposed rational function */
1927 ex sqrfree_parfrac(const ex & a, const symbol & x)
1929 // Find numerator and denominator
1930 ex nd = numer_denom(a);
1931 ex numer = nd.op(0), denom = nd.op(1);
1932 //clog << "numer = " << numer << ", denom = " << denom << endl;
1934 // Convert N(x)/D(x) -> Q(x) + R(x)/D(x), so degree(R) < degree(D)
1935 ex red_poly = quo(numer, denom, x), red_numer = rem(numer, denom, x).expand();
1936 //clog << "red_poly = " << red_poly << ", red_numer = " << red_numer << endl;
1938 // Factorize denominator and compute cofactors
1939 exvector yun = sqrfree_yun(denom, x);
1940 //clog << "yun factors: " << exprseq(yun) << endl;
1941 size_t num_yun = yun.size();
1942 exvector factor; factor.reserve(num_yun);
1943 exvector cofac; cofac.reserve(num_yun);
1944 for (size_t i=0; i<num_yun; i++) {
1945 if (!yun[i].is_equal(_ex1)) {
1946 for (size_t j=0; j<=i; j++) {
1947 factor.push_back(pow(yun[i], j+1));
1949 for (size_t k=0; k<num_yun; k++) {
1951 prod *= pow(yun[k], i-j);
1953 prod *= pow(yun[k], k+1);
1955 cofac.push_back(prod.expand());
1959 size_t num_factors = factor.size();
1960 //clog << "factors : " << exprseq(factor) << endl;
1961 //clog << "cofactors: " << exprseq(cofac) << endl;
1963 // Construct coefficient matrix for decomposition
1964 int max_denom_deg = denom.degree(x);
1965 matrix sys(max_denom_deg + 1, num_factors);
1966 matrix rhs(max_denom_deg + 1, 1);
1967 for (int i=0; i<=max_denom_deg; i++) {
1968 for (size_t j=0; j<num_factors; j++)
1969 sys(i, j) = cofac[j].coeff(x, i);
1970 rhs(i, 0) = red_numer.coeff(x, i);
1972 //clog << "coeffs: " << sys << endl;
1973 //clog << "rhs : " << rhs << endl;
1975 // Solve resulting linear system
1976 matrix vars(num_factors, 1);
1977 for (size_t i=0; i<num_factors; i++)
1978 vars(i, 0) = symbol();
1979 matrix sol = sys.solve(vars, rhs);
1981 // Sum up decomposed fractions
1983 for (size_t i=0; i<num_factors; i++)
1984 sum += sol(i, 0) / factor[i];
1986 return red_poly + sum;
1991 * Normal form of rational functions
1995 * Note: The internal normal() functions (= basic::normal() and overloaded
1996 * functions) all return lists of the form {numerator, denominator}. This
1997 * is to get around mul::eval()'s automatic expansion of numeric coefficients.
1998 * E.g. (a+b)/3 is automatically converted to a/3+b/3 but we want to keep
1999 * the information that (a+b) is the numerator and 3 is the denominator.
2003 /** Create a symbol for replacing the expression "e" (or return a previously
2004 * assigned symbol). The symbol and expression are appended to repl, for
2005 * a later application of subs().
2006 * @see ex::normal */
2007 static ex replace_with_symbol(const ex & e, exmap & repl, exmap & rev_lookup)
2009 // Since the repl contains replaced expressions we should search for them
2010 ex e_replaced = e.subs(repl, subs_options::no_pattern);
2012 // Expression already replaced? Then return the assigned symbol
2013 exmap::const_iterator it = rev_lookup.find(e_replaced);
2014 if (it != rev_lookup.end())
2017 // Otherwise create new symbol and add to list, taking care that the
2018 // replacement expression doesn't itself contain symbols from repl,
2019 // because subs() is not recursive
2020 ex es = (new symbol)->setflag(status_flags::dynallocated);
2021 repl.insert(std::make_pair(es, e_replaced));
2022 rev_lookup.insert(std::make_pair(e_replaced, es));
2026 /** Create a symbol for replacing the expression "e" (or return a previously
2027 * assigned symbol). The symbol and expression are appended to repl, and the
2028 * symbol is returned.
2029 * @see basic::to_rational
2030 * @see basic::to_polynomial */
2031 static ex replace_with_symbol(const ex & e, exmap & repl)
2033 // Since the repl contains replaced expressions we should search for them
2034 ex e_replaced = e.subs(repl, subs_options::no_pattern);
2036 // Expression already replaced? Then return the assigned symbol
2037 for (exmap::const_iterator it = repl.begin(); it != repl.end(); ++it)
2038 if (it->second.is_equal(e_replaced))
2041 // Otherwise create new symbol and add to list, taking care that the
2042 // replacement expression doesn't itself contain symbols from repl,
2043 // because subs() is not recursive
2044 ex es = (new symbol)->setflag(status_flags::dynallocated);
2045 repl.insert(std::make_pair(es, e_replaced));
2050 /** Function object to be applied by basic::normal(). */
2051 struct normal_map_function : public map_function {
2053 normal_map_function(int l) : level(l) {}
2054 ex operator()(const ex & e) { return normal(e, level); }
2057 /** Default implementation of ex::normal(). It normalizes the children and
2058 * replaces the object with a temporary symbol.
2059 * @see ex::normal */
2060 ex basic::normal(exmap & repl, exmap & rev_lookup, int level) const
2063 return (new lst(replace_with_symbol(*this, repl, rev_lookup), _ex1))->setflag(status_flags::dynallocated);
2066 return (new lst(replace_with_symbol(*this, repl, rev_lookup), _ex1))->setflag(status_flags::dynallocated);
2067 else if (level == -max_recursion_level)
2068 throw(std::runtime_error("max recursion level reached"));
2070 normal_map_function map_normal(level - 1);
2071 return (new lst(replace_with_symbol(map(map_normal), repl, rev_lookup), _ex1))->setflag(status_flags::dynallocated);
2077 /** Implementation of ex::normal() for symbols. This returns the unmodified symbol.
2078 * @see ex::normal */
2079 ex symbol::normal(exmap & repl, exmap & rev_lookup, int level) const
2081 return (new lst(*this, _ex1))->setflag(status_flags::dynallocated);
2085 /** Implementation of ex::normal() for a numeric. It splits complex numbers
2086 * into re+I*im and replaces I and non-rational real numbers with a temporary
2088 * @see ex::normal */
2089 ex numeric::normal(exmap & repl, exmap & rev_lookup, int level) const
2091 numeric num = numer();
2094 if (num.is_real()) {
2095 if (!num.is_integer())
2096 numex = replace_with_symbol(numex, repl, rev_lookup);
2098 numeric re = num.real(), im = num.imag();
2099 ex re_ex = re.is_rational() ? re : replace_with_symbol(re, repl, rev_lookup);
2100 ex im_ex = im.is_rational() ? im : replace_with_symbol(im, repl, rev_lookup);
2101 numex = re_ex + im_ex * replace_with_symbol(I, repl, rev_lookup);
2104 // Denominator is always a real integer (see numeric::denom())
2105 return (new lst(numex, denom()))->setflag(status_flags::dynallocated);
2109 /** Fraction cancellation.
2110 * @param n numerator
2111 * @param d denominator
2112 * @return cancelled fraction {n, d} as a list */
2113 static ex frac_cancel(const ex &n, const ex &d)
2117 numeric pre_factor = *_num1_p;
2119 //std::clog << "frac_cancel num = " << num << ", den = " << den << std::endl;
2121 // Handle trivial case where denominator is 1
2122 if (den.is_equal(_ex1))
2123 return (new lst(num, den))->setflag(status_flags::dynallocated);
2125 // Handle special cases where numerator or denominator is 0
2127 return (new lst(num, _ex1))->setflag(status_flags::dynallocated);
2128 if (den.expand().is_zero())
2129 throw(std::overflow_error("frac_cancel: division by zero in frac_cancel"));
2131 // Bring numerator and denominator to Z[X] by multiplying with
2132 // LCM of all coefficients' denominators
2133 numeric num_lcm = lcm_of_coefficients_denominators(num);
2134 numeric den_lcm = lcm_of_coefficients_denominators(den);
2135 num = multiply_lcm(num, num_lcm);
2136 den = multiply_lcm(den, den_lcm);
2137 pre_factor = den_lcm / num_lcm;
2139 // Cancel GCD from numerator and denominator
2141 if (gcd(num, den, &cnum, &cden, false) != _ex1) {
2146 // Make denominator unit normal (i.e. coefficient of first symbol
2147 // as defined by get_first_symbol() is made positive)
2148 if (is_exactly_a<numeric>(den)) {
2149 if (ex_to<numeric>(den).is_negative()) {
2155 if (get_first_symbol(den, x)) {
2156 GINAC_ASSERT(is_exactly_a<numeric>(den.unit(x)));
2157 if (ex_to<numeric>(den.unit(x)).is_negative()) {
2164 // Return result as list
2165 //std::clog << " returns num = " << num << ", den = " << den << ", pre_factor = " << pre_factor << std::endl;
2166 return (new lst(num * pre_factor.numer(), den * pre_factor.denom()))->setflag(status_flags::dynallocated);
2170 /** Implementation of ex::normal() for a sum. It expands terms and performs
2171 * fractional addition.
2172 * @see ex::normal */
2173 ex add::normal(exmap & repl, exmap & rev_lookup, int level) const
2176 return (new lst(replace_with_symbol(*this, repl, rev_lookup), _ex1))->setflag(status_flags::dynallocated);
2177 else if (level == -max_recursion_level)
2178 throw(std::runtime_error("max recursion level reached"));
2180 // Normalize children and split each one into numerator and denominator
2181 exvector nums, dens;
2182 nums.reserve(seq.size()+1);
2183 dens.reserve(seq.size()+1);
2184 epvector::const_iterator it = seq.begin(), itend = seq.end();
2185 while (it != itend) {
2186 ex n = ex_to<basic>(recombine_pair_to_ex(*it)).normal(repl, rev_lookup, level-1);
2187 nums.push_back(n.op(0));
2188 dens.push_back(n.op(1));
2191 ex n = ex_to<numeric>(overall_coeff).normal(repl, rev_lookup, level-1);
2192 nums.push_back(n.op(0));
2193 dens.push_back(n.op(1));
2194 GINAC_ASSERT(nums.size() == dens.size());
2196 // Now, nums is a vector of all numerators and dens is a vector of
2198 //std::clog << "add::normal uses " << nums.size() << " summands:\n";
2200 // Add fractions sequentially
2201 exvector::const_iterator num_it = nums.begin(), num_itend = nums.end();
2202 exvector::const_iterator den_it = dens.begin(), den_itend = dens.end();
2203 //std::clog << " num = " << *num_it << ", den = " << *den_it << std::endl;
2204 ex num = *num_it++, den = *den_it++;
2205 while (num_it != num_itend) {
2206 //std::clog << " num = " << *num_it << ", den = " << *den_it << std::endl;
2207 ex next_num = *num_it++, next_den = *den_it++;
2209 // Trivially add sequences of fractions with identical denominators
2210 while ((den_it != den_itend) && next_den.is_equal(*den_it)) {
2211 next_num += *num_it;
2215 // Addition of two fractions, taking advantage of the fact that
2216 // the heuristic GCD algorithm computes the cofactors at no extra cost
2217 ex co_den1, co_den2;
2218 ex g = gcd(den, next_den, &co_den1, &co_den2, false);
2219 num = ((num * co_den2) + (next_num * co_den1)).expand();
2220 den *= co_den2; // this is the lcm(den, next_den)
2222 //std::clog << " common denominator = " << den << std::endl;
2224 // Cancel common factors from num/den
2225 return frac_cancel(num, den);
2229 /** Implementation of ex::normal() for a product. It cancels common factors
2231 * @see ex::normal() */
2232 ex mul::normal(exmap & repl, exmap & rev_lookup, int level) const
2235 return (new lst(replace_with_symbol(*this, repl, rev_lookup), _ex1))->setflag(status_flags::dynallocated);
2236 else if (level == -max_recursion_level)
2237 throw(std::runtime_error("max recursion level reached"));
2239 // Normalize children, separate into numerator and denominator
2240 exvector num; num.reserve(seq.size());
2241 exvector den; den.reserve(seq.size());
2243 epvector::const_iterator it = seq.begin(), itend = seq.end();
2244 while (it != itend) {
2245 n = ex_to<basic>(recombine_pair_to_ex(*it)).normal(repl, rev_lookup, level-1);
2246 num.push_back(n.op(0));
2247 den.push_back(n.op(1));
2250 n = ex_to<numeric>(overall_coeff).normal(repl, rev_lookup, level-1);
2251 num.push_back(n.op(0));
2252 den.push_back(n.op(1));
2254 // Perform fraction cancellation
2255 return frac_cancel((new mul(num))->setflag(status_flags::dynallocated),
2256 (new mul(den))->setflag(status_flags::dynallocated));
2260 /** Implementation of ex::normal([B) for powers. It normalizes the basis,
2261 * distributes integer exponents to numerator and denominator, and replaces
2262 * non-integer powers by temporary symbols.
2263 * @see ex::normal */
2264 ex power::normal(exmap & repl, exmap & rev_lookup, int level) const
2267 return (new lst(replace_with_symbol(*this, repl, rev_lookup), _ex1))->setflag(status_flags::dynallocated);
2268 else if (level == -max_recursion_level)
2269 throw(std::runtime_error("max recursion level reached"));
2271 // Normalize basis and exponent (exponent gets reassembled)
2272 ex n_basis = ex_to<basic>(basis).normal(repl, rev_lookup, level-1);
2273 ex n_exponent = ex_to<basic>(exponent).normal(repl, rev_lookup, level-1);
2274 n_exponent = n_exponent.op(0) / n_exponent.op(1);
2276 if (n_exponent.info(info_flags::integer)) {
2278 if (n_exponent.info(info_flags::positive)) {
2280 // (a/b)^n -> {a^n, b^n}
2281 return (new lst(power(n_basis.op(0), n_exponent), power(n_basis.op(1), n_exponent)))->setflag(status_flags::dynallocated);
2283 } else if (n_exponent.info(info_flags::negative)) {
2285 // (a/b)^-n -> {b^n, a^n}
2286 return (new lst(power(n_basis.op(1), -n_exponent), power(n_basis.op(0), -n_exponent)))->setflag(status_flags::dynallocated);
2291 if (n_exponent.info(info_flags::positive)) {
2293 // (a/b)^x -> {sym((a/b)^x), 1}
2294 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);
2296 } else if (n_exponent.info(info_flags::negative)) {
2298 if (n_basis.op(1).is_equal(_ex1)) {
2300 // a^-x -> {1, sym(a^x)}
2301 return (new lst(_ex1, replace_with_symbol(power(n_basis.op(0), -n_exponent), repl, rev_lookup)))->setflag(status_flags::dynallocated);
2305 // (a/b)^-x -> {sym((b/a)^x), 1}
2306 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);
2311 // (a/b)^x -> {sym((a/b)^x, 1}
2312 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);
2316 /** Implementation of ex::normal() for pseries. It normalizes each coefficient
2317 * and replaces the series by a temporary symbol.
2318 * @see ex::normal */
2319 ex pseries::normal(exmap & repl, exmap & rev_lookup, int level) const
2322 epvector::const_iterator i = seq.begin(), end = seq.end();
2324 ex restexp = i->rest.normal();
2325 if (!restexp.is_zero())
2326 newseq.push_back(expair(restexp, i->coeff));
2329 ex n = pseries(relational(var,point), newseq);
2330 return (new lst(replace_with_symbol(n, repl, rev_lookup), _ex1))->setflag(status_flags::dynallocated);
2334 /** Normalization of rational functions.
2335 * This function converts an expression to its normal form
2336 * "numerator/denominator", where numerator and denominator are (relatively
2337 * prime) polynomials. Any subexpressions which are not rational functions
2338 * (like non-rational numbers, non-integer powers or functions like sin(),
2339 * cos() etc.) are replaced by temporary symbols which are re-substituted by
2340 * the (normalized) subexpressions before normal() returns (this way, any
2341 * expression can be treated as a rational function). normal() is applied
2342 * recursively to arguments of functions etc.
2344 * @param level maximum depth of recursion
2345 * @return normalized expression */
2346 ex ex::normal(int level) const
2348 exmap repl, rev_lookup;
2350 ex e = bp->normal(repl, rev_lookup, level);
2351 GINAC_ASSERT(is_a<lst>(e));
2353 // Re-insert replaced symbols
2355 e = e.subs(repl, subs_options::no_pattern);
2357 // Convert {numerator, denominator} form back to fraction
2358 return e.op(0) / e.op(1);
2361 /** Get numerator of an expression. If the expression is not of the normal
2362 * form "numerator/denominator", it is first converted to this form and
2363 * then the numerator is returned.
2366 * @return numerator */
2367 ex ex::numer() const
2369 exmap repl, rev_lookup;
2371 ex e = bp->normal(repl, rev_lookup, 0);
2372 GINAC_ASSERT(is_a<lst>(e));
2374 // Re-insert replaced symbols
2378 return e.op(0).subs(repl, subs_options::no_pattern);
2381 /** Get denominator of an expression. If the expression is not of the normal
2382 * form "numerator/denominator", it is first converted to this form and
2383 * then the denominator is returned.
2386 * @return denominator */
2387 ex ex::denom() const
2389 exmap repl, rev_lookup;
2391 ex e = bp->normal(repl, rev_lookup, 0);
2392 GINAC_ASSERT(is_a<lst>(e));
2394 // Re-insert replaced symbols
2398 return e.op(1).subs(repl, subs_options::no_pattern);
2401 /** Get numerator and denominator of an expression. If the expression is not
2402 * of the normal form "numerator/denominator", it is first converted to this
2403 * form and then a list [numerator, denominator] is returned.
2406 * @return a list [numerator, denominator] */
2407 ex ex::numer_denom() const
2409 exmap repl, rev_lookup;
2411 ex e = bp->normal(repl, rev_lookup, 0);
2412 GINAC_ASSERT(is_a<lst>(e));
2414 // Re-insert replaced symbols
2418 return e.subs(repl, subs_options::no_pattern);
2422 /** Rationalization of non-rational functions.
2423 * This function converts a general expression to a rational function
2424 * by replacing all non-rational subexpressions (like non-rational numbers,
2425 * non-integer powers or functions like sin(), cos() etc.) to temporary
2426 * symbols. This makes it possible to use functions like gcd() and divide()
2427 * on non-rational functions by applying to_rational() on the arguments,
2428 * calling the desired function and re-substituting the temporary symbols
2429 * in the result. To make the last step possible, all temporary symbols and
2430 * their associated expressions are collected in the map specified by the
2431 * repl parameter, ready to be passed as an argument to ex::subs().
2433 * @param repl collects all temporary symbols and their replacements
2434 * @return rationalized expression */
2435 ex ex::to_rational(exmap & repl) const
2437 return bp->to_rational(repl);
2440 // GiNaC 1.1 compatibility function
2441 ex ex::to_rational(lst & repl_lst) const
2443 // Convert lst to exmap
2445 for (lst::const_iterator it = repl_lst.begin(); it != repl_lst.end(); ++it)
2446 m.insert(std::make_pair(it->op(0), it->op(1)));
2448 ex ret = bp->to_rational(m);
2450 // Convert exmap back to lst
2451 repl_lst.remove_all();
2452 for (exmap::const_iterator it = m.begin(); it != m.end(); ++it)
2453 repl_lst.append(it->first == it->second);
2458 ex ex::to_polynomial(exmap & repl) const
2460 return bp->to_polynomial(repl);
2463 // GiNaC 1.1 compatibility function
2464 ex ex::to_polynomial(lst & repl_lst) const
2466 // Convert lst to exmap
2468 for (lst::const_iterator it = repl_lst.begin(); it != repl_lst.end(); ++it)
2469 m.insert(std::make_pair(it->op(0), it->op(1)));
2471 ex ret = bp->to_polynomial(m);
2473 // Convert exmap back to lst
2474 repl_lst.remove_all();
2475 for (exmap::const_iterator it = m.begin(); it != m.end(); ++it)
2476 repl_lst.append(it->first == it->second);
2481 /** Default implementation of ex::to_rational(). This replaces the object with
2482 * a temporary symbol. */
2483 ex basic::to_rational(exmap & repl) const
2485 return replace_with_symbol(*this, repl);
2488 ex basic::to_polynomial(exmap & repl) const
2490 return replace_with_symbol(*this, repl);
2494 /** Implementation of ex::to_rational() for symbols. This returns the
2495 * unmodified symbol. */
2496 ex symbol::to_rational(exmap & repl) const
2501 /** Implementation of ex::to_polynomial() for symbols. This returns the
2502 * unmodified symbol. */
2503 ex symbol::to_polynomial(exmap & repl) const
2509 /** Implementation of ex::to_rational() for a numeric. It splits complex
2510 * numbers into re+I*im and replaces I and non-rational real numbers with a
2511 * temporary symbol. */
2512 ex numeric::to_rational(exmap & repl) const
2516 return replace_with_symbol(*this, repl);
2518 numeric re = real();
2519 numeric im = imag();
2520 ex re_ex = re.is_rational() ? re : replace_with_symbol(re, repl);
2521 ex im_ex = im.is_rational() ? im : replace_with_symbol(im, repl);
2522 return re_ex + im_ex * replace_with_symbol(I, repl);
2527 /** Implementation of ex::to_polynomial() for a numeric. It splits complex
2528 * numbers into re+I*im and replaces I and non-integer real numbers with a
2529 * temporary symbol. */
2530 ex numeric::to_polynomial(exmap & repl) const
2534 return replace_with_symbol(*this, repl);
2536 numeric re = real();
2537 numeric im = imag();
2538 ex re_ex = re.is_integer() ? re : replace_with_symbol(re, repl);
2539 ex im_ex = im.is_integer() ? im : replace_with_symbol(im, repl);
2540 return re_ex + im_ex * replace_with_symbol(I, repl);
2546 /** Implementation of ex::to_rational() for powers. It replaces non-integer
2547 * powers by temporary symbols. */
2548 ex power::to_rational(exmap & repl) const
2550 if (exponent.info(info_flags::integer))
2551 return power(basis.to_rational(repl), exponent);
2553 return replace_with_symbol(*this, repl);
2556 /** Implementation of ex::to_polynomial() for powers. It replaces non-posint
2557 * powers by temporary symbols. */
2558 ex power::to_polynomial(exmap & repl) const
2560 if (exponent.info(info_flags::posint))
2561 return power(basis.to_rational(repl), exponent);
2562 else if (exponent.info(info_flags::negint))
2564 ex basis_pref = collect_common_factors(basis);
2565 if (is_exactly_a<mul>(basis_pref) || is_exactly_a<power>(basis_pref)) {
2566 // (A*B)^n will be automagically transformed to A^n*B^n
2567 ex t = power(basis_pref, exponent);
2568 return t.to_polynomial(repl);
2571 return power(replace_with_symbol(power(basis, _ex_1), repl), -exponent);
2574 return replace_with_symbol(*this, repl);
2578 /** Implementation of ex::to_rational() for expairseqs. */
2579 ex expairseq::to_rational(exmap & repl) const
2582 s.reserve(seq.size());
2583 epvector::const_iterator i = seq.begin(), end = seq.end();
2585 s.push_back(split_ex_to_pair(recombine_pair_to_ex(*i).to_rational(repl)));
2588 ex oc = overall_coeff.to_rational(repl);
2589 if (oc.info(info_flags::numeric))
2590 return thisexpairseq(s, overall_coeff);
2592 s.push_back(combine_ex_with_coeff_to_pair(oc, _ex1));
2593 return thisexpairseq(s, default_overall_coeff());
2596 /** Implementation of ex::to_polynomial() for expairseqs. */
2597 ex expairseq::to_polynomial(exmap & repl) const
2600 s.reserve(seq.size());
2601 epvector::const_iterator i = seq.begin(), end = seq.end();
2603 s.push_back(split_ex_to_pair(recombine_pair_to_ex(*i).to_polynomial(repl)));
2606 ex oc = overall_coeff.to_polynomial(repl);
2607 if (oc.info(info_flags::numeric))
2608 return thisexpairseq(s, overall_coeff);
2610 s.push_back(combine_ex_with_coeff_to_pair(oc, _ex1));
2611 return thisexpairseq(s, default_overall_coeff());
2615 /** Remove the common factor in the terms of a sum 'e' by calculating the GCD,
2616 * and multiply it into the expression 'factor' (which needs to be initialized
2617 * to 1, unless you're accumulating factors). */
2618 static ex find_common_factor(const ex & e, ex & factor, exmap & repl)
2620 if (is_exactly_a<add>(e)) {
2622 size_t num = e.nops();
2623 exvector terms; terms.reserve(num);
2626 // Find the common GCD
2627 for (size_t i=0; i<num; i++) {
2628 ex x = e.op(i).to_polynomial(repl);
2630 if (is_exactly_a<add>(x) || is_exactly_a<mul>(x) || is_a<power>(x)) {
2632 x = find_common_factor(x, f, repl);
2644 if (gc.is_equal(_ex1))
2647 // The GCD is the factor we pull out
2650 // Now divide all terms by the GCD
2651 for (size_t i=0; i<num; i++) {
2654 // Try to avoid divide() because it expands the polynomial
2656 if (is_exactly_a<mul>(t)) {
2657 for (size_t j=0; j<t.nops(); j++) {
2658 if (t.op(j).is_equal(gc)) {
2659 exvector v; v.reserve(t.nops());
2660 for (size_t k=0; k<t.nops(); k++) {
2664 v.push_back(t.op(k));
2666 t = (new mul(v))->setflag(status_flags::dynallocated);
2676 return (new add(terms))->setflag(status_flags::dynallocated);
2678 } else if (is_exactly_a<mul>(e)) {
2680 size_t num = e.nops();
2681 exvector v; v.reserve(num);
2683 for (size_t i=0; i<num; i++)
2684 v.push_back(find_common_factor(e.op(i), factor, repl));
2686 return (new mul(v))->setflag(status_flags::dynallocated);
2688 } else if (is_exactly_a<power>(e)) {
2689 const ex e_exp(e.op(1));
2690 if (e_exp.info(info_flags::integer)) {
2691 ex eb = e.op(0).to_polynomial(repl);
2692 ex factor_local(_ex1);
2693 ex pre_res = find_common_factor(eb, factor_local, repl);
2694 factor *= power(factor_local, e_exp);
2695 return power(pre_res, e_exp);
2698 return e.to_polynomial(repl);
2705 /** Collect common factors in sums. This converts expressions like
2706 * 'a*(b*x+b*y)' to 'a*b*(x+y)'. */
2707 ex collect_common_factors(const ex & e)
2709 if (is_exactly_a<add>(e) || is_exactly_a<mul>(e) || is_exactly_a<power>(e)) {
2713 ex r = find_common_factor(e, factor, repl);
2714 return factor.subs(repl, subs_options::no_pattern) * r.subs(repl, subs_options::no_pattern);
2721 /** Resultant of two expressions e1,e2 with respect to symbol s.
2722 * Method: Compute determinant of Sylvester matrix of e1,e2,s. */
2723 ex resultant(const ex & e1, const ex & e2, const ex & s)
2725 const ex ee1 = e1.expand();
2726 const ex ee2 = e2.expand();
2727 if (!ee1.info(info_flags::polynomial) ||
2728 !ee2.info(info_flags::polynomial))
2729 throw(std::runtime_error("resultant(): arguments must be polynomials"));
2731 const int h1 = ee1.degree(s);
2732 const int l1 = ee1.ldegree(s);
2733 const int h2 = ee2.degree(s);
2734 const int l2 = ee2.ldegree(s);
2736 const int msize = h1 + h2;
2737 matrix m(msize, msize);
2739 for (int l = h1; l >= l1; --l) {
2740 const ex e = ee1.coeff(s, l);
2741 for (int k = 0; k < h2; ++k)
2744 for (int l = h2; l >= l2; --l) {
2745 const ex e = ee2.coeff(s, l);
2746 for (int k = 0; k < h1; ++k)
2747 m(k+h2, k+h2-l) = e;
2750 return m.determinant();
2754 } // namespace GiNaC