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 /** Initialize symbol, leave other variables uninitialized */
124 sym_desc(const ex& s)
125 : sym(s), deg_a(0), deg_b(0), ldeg_a(0), ldeg_b(0), max_deg(0), max_lcnops(0)
128 /** Reference to symbol */
131 /** Highest degree of symbol in polynomial "a" */
134 /** Highest degree of symbol in polynomial "b" */
137 /** Lowest degree of symbol in polynomial "a" */
140 /** Lowest degree of symbol in polynomial "b" */
143 /** Maximum of deg_a and deg_b (Used for sorting) */
146 /** Maximum number of terms of leading coefficient of symbol in both polynomials */
149 /** Commparison operator for sorting */
150 bool operator<(const sym_desc &x) const
152 if (max_deg == x.max_deg)
153 return max_lcnops < x.max_lcnops;
155 return max_deg < x.max_deg;
159 // Vector of sym_desc structures
160 typedef std::vector<sym_desc> sym_desc_vec;
162 // Add symbol the sym_desc_vec (used internally by get_symbol_stats())
163 static void add_symbol(const ex &s, sym_desc_vec &v)
166 if (it.sym.is_equal(s)) // If it's already in there, don't add it a second time
169 v.push_back(sym_desc(s));
172 // Collect all symbols of an expression (used internally by get_symbol_stats())
173 static void collect_symbols(const ex &e, sym_desc_vec &v)
175 if (is_a<symbol>(e)) {
177 } else if (is_exactly_a<add>(e) || is_exactly_a<mul>(e)) {
178 for (size_t i=0; i<e.nops(); i++)
179 collect_symbols(e.op(i), v);
180 } else if (is_exactly_a<power>(e)) {
181 collect_symbols(e.op(0), v);
185 /** Collect statistical information about symbols in polynomials.
186 * This function fills in a vector of "sym_desc" structs which contain
187 * information about the highest and lowest degrees of all symbols that
188 * appear in two polynomials. The vector is then sorted by minimum
189 * degree (lowest to highest). The information gathered by this
190 * function is used by the GCD routines to identify trivial factors
191 * and to determine which variable to choose as the main variable
192 * for GCD computation.
194 * @param a first multivariate polynomial
195 * @param b second multivariate polynomial
196 * @param v vector of sym_desc structs (filled in) */
197 static void get_symbol_stats(const ex &a, const ex &b, sym_desc_vec &v)
199 collect_symbols(a, v);
200 collect_symbols(b, v);
201 for (auto & it : v) {
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);
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 dynallocate<mul>(v);
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 dynallocate<add>(v);
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 numeric c = *_num0_p, l = *_num1_p;
324 for (auto & it : seq) {
325 GINAC_ASSERT(!is_exactly_a<numeric>(it.rest));
326 GINAC_ASSERT(is_exactly_a<numeric>(it.coeff));
327 c = gcd(ex_to<numeric>(it.coeff).numer(), c);
328 l = lcm(ex_to<numeric>(it.coeff).denom(), l);
330 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
331 c = gcd(ex_to<numeric>(overall_coeff).numer(), c);
332 l = lcm(ex_to<numeric>(overall_coeff).denom(), l);
336 numeric mul::integer_content() const
338 #ifdef DO_GINAC_ASSERT
339 for (auto & it : seq) {
340 GINAC_ASSERT(!is_exactly_a<numeric>(recombine_pair_to_ex(it)));
342 #endif // def DO_GINAC_ASSERT
343 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
344 return abs(ex_to<numeric>(overall_coeff));
349 * Polynomial quotients and remainders
352 /** Quotient q(x) of polynomials a(x) and b(x) in Q[x].
353 * It satisfies a(x)=b(x)*q(x)+r(x).
355 * @param a first polynomial in x (dividend)
356 * @param b second polynomial in x (divisor)
357 * @param x a and b are polynomials in x
358 * @param check_args check whether a and b are polynomials with rational
359 * coefficients (defaults to "true")
360 * @return quotient of a and b in Q[x] */
361 ex quo(const ex &a, const ex &b, const ex &x, bool check_args)
364 throw(std::overflow_error("quo: division by zero"));
365 if (is_exactly_a<numeric>(a) && is_exactly_a<numeric>(b))
371 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
372 throw(std::invalid_argument("quo: arguments must be polynomials over the rationals"));
374 // Polynomial long division
378 int bdeg = b.degree(x);
379 int rdeg = r.degree(x);
380 ex blcoeff = b.expand().coeff(x, bdeg);
381 bool blcoeff_is_numeric = is_exactly_a<numeric>(blcoeff);
382 exvector v; v.reserve(std::max(rdeg - bdeg + 1, 0));
383 while (rdeg >= bdeg) {
384 ex term, rcoeff = r.coeff(x, rdeg);
385 if (blcoeff_is_numeric)
386 term = rcoeff / blcoeff;
388 if (!divide(rcoeff, blcoeff, term, false))
389 return dynallocate<fail>();
391 term *= power(x, rdeg - bdeg);
393 r -= (term * b).expand();
398 return dynallocate<add>(v);
402 /** Remainder r(x) of polynomials a(x) and b(x) in Q[x].
403 * It satisfies a(x)=b(x)*q(x)+r(x).
405 * @param a first polynomial in x (dividend)
406 * @param b second polynomial in x (divisor)
407 * @param x a and b are polynomials in x
408 * @param check_args check whether a and b are polynomials with rational
409 * coefficients (defaults to "true")
410 * @return remainder of a(x) and b(x) in Q[x] */
411 ex rem(const ex &a, const ex &b, const ex &x, bool check_args)
414 throw(std::overflow_error("rem: division by zero"));
415 if (is_exactly_a<numeric>(a)) {
416 if (is_exactly_a<numeric>(b))
425 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
426 throw(std::invalid_argument("rem: arguments must be polynomials over the rationals"));
428 // Polynomial long division
432 int bdeg = b.degree(x);
433 int rdeg = r.degree(x);
434 ex blcoeff = b.expand().coeff(x, bdeg);
435 bool blcoeff_is_numeric = is_exactly_a<numeric>(blcoeff);
436 while (rdeg >= bdeg) {
437 ex term, rcoeff = r.coeff(x, rdeg);
438 if (blcoeff_is_numeric)
439 term = rcoeff / blcoeff;
441 if (!divide(rcoeff, blcoeff, term, false))
442 return dynallocate<fail>();
444 term *= power(x, rdeg - bdeg);
445 r -= (term * b).expand();
454 /** Decompose rational function a(x)=N(x)/D(x) into P(x)+n(x)/D(x)
455 * with degree(n, x) < degree(D, x).
457 * @param a rational function in x
458 * @param x a is a function of x
459 * @return decomposed function. */
460 ex decomp_rational(const ex &a, const ex &x)
462 ex nd = numer_denom(a);
463 ex numer = nd.op(0), denom = nd.op(1);
464 ex q = quo(numer, denom, x);
465 if (is_exactly_a<fail>(q))
468 return q + rem(numer, denom, x) / denom;
472 /** Pseudo-remainder of polynomials a(x) and b(x) in Q[x].
474 * @param a first polynomial in x (dividend)
475 * @param b second polynomial in x (divisor)
476 * @param x a and b are polynomials in x
477 * @param check_args check whether a and b are polynomials with rational
478 * coefficients (defaults to "true")
479 * @return pseudo-remainder of a(x) and b(x) in Q[x] */
480 ex prem(const ex &a, const ex &b, const ex &x, bool check_args)
483 throw(std::overflow_error("prem: division by zero"));
484 if (is_exactly_a<numeric>(a)) {
485 if (is_exactly_a<numeric>(b))
490 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
491 throw(std::invalid_argument("prem: arguments must be polynomials over the rationals"));
493 // Polynomial long division
496 int rdeg = r.degree(x);
497 int bdeg = eb.degree(x);
500 blcoeff = eb.coeff(x, bdeg);
504 eb -= blcoeff * power(x, bdeg);
508 int delta = rdeg - bdeg + 1, i = 0;
509 while (rdeg >= bdeg && !r.is_zero()) {
510 ex rlcoeff = r.coeff(x, rdeg);
511 ex term = (power(x, rdeg - bdeg) * eb * rlcoeff).expand();
515 r -= rlcoeff * power(x, rdeg);
516 r = (blcoeff * r).expand() - term;
520 return power(blcoeff, delta - i) * r;
524 /** Sparse pseudo-remainder of polynomials a(x) and b(x) in Q[x].
526 * @param a first polynomial in x (dividend)
527 * @param b second polynomial in x (divisor)
528 * @param x a and b are polynomials in x
529 * @param check_args check whether a and b are polynomials with rational
530 * coefficients (defaults to "true")
531 * @return sparse pseudo-remainder of a(x) and b(x) in Q[x] */
532 ex sprem(const ex &a, const ex &b, const ex &x, bool check_args)
535 throw(std::overflow_error("prem: division by zero"));
536 if (is_exactly_a<numeric>(a)) {
537 if (is_exactly_a<numeric>(b))
542 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
543 throw(std::invalid_argument("prem: arguments must be polynomials over the rationals"));
545 // Polynomial long division
548 int rdeg = r.degree(x);
549 int bdeg = eb.degree(x);
552 blcoeff = eb.coeff(x, bdeg);
556 eb -= blcoeff * power(x, bdeg);
560 while (rdeg >= bdeg && !r.is_zero()) {
561 ex rlcoeff = r.coeff(x, rdeg);
562 ex term = (power(x, rdeg - bdeg) * eb * rlcoeff).expand();
566 r -= rlcoeff * power(x, rdeg);
567 r = (blcoeff * r).expand() - term;
574 /** Exact polynomial division of a(X) by b(X) in Q[X].
576 * @param a first multivariate polynomial (dividend)
577 * @param b second multivariate polynomial (divisor)
578 * @param q quotient (returned)
579 * @param check_args check whether a and b are polynomials with rational
580 * coefficients (defaults to "true")
581 * @return "true" when exact division succeeds (quotient returned in q),
582 * "false" otherwise (q left untouched) */
583 bool divide(const ex &a, const ex &b, ex &q, bool check_args)
586 throw(std::overflow_error("divide: division by zero"));
591 if (is_exactly_a<numeric>(b)) {
594 } else if (is_exactly_a<numeric>(a))
602 if (check_args && (!a.info(info_flags::rational_polynomial) ||
603 !b.info(info_flags::rational_polynomial)))
604 throw(std::invalid_argument("divide: arguments must be polynomials over the rationals"));
608 if (!get_first_symbol(a, x) && !get_first_symbol(b, x))
609 throw(std::invalid_argument("invalid expression in divide()"));
611 // Try to avoid expanding partially factored expressions.
612 if (is_exactly_a<mul>(b)) {
613 // Divide sequentially by each term
614 ex rem_new, rem_old = a;
615 for (size_t i=0; i < b.nops(); i++) {
616 if (! divide(rem_old, b.op(i), rem_new, false))
622 } else if (is_exactly_a<power>(b)) {
623 const ex& bb(b.op(0));
624 int exp_b = ex_to<numeric>(b.op(1)).to_int();
625 ex rem_new, rem_old = a;
626 for (int i=exp_b; i>0; i--) {
627 if (! divide(rem_old, bb, rem_new, false))
635 if (is_exactly_a<mul>(a)) {
636 // Divide sequentially each term. If some term in a is divisible
637 // by b we are done... and if not, we can't really say anything.
640 bool divisible_p = false;
641 for (i=0; i < a.nops(); ++i) {
642 if (divide(a.op(i), b, rem_i, false)) {
649 resv.reserve(a.nops());
650 for (size_t j=0; j < a.nops(); j++) {
652 resv.push_back(rem_i);
654 resv.push_back(a.op(j));
656 q = dynallocate<mul>(resv);
659 } else if (is_exactly_a<power>(a)) {
660 // The base itself might be divisible by b, in that case we don't
662 const ex& ab(a.op(0));
663 int a_exp = ex_to<numeric>(a.op(1)).to_int();
665 if (divide(ab, b, rem_i, false)) {
666 q = rem_i*power(ab, a_exp - 1);
669 // code below is commented-out because it leads to a significant slowdown
670 // for (int i=2; i < a_exp; i++) {
671 // if (divide(power(ab, i), b, rem_i, false)) {
672 // q = rem_i*power(ab, a_exp - i);
675 // } // ... so we *really* need to expand expression.
678 // Polynomial long division (recursive)
684 int bdeg = b.degree(x);
685 int rdeg = r.degree(x);
686 ex blcoeff = b.expand().coeff(x, bdeg);
687 bool blcoeff_is_numeric = is_exactly_a<numeric>(blcoeff);
688 exvector v; v.reserve(std::max(rdeg - bdeg + 1, 0));
689 while (rdeg >= bdeg) {
690 ex term, rcoeff = r.coeff(x, rdeg);
691 if (blcoeff_is_numeric)
692 term = rcoeff / blcoeff;
694 if (!divide(rcoeff, blcoeff, term, false))
696 term *= power(x, rdeg - bdeg);
698 r -= (term * b).expand();
700 q = dynallocate<add>(v);
714 typedef std::pair<ex, ex> ex2;
715 typedef std::pair<ex, bool> exbool;
718 bool operator() (const ex2 &p, const ex2 &q) const
720 int cmp = p.first.compare(q.first);
721 return ((cmp<0) || (!(cmp>0) && p.second.compare(q.second)<0));
725 typedef std::map<ex2, exbool, ex2_less> ex2_exbool_remember;
729 /** Exact polynomial division of a(X) by b(X) in Z[X].
730 * This functions works like divide() but the input and output polynomials are
731 * in Z[X] instead of Q[X] (i.e. they have integer coefficients). Unlike
732 * divide(), it doesn't check whether the input polynomials really are integer
733 * polynomials, so be careful of what you pass in. Also, you have to run
734 * get_symbol_stats() over the input polynomials before calling this function
735 * and pass an iterator to the first element of the sym_desc vector. This
736 * function is used internally by the heur_gcd().
738 * @param a first multivariate polynomial (dividend)
739 * @param b second multivariate polynomial (divisor)
740 * @param q quotient (returned)
741 * @param var iterator to first element of vector of sym_desc structs
742 * @return "true" when exact division succeeds (the quotient is returned in
743 * q), "false" otherwise.
744 * @see get_symbol_stats, heur_gcd */
745 static bool divide_in_z(const ex &a, const ex &b, ex &q, sym_desc_vec::const_iterator var)
749 throw(std::overflow_error("divide_in_z: division by zero"));
750 if (b.is_equal(_ex1)) {
754 if (is_exactly_a<numeric>(a)) {
755 if (is_exactly_a<numeric>(b)) {
757 return q.info(info_flags::integer);
770 static ex2_exbool_remember dr_remember;
771 ex2_exbool_remember::const_iterator remembered = dr_remember.find(ex2(a, b));
772 if (remembered != dr_remember.end()) {
773 q = remembered->second.first;
774 return remembered->second.second;
778 if (is_exactly_a<power>(b)) {
779 const ex& bb(b.op(0));
781 int exp_b = ex_to<numeric>(b.op(1)).to_int();
782 for (int i=exp_b; i>0; i--) {
783 if (!divide_in_z(qbar, bb, q, var))
790 if (is_exactly_a<mul>(b)) {
792 for (const auto & it : b) {
793 sym_desc_vec sym_stats;
794 get_symbol_stats(a, it, sym_stats);
795 if (!divide_in_z(qbar, it, q, sym_stats.begin()))
804 const ex &x = var->sym;
807 int adeg = a.degree(x), bdeg = b.degree(x);
811 #if USE_TRIAL_DIVISION
813 // Trial division with polynomial interpolation
816 // Compute values at evaluation points 0..adeg
817 vector<numeric> alpha; alpha.reserve(adeg + 1);
818 exvector u; u.reserve(adeg + 1);
819 numeric point = *_num0_p;
821 for (i=0; i<=adeg; i++) {
822 ex bs = b.subs(x == point, subs_options::no_pattern);
823 while (bs.is_zero()) {
825 bs = b.subs(x == point, subs_options::no_pattern);
827 if (!divide_in_z(a.subs(x == point, subs_options::no_pattern), bs, c, var+1))
829 alpha.push_back(point);
835 vector<numeric> rcp; rcp.reserve(adeg + 1);
836 rcp.push_back(*_num0_p);
837 for (k=1; k<=adeg; k++) {
838 numeric product = alpha[k] - alpha[0];
840 product *= alpha[k] - alpha[i];
841 rcp.push_back(product.inverse());
844 // Compute Newton coefficients
845 exvector v; v.reserve(adeg + 1);
847 for (k=1; k<=adeg; k++) {
849 for (i=k-2; i>=0; i--)
850 temp = temp * (alpha[k] - alpha[i]) + v[i];
851 v.push_back((u[k] - temp) * rcp[k]);
854 // Convert from Newton form to standard form
856 for (k=adeg-1; k>=0; k--)
857 c = c * (x - alpha[k]) + v[k];
859 if (c.degree(x) == (adeg - bdeg)) {
867 // Polynomial long division (recursive)
873 ex blcoeff = eb.coeff(x, bdeg);
874 exvector v; v.reserve(std::max(rdeg - bdeg + 1, 0));
875 while (rdeg >= bdeg) {
876 ex term, rcoeff = r.coeff(x, rdeg);
877 if (!divide_in_z(rcoeff, blcoeff, term, var+1))
879 term = (term * power(x, rdeg - bdeg)).expand();
881 r -= (term * eb).expand();
883 q = dynallocate<add>(v);
885 dr_remember[ex2(a, b)] = exbool(q, true);
892 dr_remember[ex2(a, b)] = exbool(q, false);
901 * Separation of unit part, content part and primitive part of polynomials
904 /** Compute unit part (= sign of leading coefficient) of a multivariate
905 * polynomial in Q[x]. The product of unit part, content part, and primitive
906 * part is the polynomial itself.
908 * @param x main variable
910 * @see ex::content, ex::primpart, ex::unitcontprim */
911 ex ex::unit(const ex &x) const
913 ex c = expand().lcoeff(x);
914 if (is_exactly_a<numeric>(c))
915 return c.info(info_flags::negative) ?_ex_1 : _ex1;
918 if (get_first_symbol(c, y))
921 throw(std::invalid_argument("invalid expression in unit()"));
926 /** Compute content part (= unit normal GCD of all coefficients) of a
927 * multivariate polynomial in Q[x]. The product of unit part, content part,
928 * and primitive part is the polynomial itself.
930 * @param x main variable
931 * @return content part
932 * @see ex::unit, ex::primpart, ex::unitcontprim */
933 ex ex::content(const ex &x) const
935 if (is_exactly_a<numeric>(*this))
936 return info(info_flags::negative) ? -*this : *this;
942 // First, divide out the integer content (which we can calculate very efficiently).
943 // If the leading coefficient of the quotient is an integer, we are done.
944 ex c = e.integer_content();
946 int deg = r.degree(x);
947 ex lcoeff = r.coeff(x, deg);
948 if (lcoeff.info(info_flags::integer))
951 // GCD of all coefficients
952 int ldeg = r.ldegree(x);
954 return lcoeff * c / lcoeff.unit(x);
956 for (int i=ldeg; i<=deg; i++)
957 cont = gcd(r.coeff(x, i), cont, nullptr, nullptr, false);
962 /** Compute primitive part of a multivariate polynomial in Q[x]. The result
963 * will be a unit-normal polynomial with a content part of 1. The product
964 * of unit part, content part, and primitive part is the polynomial itself.
966 * @param x main variable
967 * @return primitive part
968 * @see ex::unit, ex::content, ex::unitcontprim */
969 ex ex::primpart(const ex &x) const
971 // We need to compute the unit and content anyway, so call unitcontprim()
973 unitcontprim(x, u, c, p);
978 /** Compute primitive part of a multivariate polynomial in Q[x] when the
979 * content part is already known. This function is faster in computing the
980 * primitive part than the previous function.
982 * @param x main variable
983 * @param c previously computed content part
984 * @return primitive part */
985 ex ex::primpart(const ex &x, const ex &c) const
987 if (is_zero() || c.is_zero())
989 if (is_exactly_a<numeric>(*this))
992 // Divide by unit and content to get primitive part
994 if (is_exactly_a<numeric>(c))
995 return *this / (c * u);
997 return quo(*this, c * u, x, false);
1001 /** Compute unit part, content part, and primitive part of a multivariate
1002 * polynomial in Q[x]. The product of the three parts is the polynomial
1005 * @param x main variable
1006 * @param u unit part (returned)
1007 * @param c content part (returned)
1008 * @param p primitive part (returned)
1009 * @see ex::unit, ex::content, ex::primpart */
1010 void ex::unitcontprim(const ex &x, ex &u, ex &c, ex &p) const
1012 // Quick check for zero (avoid expanding)
1019 // Special case: input is a number
1020 if (is_exactly_a<numeric>(*this)) {
1021 if (info(info_flags::negative)) {
1023 c = abs(ex_to<numeric>(*this));
1032 // Expand input polynomial
1040 // Compute unit and content
1044 // Divide by unit and content to get primitive part
1049 if (is_exactly_a<numeric>(c))
1050 p = *this / (c * u);
1052 p = quo(e, c * u, x, false);
1057 * GCD of multivariate polynomials
1060 /** Compute GCD of multivariate polynomials using the subresultant PRS
1061 * algorithm. This function is used internally by gcd().
1063 * @param a first multivariate polynomial
1064 * @param b second multivariate polynomial
1065 * @param var iterator to first element of vector of sym_desc structs
1066 * @return the GCD as a new expression
1069 static ex sr_gcd(const ex &a, const ex &b, sym_desc_vec::const_iterator var)
1075 // The first symbol is our main variable
1076 const ex &x = var->sym;
1078 // Sort c and d so that c has higher degree
1080 int adeg = a.degree(x), bdeg = b.degree(x);
1094 // Remove content from c and d, to be attached to GCD later
1095 ex cont_c = c.content(x);
1096 ex cont_d = d.content(x);
1097 ex gamma = gcd(cont_c, cont_d, nullptr, nullptr, false);
1100 c = c.primpart(x, cont_c);
1101 d = d.primpart(x, cont_d);
1103 // First element of subresultant sequence
1104 ex r = _ex0, ri = _ex1, psi = _ex1;
1105 int delta = cdeg - ddeg;
1109 // Calculate polynomial pseudo-remainder
1110 r = prem(c, d, x, false);
1112 return gamma * d.primpart(x);
1116 if (!divide_in_z(r, ri * pow(psi, delta), d, var))
1117 throw(std::runtime_error("invalid expression in sr_gcd(), division failed"));
1120 if (is_exactly_a<numeric>(r))
1123 return gamma * r.primpart(x);
1126 // Next element of subresultant sequence
1127 ri = c.expand().lcoeff(x);
1131 divide_in_z(pow(ri, delta), pow(psi, delta-1), psi, var+1);
1132 delta = cdeg - ddeg;
1137 /** Return maximum (absolute value) coefficient of a polynomial.
1138 * This function is used internally by heur_gcd().
1140 * @return maximum coefficient
1142 numeric ex::max_coefficient() const
1144 return bp->max_coefficient();
1147 /** Implementation ex::max_coefficient().
1149 numeric basic::max_coefficient() const
1154 numeric numeric::max_coefficient() const
1159 numeric add::max_coefficient() const
1161 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
1162 numeric cur_max = abs(ex_to<numeric>(overall_coeff));
1163 for (auto & it : seq) {
1165 GINAC_ASSERT(!is_exactly_a<numeric>(it.rest));
1166 a = abs(ex_to<numeric>(it.coeff));
1173 numeric mul::max_coefficient() const
1175 #ifdef DO_GINAC_ASSERT
1176 for (auto & it : seq) {
1177 GINAC_ASSERT(!is_exactly_a<numeric>(recombine_pair_to_ex(it)));
1179 #endif // def DO_GINAC_ASSERT
1180 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
1181 return abs(ex_to<numeric>(overall_coeff));
1185 /** Apply symmetric modular homomorphism to an expanded multivariate
1186 * polynomial. This function is usually used internally by heur_gcd().
1189 * @return mapped polynomial
1191 ex basic::smod(const numeric &xi) const
1196 ex numeric::smod(const numeric &xi) const
1198 return GiNaC::smod(*this, xi);
1201 ex add::smod(const numeric &xi) const
1204 newseq.reserve(seq.size()+1);
1205 for (auto & it : seq) {
1206 GINAC_ASSERT(!is_exactly_a<numeric>(it.rest));
1207 numeric coeff = GiNaC::smod(ex_to<numeric>(it.coeff), xi);
1208 if (!coeff.is_zero())
1209 newseq.push_back(expair(it.rest, coeff));
1211 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
1212 numeric coeff = GiNaC::smod(ex_to<numeric>(overall_coeff), xi);
1213 return dynallocate<add>(std::move(newseq), coeff);
1216 ex mul::smod(const numeric &xi) const
1218 #ifdef DO_GINAC_ASSERT
1219 for (auto & it : seq) {
1220 GINAC_ASSERT(!is_exactly_a<numeric>(recombine_pair_to_ex(it)));
1222 #endif // def DO_GINAC_ASSERT
1223 mul & mulcopy = dynallocate<mul>(*this);
1224 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
1225 mulcopy.overall_coeff = GiNaC::smod(ex_to<numeric>(overall_coeff),xi);
1226 mulcopy.clearflag(status_flags::evaluated);
1227 mulcopy.clearflag(status_flags::hash_calculated);
1232 /** xi-adic polynomial interpolation */
1233 static ex interpolate(const ex &gamma, const numeric &xi, const ex &x, int degree_hint = 1)
1235 exvector g; g.reserve(degree_hint);
1237 numeric rxi = xi.inverse();
1238 for (int i=0; !e.is_zero(); i++) {
1240 g.push_back(gi * power(x, i));
1243 return dynallocate<add>(g);
1246 /** Exception thrown by heur_gcd() to signal failure. */
1247 class gcdheu_failed {};
1249 /** Compute GCD of multivariate polynomials using the heuristic GCD algorithm.
1250 * get_symbol_stats() must have been called previously with the input
1251 * polynomials and an iterator to the first element of the sym_desc vector
1252 * passed in. This function is used internally by gcd().
1254 * @param a first integer multivariate polynomial (expanded)
1255 * @param b second integer multivariate polynomial (expanded)
1256 * @param ca cofactor of polynomial a (returned), nullptr to suppress
1257 * calculation of cofactor
1258 * @param cb cofactor of polynomial b (returned), nullptr to suppress
1259 * calculation of cofactor
1260 * @param var iterator to first element of vector of sym_desc structs
1261 * @param res the GCD (returned)
1262 * @return true if GCD was computed, false otherwise.
1264 * @exception gcdheu_failed() */
1265 static bool heur_gcd_z(ex& res, const ex &a, const ex &b, ex *ca, ex *cb,
1266 sym_desc_vec::const_iterator var)
1272 // Algorithm only works for non-vanishing input polynomials
1273 if (a.is_zero() || b.is_zero())
1276 // GCD of two numeric values -> CLN
1277 if (is_exactly_a<numeric>(a) && is_exactly_a<numeric>(b)) {
1278 numeric g = gcd(ex_to<numeric>(a), ex_to<numeric>(b));
1280 *ca = ex_to<numeric>(a) / g;
1282 *cb = ex_to<numeric>(b) / g;
1287 // The first symbol is our main variable
1288 const ex &x = var->sym;
1290 // Remove integer content
1291 numeric gc = gcd(a.integer_content(), b.integer_content());
1292 numeric rgc = gc.inverse();
1295 int maxdeg = std::max(p.degree(x), q.degree(x));
1297 // Find evaluation point
1298 numeric mp = p.max_coefficient();
1299 numeric mq = q.max_coefficient();
1302 xi = mq * (*_num2_p) + (*_num2_p);
1304 xi = mp * (*_num2_p) + (*_num2_p);
1307 for (int t=0; t<6; t++) {
1308 if (xi.int_length() * maxdeg > 100000) {
1309 throw gcdheu_failed();
1312 // Apply evaluation homomorphism and calculate GCD
1315 bool found = heur_gcd_z(gamma,
1316 p.subs(x == xi, subs_options::no_pattern),
1317 q.subs(x == xi, subs_options::no_pattern),
1320 gamma = gamma.expand();
1321 // Reconstruct polynomial from GCD of mapped polynomials
1322 ex g = interpolate(gamma, xi, x, maxdeg);
1324 // Remove integer content
1325 g /= g.integer_content();
1327 // If the calculated polynomial divides both p and q, this is the GCD
1329 if (divide_in_z(p, g, ca ? *ca : dummy, var) && divide_in_z(q, g, cb ? *cb : dummy, var)) {
1336 // Next evaluation point
1337 xi = iquo(xi * isqrt(isqrt(xi)) * numeric(73794), numeric(27011));
1342 /** Compute GCD of multivariate polynomials using the heuristic GCD algorithm.
1343 * get_symbol_stats() must have been called previously with the input
1344 * polynomials and an iterator to the first element of the sym_desc vector
1345 * passed in. This function is used internally by gcd().
1347 * @param a first rational multivariate polynomial (expanded)
1348 * @param b second rational multivariate polynomial (expanded)
1349 * @param ca cofactor of polynomial a (returned), nullptr to suppress
1350 * calculation of cofactor
1351 * @param cb cofactor of polynomial b (returned), nullptr to suppress
1352 * calculation of cofactor
1353 * @param var iterator to first element of vector of sym_desc structs
1354 * @param res the GCD (returned)
1355 * @return true if GCD was computed, false otherwise.
1359 static bool heur_gcd(ex& res, const ex& a, const ex& b, ex *ca, ex *cb,
1360 sym_desc_vec::const_iterator var)
1362 if (a.info(info_flags::integer_polynomial) &&
1363 b.info(info_flags::integer_polynomial)) {
1365 return heur_gcd_z(res, a, b, ca, cb, var);
1366 } catch (gcdheu_failed) {
1371 // convert polynomials to Z[X]
1372 const numeric a_lcm = lcm_of_coefficients_denominators(a);
1373 const numeric ab_lcm = lcmcoeff(b, a_lcm);
1375 const ex ai = a*ab_lcm;
1376 const ex bi = b*ab_lcm;
1377 if (!ai.info(info_flags::integer_polynomial))
1378 throw std::logic_error("heur_gcd: not an integer polynomial [1]");
1380 if (!bi.info(info_flags::integer_polynomial))
1381 throw std::logic_error("heur_gcd: not an integer polynomial [2]");
1385 found = heur_gcd_z(res, ai, bi, ca, cb, var);
1386 } catch (gcdheu_failed) {
1390 // GCD is not unique, it's defined up to a unit (i.e. invertible
1391 // element). If the coefficient ring is a field, every its element is
1392 // invertible, so one can multiply the polynomial GCD with any element
1393 // of the coefficient field. We use this ambiguity to make cofactors
1394 // integer polynomials.
1401 // gcd helper to handle partially factored polynomials (to avoid expanding
1402 // large expressions). At least one of the arguments should be a power.
1403 static ex gcd_pf_pow(const ex& a, const ex& b, ex* ca, ex* cb);
1405 // gcd helper to handle partially factored polynomials (to avoid expanding
1406 // large expressions). At least one of the arguments should be a product.
1407 static ex gcd_pf_mul(const ex& a, const ex& b, ex* ca, ex* cb);
1409 /** Compute GCD (Greatest Common Divisor) of multivariate polynomials a(X)
1410 * and b(X) in Z[X]. Optionally also compute the cofactors of a and b,
1411 * defined by a = ca * gcd(a, b) and b = cb * gcd(a, b).
1413 * @param a first multivariate polynomial
1414 * @param b second multivariate polynomial
1415 * @param ca pointer to expression that will receive the cofactor of a, or nullptr
1416 * @param cb pointer to expression that will receive the cofactor of b, or nullptr
1417 * @param check_args check whether a and b are polynomials with rational
1418 * coefficients (defaults to "true")
1419 * @return the GCD as a new expression */
1420 ex gcd(const ex &a, const ex &b, ex *ca, ex *cb, bool check_args, unsigned options)
1426 // GCD of numerics -> CLN
1427 if (is_exactly_a<numeric>(a) && is_exactly_a<numeric>(b)) {
1428 numeric g = gcd(ex_to<numeric>(a), ex_to<numeric>(b));
1437 *ca = ex_to<numeric>(a) / g;
1439 *cb = ex_to<numeric>(b) / g;
1446 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial))) {
1447 throw(std::invalid_argument("gcd: arguments must be polynomials over the rationals"));
1450 // Partially factored cases (to avoid expanding large expressions)
1451 if (!(options & gcd_options::no_part_factored)) {
1452 if (is_exactly_a<mul>(a) || is_exactly_a<mul>(b))
1453 return gcd_pf_mul(a, b, ca, cb);
1455 if (is_exactly_a<power>(a) || is_exactly_a<power>(b))
1456 return gcd_pf_pow(a, b, ca, cb);
1460 // Some trivial cases
1461 ex aex = a.expand(), bex = b.expand();
1462 if (aex.is_zero()) {
1469 if (bex.is_zero()) {
1476 if (aex.is_equal(_ex1) || bex.is_equal(_ex1)) {
1484 if (a.is_equal(b)) {
1493 if (is_a<symbol>(aex)) {
1494 if (! bex.subs(aex==_ex0, subs_options::no_pattern).is_zero()) {
1503 if (is_a<symbol>(bex)) {
1504 if (! aex.subs(bex==_ex0, subs_options::no_pattern).is_zero()) {
1513 if (is_exactly_a<numeric>(aex)) {
1514 numeric bcont = bex.integer_content();
1515 numeric g = gcd(ex_to<numeric>(aex), bcont);
1517 *ca = ex_to<numeric>(aex)/g;
1523 if (is_exactly_a<numeric>(bex)) {
1524 numeric acont = aex.integer_content();
1525 numeric g = gcd(ex_to<numeric>(bex), acont);
1529 *cb = ex_to<numeric>(bex)/g;
1533 // Gather symbol statistics
1534 sym_desc_vec sym_stats;
1535 get_symbol_stats(a, b, sym_stats);
1537 // The symbol with least degree which is contained in both polynomials
1538 // is our main variable
1539 sym_desc_vec::iterator vari = sym_stats.begin();
1540 while ((vari != sym_stats.end()) &&
1541 (((vari->ldeg_b == 0) && (vari->deg_b == 0)) ||
1542 ((vari->ldeg_a == 0) && (vari->deg_a == 0))))
1545 // No common symbols at all, just return 1:
1546 if (vari == sym_stats.end()) {
1547 // N.B: keep cofactors factored
1554 // move symbols which contained only in one of the polynomials
1556 rotate(sym_stats.begin(), vari, sym_stats.end());
1558 sym_desc_vec::const_iterator var = sym_stats.begin();
1559 const ex &x = var->sym;
1561 // Cancel trivial common factor
1562 int ldeg_a = var->ldeg_a;
1563 int ldeg_b = var->ldeg_b;
1564 int min_ldeg = std::min(ldeg_a,ldeg_b);
1566 ex common = power(x, min_ldeg);
1567 return gcd((aex / common).expand(), (bex / common).expand(), ca, cb, false) * common;
1570 // Try to eliminate variables
1571 if (var->deg_a == 0 && var->deg_b != 0 ) {
1572 ex bex_u, bex_c, bex_p;
1573 bex.unitcontprim(x, bex_u, bex_c, bex_p);
1574 ex g = gcd(aex, bex_c, ca, cb, false);
1576 *cb *= bex_u * bex_p;
1578 } else if (var->deg_b == 0 && var->deg_a != 0) {
1579 ex aex_u, aex_c, aex_p;
1580 aex.unitcontprim(x, aex_u, aex_c, aex_p);
1581 ex g = gcd(aex_c, bex, ca, cb, false);
1583 *ca *= aex_u * aex_p;
1587 // Try heuristic algorithm first, fall back to PRS if that failed
1589 if (!(options & gcd_options::no_heur_gcd)) {
1590 bool found = heur_gcd(g, aex, bex, ca, cb, var);
1592 // heur_gcd have already computed cofactors...
1593 if (g.is_equal(_ex1)) {
1594 // ... but we want to keep them factored if possible.
1608 if (options & gcd_options::use_sr_gcd) {
1609 g = sr_gcd(aex, bex, var);
1612 for (std::size_t n = sym_stats.size(); n-- != 0; )
1613 vars.push_back(sym_stats[n].sym);
1614 g = chinrem_gcd(aex, bex, vars);
1617 if (g.is_equal(_ex1)) {
1618 // Keep cofactors factored if possible
1625 divide(aex, g, *ca, false);
1627 divide(bex, g, *cb, false);
1632 // gcd helper to handle partially factored polynomials (to avoid expanding
1633 // large expressions). Both arguments should be powers.
1634 static ex gcd_pf_pow_pow(const ex& a, const ex& b, ex* ca, ex* cb)
1637 const ex& exp_a = a.op(1);
1639 const ex& exp_b = b.op(1);
1641 // a = p^n, b = p^m, gcd = p^min(n, m)
1642 if (p.is_equal(pb)) {
1643 if (exp_a < exp_b) {
1647 *cb = power(p, exp_b - exp_a);
1648 return power(p, exp_a);
1651 *ca = power(p, exp_a - exp_b);
1654 return power(p, exp_b);
1659 ex p_gcd = gcd(p, pb, &p_co, &pb_co, false);
1660 // a(x) = p(x)^n, b(x) = p_b(x)^m, gcd (p, p_b) = 1 ==> gcd(a,b) = 1
1661 if (p_gcd.is_equal(_ex1)) {
1667 // XXX: do I need to check for p_gcd = -1?
1670 // there are common factors:
1671 // a(x) = g(x)^n A(x)^n, b(x) = g(x)^m B(x)^m ==>
1672 // gcd(a, b) = g(x)^n gcd(A(x)^n, g(x)^(n-m) B(x)^m
1673 if (exp_a < exp_b) {
1674 ex pg = gcd(power(p_co, exp_a), power(p_gcd, exp_b-exp_a)*power(pb_co, exp_b), ca, cb, false);
1675 return power(p_gcd, exp_a)*pg;
1677 ex pg = gcd(power(p_gcd, exp_a - exp_b)*power(p_co, exp_a), power(pb_co, exp_b), ca, cb, false);
1678 return power(p_gcd, exp_b)*pg;
1682 static ex gcd_pf_pow(const ex& a, const ex& b, ex* ca, ex* cb)
1684 if (is_exactly_a<power>(a) && is_exactly_a<power>(b))
1685 return gcd_pf_pow_pow(a, b, ca, cb);
1687 if (is_exactly_a<power>(b) && (! is_exactly_a<power>(a)))
1688 return gcd_pf_pow(b, a, cb, ca);
1690 GINAC_ASSERT(is_exactly_a<power>(a));
1693 const ex& exp_a = a.op(1);
1694 if (p.is_equal(b)) {
1695 // a = p^n, b = p, gcd = p
1697 *ca = power(p, a.op(1) - 1);
1704 ex p_gcd = gcd(p, b, &p_co, &bpart_co, false);
1706 // a(x) = p(x)^n, gcd(p, b) = 1 ==> gcd(a, b) = 1
1707 if (p_gcd.is_equal(_ex1)) {
1714 // 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))
1715 ex rg = gcd(power(p_gcd, exp_a-1)*power(p_co, exp_a), bpart_co, ca, cb, false);
1719 static ex gcd_pf_mul(const ex& a, const ex& b, ex* ca, ex* cb)
1721 if (is_exactly_a<mul>(a) && is_exactly_a<mul>(b)
1722 && (b.nops() > a.nops()))
1723 return gcd_pf_mul(b, a, cb, ca);
1725 if (is_exactly_a<mul>(b) && (!is_exactly_a<mul>(a)))
1726 return gcd_pf_mul(b, a, cb, ca);
1728 GINAC_ASSERT(is_exactly_a<mul>(a));
1729 size_t num = a.nops();
1730 exvector g; g.reserve(num);
1731 exvector acc_ca; acc_ca.reserve(num);
1733 for (size_t i=0; i<num; i++) {
1734 ex part_ca, part_cb;
1735 g.push_back(gcd(a.op(i), part_b, &part_ca, &part_cb, false));
1736 acc_ca.push_back(part_ca);
1740 *ca = dynallocate<mul>(acc_ca);
1743 return dynallocate<mul>(g);
1746 /** Compute LCM (Least Common Multiple) of multivariate polynomials in Z[X].
1748 * @param a first multivariate polynomial
1749 * @param b second multivariate polynomial
1750 * @param check_args check whether a and b are polynomials with rational
1751 * coefficients (defaults to "true")
1752 * @return the LCM as a new expression */
1753 ex lcm(const ex &a, const ex &b, bool check_args)
1755 if (is_exactly_a<numeric>(a) && is_exactly_a<numeric>(b))
1756 return lcm(ex_to<numeric>(a), ex_to<numeric>(b));
1757 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
1758 throw(std::invalid_argument("lcm: arguments must be polynomials over the rationals"));
1761 ex g = gcd(a, b, &ca, &cb, false);
1767 * Square-free factorization
1770 /** Compute square-free factorization of multivariate polynomial a(x) using
1771 * Yun's algorithm. Used internally by sqrfree().
1773 * @param a multivariate polynomial over Z[X], treated here as univariate
1775 * @param x variable to factor in
1776 * @return vector of factors sorted in ascending degree */
1777 static exvector sqrfree_yun(const ex &a, const symbol &x)
1783 if (g.is_equal(_ex1)) {
1794 } while (!z.is_zero());
1799 /** Compute a square-free factorization of a multivariate polynomial in Q[X].
1801 * @param a multivariate polynomial over Q[X]
1802 * @param l lst of variables to factor in, may be left empty for autodetection
1803 * @return a square-free factorization of \p a.
1806 * A polynomial \f$p(X) \in C[X]\f$ is said <EM>square-free</EM>
1807 * if, whenever any two polynomials \f$q(X)\f$ and \f$r(X)\f$
1810 * p(X) = q(X)^2 r(X),
1812 * we have \f$q(X) \in C\f$.
1813 * This means that \f$p(X)\f$ has no repeated factors, apart
1814 * eventually from constants.
1815 * Given a polynomial \f$p(X) \in C[X]\f$, we say that the
1818 * p(X) = b \cdot p_1(X)^{a_1} \cdot p_2(X)^{a_2} \cdots p_r(X)^{a_r}
1820 * is a <EM>square-free factorization</EM> of \f$p(X)\f$ if the
1821 * following conditions hold:
1822 * -# \f$b \in C\f$ and \f$b \neq 0\f$;
1823 * -# \f$a_i\f$ is a positive integer for \f$i = 1, \ldots, r\f$;
1824 * -# the degree of the polynomial \f$p_i\f$ is strictly positive
1825 * for \f$i = 1, \ldots, r\f$;
1826 * -# the polynomial \f$\Pi_{i=1}^r p_i(X)\f$ is square-free.
1828 * Square-free factorizations need not be unique. For example, if
1829 * \f$a_i\f$ is even, we could change the polynomial \f$p_i(X)\f$
1830 * into \f$-p_i(X)\f$.
1831 * Observe also that the factors \f$p_i(X)\f$ need not be irreducible
1834 ex sqrfree(const ex &a, const lst &l)
1836 if (is_exactly_a<numeric>(a) || // algorithm does not trap a==0
1837 is_a<symbol>(a)) // shortcut
1840 // If no lst of variables to factorize in was specified we have to
1841 // invent one now. Maybe one can optimize here by reversing the order
1842 // or so, I don't know.
1846 get_symbol_stats(a, _ex0, sdv);
1847 for (auto & it : sdv)
1848 args.append(it.sym);
1853 // Find the symbol to factor in at this stage
1854 if (!is_a<symbol>(args.op(0)))
1855 throw (std::runtime_error("sqrfree(): invalid factorization variable"));
1856 const symbol &x = ex_to<symbol>(args.op(0));
1858 // convert the argument from something in Q[X] to something in Z[X]
1859 const numeric lcm = lcm_of_coefficients_denominators(a);
1860 const ex tmp = multiply_lcm(a,lcm);
1863 exvector factors = sqrfree_yun(tmp, x);
1865 // construct the next list of symbols with the first element popped
1867 newargs.remove_first();
1869 // recurse down the factors in remaining variables
1870 if (newargs.nops()>0) {
1871 for (auto & it : factors)
1872 it = sqrfree(it, newargs);
1875 // Done with recursion, now construct the final result
1878 for (auto & it : factors)
1879 result *= power(it, p++);
1881 // Yun's algorithm does not account for constant factors. (For univariate
1882 // polynomials it works only in the monic case.) We can correct this by
1883 // inserting what has been lost back into the result. For completeness
1884 // we'll also have to recurse down that factor in the remaining variables.
1885 if (newargs.nops()>0)
1886 result *= sqrfree(quo(tmp, result, x), newargs);
1888 result *= quo(tmp, result, x);
1890 // Put in the rational overall factor again and return
1891 return result * lcm.inverse();
1895 /** Compute square-free partial fraction decomposition of rational function
1898 * @param a rational function over Z[x], treated as univariate polynomial
1900 * @param x variable to factor in
1901 * @return decomposed rational function */
1902 ex sqrfree_parfrac(const ex & a, const symbol & x)
1904 // Find numerator and denominator
1905 ex nd = numer_denom(a);
1906 ex numer = nd.op(0), denom = nd.op(1);
1907 //clog << "numer = " << numer << ", denom = " << denom << endl;
1909 // Convert N(x)/D(x) -> Q(x) + R(x)/D(x), so degree(R) < degree(D)
1910 ex red_poly = quo(numer, denom, x), red_numer = rem(numer, denom, x).expand();
1911 //clog << "red_poly = " << red_poly << ", red_numer = " << red_numer << endl;
1913 // Factorize denominator and compute cofactors
1914 exvector yun = sqrfree_yun(denom, x);
1915 //clog << "yun factors: " << exprseq(yun) << endl;
1916 size_t num_yun = yun.size();
1917 exvector factor; factor.reserve(num_yun);
1918 exvector cofac; cofac.reserve(num_yun);
1919 for (size_t i=0; i<num_yun; i++) {
1920 if (!yun[i].is_equal(_ex1)) {
1921 for (size_t j=0; j<=i; j++) {
1922 factor.push_back(pow(yun[i], j+1));
1924 for (size_t k=0; k<num_yun; k++) {
1926 prod *= pow(yun[k], i-j);
1928 prod *= pow(yun[k], k+1);
1930 cofac.push_back(prod.expand());
1934 size_t num_factors = factor.size();
1935 //clog << "factors : " << exprseq(factor) << endl;
1936 //clog << "cofactors: " << exprseq(cofac) << endl;
1938 // Construct coefficient matrix for decomposition
1939 int max_denom_deg = denom.degree(x);
1940 matrix sys(max_denom_deg + 1, num_factors);
1941 matrix rhs(max_denom_deg + 1, 1);
1942 for (int i=0; i<=max_denom_deg; i++) {
1943 for (size_t j=0; j<num_factors; j++)
1944 sys(i, j) = cofac[j].coeff(x, i);
1945 rhs(i, 0) = red_numer.coeff(x, i);
1947 //clog << "coeffs: " << sys << endl;
1948 //clog << "rhs : " << rhs << endl;
1950 // Solve resulting linear system
1951 matrix vars(num_factors, 1);
1952 for (size_t i=0; i<num_factors; i++)
1953 vars(i, 0) = symbol();
1954 matrix sol = sys.solve(vars, rhs);
1956 // Sum up decomposed fractions
1958 for (size_t i=0; i<num_factors; i++)
1959 sum += sol(i, 0) / factor[i];
1961 return red_poly + sum;
1966 * Normal form of rational functions
1970 * Note: The internal normal() functions (= basic::normal() and overloaded
1971 * functions) all return lists of the form {numerator, denominator}. This
1972 * is to get around mul::eval()'s automatic expansion of numeric coefficients.
1973 * E.g. (a+b)/3 is automatically converted to a/3+b/3 but we want to keep
1974 * the information that (a+b) is the numerator and 3 is the denominator.
1978 /** Create a symbol for replacing the expression "e" (or return a previously
1979 * assigned symbol). The symbol and expression are appended to repl, for
1980 * a later application of subs().
1981 * @see ex::normal */
1982 static ex replace_with_symbol(const ex & e, exmap & repl, exmap & rev_lookup)
1984 // Since the repl contains replaced expressions we should search for them
1985 ex e_replaced = e.subs(repl, subs_options::no_pattern);
1987 // Expression already replaced? Then return the assigned symbol
1988 auto it = rev_lookup.find(e_replaced);
1989 if (it != rev_lookup.end())
1992 // Otherwise create new symbol and add to list, taking care that the
1993 // replacement expression doesn't itself contain symbols from repl,
1994 // because subs() is not recursive
1995 ex es = dynallocate<symbol>();
1996 repl.insert(std::make_pair(es, e_replaced));
1997 rev_lookup.insert(std::make_pair(e_replaced, es));
2001 /** Create a symbol for replacing the expression "e" (or return a previously
2002 * assigned symbol). The symbol and expression are appended to repl, and the
2003 * symbol is returned.
2004 * @see basic::to_rational
2005 * @see basic::to_polynomial */
2006 static ex replace_with_symbol(const ex & e, exmap & repl)
2008 // Since the repl contains replaced expressions we should search for them
2009 ex e_replaced = e.subs(repl, subs_options::no_pattern);
2011 // Expression already replaced? Then return the assigned symbol
2012 for (auto & it : repl)
2013 if (it.second.is_equal(e_replaced))
2016 // Otherwise create new symbol and add to list, taking care that the
2017 // replacement expression doesn't itself contain symbols from repl,
2018 // because subs() is not recursive
2019 ex es = dynallocate<symbol>();
2020 repl.insert(std::make_pair(es, e_replaced));
2025 /** Function object to be applied by basic::normal(). */
2026 struct normal_map_function : public map_function {
2028 normal_map_function(int l) : level(l) {}
2029 ex operator()(const ex & e) override { return normal(e, level); }
2032 /** Default implementation of ex::normal(). It normalizes the children and
2033 * replaces the object with a temporary symbol.
2034 * @see ex::normal */
2035 ex basic::normal(exmap & repl, exmap & rev_lookup, int level) const
2038 return dynallocate<lst>({replace_with_symbol(*this, repl, rev_lookup), _ex1});
2041 return dynallocate<lst>({replace_with_symbol(*this, repl, rev_lookup), _ex1});
2042 else if (level == -max_recursion_level)
2043 throw(std::runtime_error("max recursion level reached"));
2045 normal_map_function map_normal(level - 1);
2046 return dynallocate<lst>({replace_with_symbol(map(map_normal), repl, rev_lookup), _ex1});
2052 /** Implementation of ex::normal() for symbols. This returns the unmodified symbol.
2053 * @see ex::normal */
2054 ex symbol::normal(exmap & repl, exmap & rev_lookup, int level) const
2056 return dynallocate<lst>({*this, _ex1});
2060 /** Implementation of ex::normal() for a numeric. It splits complex numbers
2061 * into re+I*im and replaces I and non-rational real numbers with a temporary
2063 * @see ex::normal */
2064 ex numeric::normal(exmap & repl, exmap & rev_lookup, int level) const
2066 numeric num = numer();
2069 if (num.is_real()) {
2070 if (!num.is_integer())
2071 numex = replace_with_symbol(numex, repl, rev_lookup);
2073 numeric re = num.real(), im = num.imag();
2074 ex re_ex = re.is_rational() ? re : replace_with_symbol(re, repl, rev_lookup);
2075 ex im_ex = im.is_rational() ? im : replace_with_symbol(im, repl, rev_lookup);
2076 numex = re_ex + im_ex * replace_with_symbol(I, repl, rev_lookup);
2079 // Denominator is always a real integer (see numeric::denom())
2080 return dynallocate<lst>({numex, denom()});
2084 /** Fraction cancellation.
2085 * @param n numerator
2086 * @param d denominator
2087 * @return cancelled fraction {n, d} as a list */
2088 static ex frac_cancel(const ex &n, const ex &d)
2092 numeric pre_factor = *_num1_p;
2094 //std::clog << "frac_cancel num = " << num << ", den = " << den << std::endl;
2096 // Handle trivial case where denominator is 1
2097 if (den.is_equal(_ex1))
2098 return dynallocate<lst>({num, den});
2100 // Handle special cases where numerator or denominator is 0
2102 return dynallocate<lst>({num, _ex1});
2103 if (den.expand().is_zero())
2104 throw(std::overflow_error("frac_cancel: division by zero in frac_cancel"));
2106 // Bring numerator and denominator to Z[X] by multiplying with
2107 // LCM of all coefficients' denominators
2108 numeric num_lcm = lcm_of_coefficients_denominators(num);
2109 numeric den_lcm = lcm_of_coefficients_denominators(den);
2110 num = multiply_lcm(num, num_lcm);
2111 den = multiply_lcm(den, den_lcm);
2112 pre_factor = den_lcm / num_lcm;
2114 // Cancel GCD from numerator and denominator
2116 if (gcd(num, den, &cnum, &cden, false) != _ex1) {
2121 // Make denominator unit normal (i.e. coefficient of first symbol
2122 // as defined by get_first_symbol() is made positive)
2123 if (is_exactly_a<numeric>(den)) {
2124 if (ex_to<numeric>(den).is_negative()) {
2130 if (get_first_symbol(den, x)) {
2131 GINAC_ASSERT(is_exactly_a<numeric>(den.unit(x)));
2132 if (ex_to<numeric>(den.unit(x)).is_negative()) {
2139 // Return result as list
2140 //std::clog << " returns num = " << num << ", den = " << den << ", pre_factor = " << pre_factor << std::endl;
2141 return dynallocate<lst>({num * pre_factor.numer(), den * pre_factor.denom()});
2145 /** Implementation of ex::normal() for a sum. It expands terms and performs
2146 * fractional addition.
2147 * @see ex::normal */
2148 ex add::normal(exmap & repl, exmap & rev_lookup, int level) const
2151 return dynallocate<lst>({replace_with_symbol(*this, repl, rev_lookup), _ex1});
2152 else if (level == -max_recursion_level)
2153 throw(std::runtime_error("max recursion level reached"));
2155 // Normalize children and split each one into numerator and denominator
2156 exvector nums, dens;
2157 nums.reserve(seq.size()+1);
2158 dens.reserve(seq.size()+1);
2159 for (auto & it : seq) {
2160 ex n = ex_to<basic>(recombine_pair_to_ex(it)).normal(repl, rev_lookup, level-1);
2161 nums.push_back(n.op(0));
2162 dens.push_back(n.op(1));
2164 ex n = ex_to<numeric>(overall_coeff).normal(repl, rev_lookup, level-1);
2165 nums.push_back(n.op(0));
2166 dens.push_back(n.op(1));
2167 GINAC_ASSERT(nums.size() == dens.size());
2169 // Now, nums is a vector of all numerators and dens is a vector of
2171 //std::clog << "add::normal uses " << nums.size() << " summands:\n";
2173 // Add fractions sequentially
2174 auto num_it = nums.begin(), num_itend = nums.end();
2175 auto den_it = dens.begin(), den_itend = dens.end();
2176 //std::clog << " num = " << *num_it << ", den = " << *den_it << std::endl;
2177 ex num = *num_it++, den = *den_it++;
2178 while (num_it != num_itend) {
2179 //std::clog << " num = " << *num_it << ", den = " << *den_it << std::endl;
2180 ex next_num = *num_it++, next_den = *den_it++;
2182 // Trivially add sequences of fractions with identical denominators
2183 while ((den_it != den_itend) && next_den.is_equal(*den_it)) {
2184 next_num += *num_it;
2188 // Addition of two fractions, taking advantage of the fact that
2189 // the heuristic GCD algorithm computes the cofactors at no extra cost
2190 ex co_den1, co_den2;
2191 ex g = gcd(den, next_den, &co_den1, &co_den2, false);
2192 num = ((num * co_den2) + (next_num * co_den1)).expand();
2193 den *= co_den2; // this is the lcm(den, next_den)
2195 //std::clog << " common denominator = " << den << std::endl;
2197 // Cancel common factors from num/den
2198 return frac_cancel(num, den);
2202 /** Implementation of ex::normal() for a product. It cancels common factors
2204 * @see ex::normal() */
2205 ex mul::normal(exmap & repl, exmap & rev_lookup, int level) const
2208 return dynallocate<lst>({replace_with_symbol(*this, repl, rev_lookup), _ex1});
2209 else if (level == -max_recursion_level)
2210 throw(std::runtime_error("max recursion level reached"));
2212 // Normalize children, separate into numerator and denominator
2213 exvector num; num.reserve(seq.size());
2214 exvector den; den.reserve(seq.size());
2216 for (auto & it : seq) {
2217 n = ex_to<basic>(recombine_pair_to_ex(it)).normal(repl, rev_lookup, level-1);
2218 num.push_back(n.op(0));
2219 den.push_back(n.op(1));
2221 n = ex_to<numeric>(overall_coeff).normal(repl, rev_lookup, level-1);
2222 num.push_back(n.op(0));
2223 den.push_back(n.op(1));
2225 // Perform fraction cancellation
2226 return frac_cancel(dynallocate<mul>(num), dynallocate<mul>(den));
2230 /** Implementation of ex::normal([B) for powers. It normalizes the basis,
2231 * distributes integer exponents to numerator and denominator, and replaces
2232 * non-integer powers by temporary symbols.
2233 * @see ex::normal */
2234 ex power::normal(exmap & repl, exmap & rev_lookup, int level) const
2237 return dynallocate<lst>({replace_with_symbol(*this, repl, rev_lookup), _ex1});
2238 else if (level == -max_recursion_level)
2239 throw(std::runtime_error("max recursion level reached"));
2241 // Normalize basis and exponent (exponent gets reassembled)
2242 ex n_basis = ex_to<basic>(basis).normal(repl, rev_lookup, level-1);
2243 ex n_exponent = ex_to<basic>(exponent).normal(repl, rev_lookup, level-1);
2244 n_exponent = n_exponent.op(0) / n_exponent.op(1);
2246 if (n_exponent.info(info_flags::integer)) {
2248 if (n_exponent.info(info_flags::positive)) {
2250 // (a/b)^n -> {a^n, b^n}
2251 return dynallocate<lst>({power(n_basis.op(0), n_exponent), power(n_basis.op(1), n_exponent)});
2253 } else if (n_exponent.info(info_flags::negative)) {
2255 // (a/b)^-n -> {b^n, a^n}
2256 return dynallocate<lst>({power(n_basis.op(1), -n_exponent), power(n_basis.op(0), -n_exponent)});
2261 if (n_exponent.info(info_flags::positive)) {
2263 // (a/b)^x -> {sym((a/b)^x), 1}
2264 return dynallocate<lst>({replace_with_symbol(power(n_basis.op(0) / n_basis.op(1), n_exponent), repl, rev_lookup), _ex1});
2266 } else if (n_exponent.info(info_flags::negative)) {
2268 if (n_basis.op(1).is_equal(_ex1)) {
2270 // a^-x -> {1, sym(a^x)}
2271 return dynallocate<lst>({_ex1, replace_with_symbol(power(n_basis.op(0), -n_exponent), repl, rev_lookup)});
2275 // (a/b)^-x -> {sym((b/a)^x), 1}
2276 return dynallocate<lst>({replace_with_symbol(power(n_basis.op(1) / n_basis.op(0), -n_exponent), repl, rev_lookup), _ex1});
2281 // (a/b)^x -> {sym((a/b)^x, 1}
2282 return dynallocate<lst>({replace_with_symbol(power(n_basis.op(0) / n_basis.op(1), n_exponent), repl, rev_lookup), _ex1});
2286 /** Implementation of ex::normal() for pseries. It normalizes each coefficient
2287 * and replaces the series by a temporary symbol.
2288 * @see ex::normal */
2289 ex pseries::normal(exmap & repl, exmap & rev_lookup, int level) const
2292 for (auto & it : seq) {
2293 ex restexp = it.rest.normal();
2294 if (!restexp.is_zero())
2295 newseq.push_back(expair(restexp, it.coeff));
2297 ex n = pseries(relational(var,point), std::move(newseq));
2298 return dynallocate<lst>({replace_with_symbol(n, repl, rev_lookup), _ex1});
2302 /** Normalization of rational functions.
2303 * This function converts an expression to its normal form
2304 * "numerator/denominator", where numerator and denominator are (relatively
2305 * prime) polynomials. Any subexpressions which are not rational functions
2306 * (like non-rational numbers, non-integer powers or functions like sin(),
2307 * cos() etc.) are replaced by temporary symbols which are re-substituted by
2308 * the (normalized) subexpressions before normal() returns (this way, any
2309 * expression can be treated as a rational function). normal() is applied
2310 * recursively to arguments of functions etc.
2312 * @param level maximum depth of recursion
2313 * @return normalized expression */
2314 ex ex::normal(int level) const
2316 exmap repl, rev_lookup;
2318 ex e = bp->normal(repl, rev_lookup, level);
2319 GINAC_ASSERT(is_a<lst>(e));
2321 // Re-insert replaced symbols
2323 e = e.subs(repl, subs_options::no_pattern);
2325 // Convert {numerator, denominator} form back to fraction
2326 return e.op(0) / e.op(1);
2329 /** Get numerator of an expression. If the expression is not of the normal
2330 * form "numerator/denominator", it is first converted to this form and
2331 * then the numerator is returned.
2334 * @return numerator */
2335 ex ex::numer() const
2337 exmap repl, rev_lookup;
2339 ex e = bp->normal(repl, rev_lookup, 0);
2340 GINAC_ASSERT(is_a<lst>(e));
2342 // Re-insert replaced symbols
2346 return e.op(0).subs(repl, subs_options::no_pattern);
2349 /** Get denominator of an expression. If the expression is not of the normal
2350 * form "numerator/denominator", it is first converted to this form and
2351 * then the denominator is returned.
2354 * @return denominator */
2355 ex ex::denom() const
2357 exmap repl, rev_lookup;
2359 ex e = bp->normal(repl, rev_lookup, 0);
2360 GINAC_ASSERT(is_a<lst>(e));
2362 // Re-insert replaced symbols
2366 return e.op(1).subs(repl, subs_options::no_pattern);
2369 /** Get numerator and denominator of an expression. If the expression is not
2370 * of the normal form "numerator/denominator", it is first converted to this
2371 * form and then a list [numerator, denominator] is returned.
2374 * @return a list [numerator, denominator] */
2375 ex ex::numer_denom() const
2377 exmap repl, rev_lookup;
2379 ex e = bp->normal(repl, rev_lookup, 0);
2380 GINAC_ASSERT(is_a<lst>(e));
2382 // Re-insert replaced symbols
2386 return e.subs(repl, subs_options::no_pattern);
2390 /** Rationalization of non-rational functions.
2391 * This function converts a general expression to a rational function
2392 * by replacing all non-rational subexpressions (like non-rational numbers,
2393 * non-integer powers or functions like sin(), cos() etc.) to temporary
2394 * symbols. This makes it possible to use functions like gcd() and divide()
2395 * on non-rational functions by applying to_rational() on the arguments,
2396 * calling the desired function and re-substituting the temporary symbols
2397 * in the result. To make the last step possible, all temporary symbols and
2398 * their associated expressions are collected in the map specified by the
2399 * repl parameter, ready to be passed as an argument to ex::subs().
2401 * @param repl collects all temporary symbols and their replacements
2402 * @return rationalized expression */
2403 ex ex::to_rational(exmap & repl) const
2405 return bp->to_rational(repl);
2408 // GiNaC 1.1 compatibility function
2409 ex ex::to_rational(lst & repl_lst) const
2411 // Convert lst to exmap
2413 for (auto & it : repl_lst)
2414 m.insert(std::make_pair(it.op(0), it.op(1)));
2416 ex ret = bp->to_rational(m);
2418 // Convert exmap back to lst
2419 repl_lst.remove_all();
2421 repl_lst.append(it.first == it.second);
2426 ex ex::to_polynomial(exmap & repl) const
2428 return bp->to_polynomial(repl);
2431 // GiNaC 1.1 compatibility function
2432 ex ex::to_polynomial(lst & repl_lst) const
2434 // Convert lst to exmap
2436 for (auto & it : repl_lst)
2437 m.insert(std::make_pair(it.op(0), it.op(1)));
2439 ex ret = bp->to_polynomial(m);
2441 // Convert exmap back to lst
2442 repl_lst.remove_all();
2444 repl_lst.append(it.first == it.second);
2449 /** Default implementation of ex::to_rational(). This replaces the object with
2450 * a temporary symbol. */
2451 ex basic::to_rational(exmap & repl) const
2453 return replace_with_symbol(*this, repl);
2456 ex basic::to_polynomial(exmap & repl) const
2458 return replace_with_symbol(*this, repl);
2462 /** Implementation of ex::to_rational() for symbols. This returns the
2463 * unmodified symbol. */
2464 ex symbol::to_rational(exmap & repl) const
2469 /** Implementation of ex::to_polynomial() for symbols. This returns the
2470 * unmodified symbol. */
2471 ex symbol::to_polynomial(exmap & repl) const
2477 /** Implementation of ex::to_rational() for a numeric. It splits complex
2478 * numbers into re+I*im and replaces I and non-rational real numbers with a
2479 * temporary symbol. */
2480 ex numeric::to_rational(exmap & repl) const
2484 return replace_with_symbol(*this, repl);
2486 numeric re = real();
2487 numeric im = imag();
2488 ex re_ex = re.is_rational() ? re : replace_with_symbol(re, repl);
2489 ex im_ex = im.is_rational() ? im : replace_with_symbol(im, repl);
2490 return re_ex + im_ex * replace_with_symbol(I, repl);
2495 /** Implementation of ex::to_polynomial() for a numeric. It splits complex
2496 * numbers into re+I*im and replaces I and non-integer real numbers with a
2497 * temporary symbol. */
2498 ex numeric::to_polynomial(exmap & repl) const
2502 return replace_with_symbol(*this, repl);
2504 numeric re = real();
2505 numeric im = imag();
2506 ex re_ex = re.is_integer() ? re : replace_with_symbol(re, repl);
2507 ex im_ex = im.is_integer() ? im : replace_with_symbol(im, repl);
2508 return re_ex + im_ex * replace_with_symbol(I, repl);
2514 /** Implementation of ex::to_rational() for powers. It replaces non-integer
2515 * powers by temporary symbols. */
2516 ex power::to_rational(exmap & repl) const
2518 if (exponent.info(info_flags::integer))
2519 return power(basis.to_rational(repl), exponent);
2521 return replace_with_symbol(*this, repl);
2524 /** Implementation of ex::to_polynomial() for powers. It replaces non-posint
2525 * powers by temporary symbols. */
2526 ex power::to_polynomial(exmap & repl) const
2528 if (exponent.info(info_flags::posint))
2529 return power(basis.to_rational(repl), exponent);
2530 else if (exponent.info(info_flags::negint))
2532 ex basis_pref = collect_common_factors(basis);
2533 if (is_exactly_a<mul>(basis_pref) || is_exactly_a<power>(basis_pref)) {
2534 // (A*B)^n will be automagically transformed to A^n*B^n
2535 ex t = power(basis_pref, exponent);
2536 return t.to_polynomial(repl);
2539 return power(replace_with_symbol(power(basis, _ex_1), repl), -exponent);
2542 return replace_with_symbol(*this, repl);
2546 /** Implementation of ex::to_rational() for expairseqs. */
2547 ex expairseq::to_rational(exmap & repl) const
2550 s.reserve(seq.size());
2551 for (auto & it : seq)
2552 s.push_back(split_ex_to_pair(recombine_pair_to_ex(it).to_rational(repl)));
2554 ex oc = overall_coeff.to_rational(repl);
2555 if (oc.info(info_flags::numeric))
2556 return thisexpairseq(std::move(s), overall_coeff);
2558 s.push_back(expair(oc, _ex1));
2559 return thisexpairseq(std::move(s), default_overall_coeff());
2562 /** Implementation of ex::to_polynomial() for expairseqs. */
2563 ex expairseq::to_polynomial(exmap & repl) const
2566 s.reserve(seq.size());
2567 for (auto & it : seq)
2568 s.push_back(split_ex_to_pair(recombine_pair_to_ex(it).to_polynomial(repl)));
2570 ex oc = overall_coeff.to_polynomial(repl);
2571 if (oc.info(info_flags::numeric))
2572 return thisexpairseq(std::move(s), overall_coeff);
2574 s.push_back(expair(oc, _ex1));
2575 return thisexpairseq(std::move(s), default_overall_coeff());
2579 /** Remove the common factor in the terms of a sum 'e' by calculating the GCD,
2580 * and multiply it into the expression 'factor' (which needs to be initialized
2581 * to 1, unless you're accumulating factors). */
2582 static ex find_common_factor(const ex & e, ex & factor, exmap & repl)
2584 if (is_exactly_a<add>(e)) {
2586 size_t num = e.nops();
2587 exvector terms; terms.reserve(num);
2590 // Find the common GCD
2591 for (size_t i=0; i<num; i++) {
2592 ex x = e.op(i).to_polynomial(repl);
2594 if (is_exactly_a<add>(x) || is_exactly_a<mul>(x) || is_a<power>(x)) {
2596 x = find_common_factor(x, f, repl);
2608 if (gc.is_equal(_ex1))
2611 // The GCD is the factor we pull out
2614 // Now divide all terms by the GCD
2615 for (size_t i=0; i<num; i++) {
2618 // Try to avoid divide() because it expands the polynomial
2620 if (is_exactly_a<mul>(t)) {
2621 for (size_t j=0; j<t.nops(); j++) {
2622 if (t.op(j).is_equal(gc)) {
2623 exvector v; v.reserve(t.nops());
2624 for (size_t k=0; k<t.nops(); k++) {
2628 v.push_back(t.op(k));
2630 t = dynallocate<mul>(v);
2640 return dynallocate<add>(terms);
2642 } else if (is_exactly_a<mul>(e)) {
2644 size_t num = e.nops();
2645 exvector v; v.reserve(num);
2647 for (size_t i=0; i<num; i++)
2648 v.push_back(find_common_factor(e.op(i), factor, repl));
2650 return dynallocate<mul>(v);
2652 } else if (is_exactly_a<power>(e)) {
2653 const ex e_exp(e.op(1));
2654 if (e_exp.info(info_flags::integer)) {
2655 ex eb = e.op(0).to_polynomial(repl);
2656 ex factor_local(_ex1);
2657 ex pre_res = find_common_factor(eb, factor_local, repl);
2658 factor *= power(factor_local, e_exp);
2659 return power(pre_res, e_exp);
2662 return e.to_polynomial(repl);
2669 /** Collect common factors in sums. This converts expressions like
2670 * 'a*(b*x+b*y)' to 'a*b*(x+y)'. */
2671 ex collect_common_factors(const ex & e)
2673 if (is_exactly_a<add>(e) || is_exactly_a<mul>(e) || is_exactly_a<power>(e)) {
2677 ex r = find_common_factor(e, factor, repl);
2678 return factor.subs(repl, subs_options::no_pattern) * r.subs(repl, subs_options::no_pattern);
2685 /** Resultant of two expressions e1,e2 with respect to symbol s.
2686 * Method: Compute determinant of Sylvester matrix of e1,e2,s. */
2687 ex resultant(const ex & e1, const ex & e2, const ex & s)
2689 const ex ee1 = e1.expand();
2690 const ex ee2 = e2.expand();
2691 if (!ee1.info(info_flags::polynomial) ||
2692 !ee2.info(info_flags::polynomial))
2693 throw(std::runtime_error("resultant(): arguments must be polynomials"));
2695 const int h1 = ee1.degree(s);
2696 const int l1 = ee1.ldegree(s);
2697 const int h2 = ee2.degree(s);
2698 const int l2 = ee2.ldegree(s);
2700 const int msize = h1 + h2;
2701 matrix m(msize, msize);
2703 for (int l = h1; l >= l1; --l) {
2704 const ex e = ee1.coeff(s, l);
2705 for (int k = 0; k < h2; ++k)
2708 for (int l = h2; l >= l2; --l) {
2709 const ex e = ee2.coeff(s, l);
2710 for (int k = 0; k < h1; ++k)
2711 m(k+h2, k+h2-l) = e;
2714 return m.determinant();
2718 } // namespace GiNaC