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