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-2022 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 /** Comparison 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 auto 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 << std::endl;
218 std::clog << " lcoeff_a=" << a.lcoeff(it->sym) << ", lcoeff_b=" << b.lcoeff(it->sym) << std::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 (lcm.is_equal(*_num1_p))
277 if (is_exactly_a<mul>(e)) {
278 // (a*b*...)*lcm -> (a*lcma)*(b*lcmb)*...*(lcm/(lcma*lcmb*...))
279 size_t num = e.nops();
282 numeric lcm_accum = *_num1_p;
283 for (size_t i=0; i<num; i++) {
284 numeric op_lcm = lcmcoeff(e.op(i), *_num1_p);
285 v.push_back(multiply_lcm(e.op(i), op_lcm));
288 v.push_back(lcm / lcm_accum);
289 return dynallocate<mul>(v);
290 } else if (is_exactly_a<add>(e)) {
291 // (a+b+...)*lcm -> a*lcm+b*lcm+...
292 size_t num = e.nops();
295 for (size_t i=0; i<num; i++)
296 v.push_back(multiply_lcm(e.op(i), lcm));
297 return dynallocate<add>(v);
298 } else if (is_exactly_a<power>(e)) {
299 if (!is_a<symbol>(e.op(0))) {
300 // (b^e)*lcm -> (b*lcm^(1/e))^e if lcm^(1/e) ∈ ℚ (i.e. not a float)
301 // but not for symbolic b, as evaluation would undo this again
302 numeric root_of_lcm = lcm.power(ex_to<numeric>(e.op(1)).inverse());
303 if (root_of_lcm.is_rational())
304 return pow(multiply_lcm(e.op(0), root_of_lcm), e.op(1));
307 // can't recurse down into e
308 return dynallocate<mul>(e, lcm);
312 /** Compute the integer content (= GCD of all numeric coefficients) of an
313 * expanded polynomial. For a polynomial with rational coefficients, this
314 * returns g/l where g is the GCD of the coefficients' numerators and l
315 * is the LCM of the coefficients' denominators.
317 * @return integer content */
318 numeric ex::integer_content() const
320 return bp->integer_content();
323 numeric basic::integer_content() const
328 numeric numeric::integer_content() const
333 numeric add::integer_content() const
335 numeric c = *_num0_p, l = *_num1_p;
336 for (auto & it : seq) {
337 GINAC_ASSERT(!is_exactly_a<numeric>(it.rest));
338 GINAC_ASSERT(is_exactly_a<numeric>(it.coeff));
339 c = gcd(ex_to<numeric>(it.coeff).numer(), c);
340 l = lcm(ex_to<numeric>(it.coeff).denom(), l);
342 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
343 c = gcd(ex_to<numeric>(overall_coeff).numer(), c);
344 l = lcm(ex_to<numeric>(overall_coeff).denom(), l);
348 numeric mul::integer_content() const
350 #ifdef DO_GINAC_ASSERT
351 for (auto & it : seq) {
352 GINAC_ASSERT(!is_exactly_a<numeric>(recombine_pair_to_ex(it)));
354 #endif // def DO_GINAC_ASSERT
355 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
356 return abs(ex_to<numeric>(overall_coeff));
361 * Polynomial quotients and remainders
364 /** Quotient q(x) of polynomials a(x) and b(x) in Q[x].
365 * It satisfies a(x)=b(x)*q(x)+r(x).
367 * @param a first polynomial in x (dividend)
368 * @param b second polynomial in x (divisor)
369 * @param x a and b are polynomials in x
370 * @param check_args check whether a and b are polynomials with rational
371 * coefficients (defaults to "true")
372 * @return quotient of a and b in Q[x] */
373 ex quo(const ex &a, const ex &b, const ex &x, bool check_args)
376 throw(std::overflow_error("quo: division by zero"));
377 if (is_exactly_a<numeric>(a) && is_exactly_a<numeric>(b))
383 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
384 throw(std::invalid_argument("quo: arguments must be polynomials over the rationals"));
386 // Polynomial long division
390 int bdeg = b.degree(x);
391 int rdeg = r.degree(x);
392 ex blcoeff = b.expand().coeff(x, bdeg);
393 bool blcoeff_is_numeric = is_exactly_a<numeric>(blcoeff);
394 exvector v; v.reserve(std::max(rdeg - bdeg + 1, 0));
395 while (rdeg >= bdeg) {
396 ex term, rcoeff = r.coeff(x, rdeg);
397 if (blcoeff_is_numeric)
398 term = rcoeff / blcoeff;
400 if (!divide(rcoeff, blcoeff, term, false))
401 return dynallocate<fail>();
403 term *= pow(x, rdeg - bdeg);
405 r -= (term * b).expand();
410 return dynallocate<add>(v);
414 /** Remainder r(x) of polynomials a(x) and b(x) in Q[x].
415 * It satisfies a(x)=b(x)*q(x)+r(x).
417 * @param a first polynomial in x (dividend)
418 * @param b second polynomial in x (divisor)
419 * @param x a and b are polynomials in x
420 * @param check_args check whether a and b are polynomials with rational
421 * coefficients (defaults to "true")
422 * @return remainder of a(x) and b(x) in Q[x] */
423 ex rem(const ex &a, const ex &b, const ex &x, bool check_args)
426 throw(std::overflow_error("rem: division by zero"));
427 if (is_exactly_a<numeric>(a)) {
428 if (is_exactly_a<numeric>(b))
437 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
438 throw(std::invalid_argument("rem: arguments must be polynomials over the rationals"));
440 // Polynomial long division
444 int bdeg = b.degree(x);
445 int rdeg = r.degree(x);
446 ex blcoeff = b.expand().coeff(x, bdeg);
447 bool blcoeff_is_numeric = is_exactly_a<numeric>(blcoeff);
448 while (rdeg >= bdeg) {
449 ex term, rcoeff = r.coeff(x, rdeg);
450 if (blcoeff_is_numeric)
451 term = rcoeff / blcoeff;
453 if (!divide(rcoeff, blcoeff, term, false))
454 return dynallocate<fail>();
456 term *= pow(x, rdeg - bdeg);
457 r -= (term * b).expand();
466 /** Decompose rational function a(x)=N(x)/D(x) into P(x)+n(x)/D(x)
467 * with degree(n, x) < degree(D, x).
469 * @param a rational function in x
470 * @param x a is a function of x
471 * @return decomposed function. */
472 ex decomp_rational(const ex &a, const ex &x)
474 ex nd = numer_denom(a);
475 ex numer = nd.op(0), denom = nd.op(1);
476 ex q = quo(numer, denom, x);
477 if (is_exactly_a<fail>(q))
480 return q + rem(numer, denom, x) / denom;
484 /** Pseudo-remainder of polynomials a(x) and b(x) in Q[x].
486 * @param a first polynomial in x (dividend)
487 * @param b second polynomial in x (divisor)
488 * @param x a and b are polynomials in x
489 * @param check_args check whether a and b are polynomials with rational
490 * coefficients (defaults to "true")
491 * @return pseudo-remainder of a(x) and b(x) in Q[x] */
492 ex prem(const ex &a, const ex &b, const ex &x, bool check_args)
495 throw(std::overflow_error("prem: division by zero"));
496 if (is_exactly_a<numeric>(a)) {
497 if (is_exactly_a<numeric>(b))
502 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
503 throw(std::invalid_argument("prem: arguments must be polynomials over the rationals"));
505 // Polynomial long division
508 int rdeg = r.degree(x);
509 int bdeg = eb.degree(x);
512 blcoeff = eb.coeff(x, bdeg);
516 eb -= blcoeff * pow(x, bdeg);
520 int delta = rdeg - bdeg + 1, i = 0;
521 while (rdeg >= bdeg && !r.is_zero()) {
522 ex rlcoeff = r.coeff(x, rdeg);
523 ex term = (pow(x, rdeg - bdeg) * eb * rlcoeff).expand();
527 r -= rlcoeff * pow(x, rdeg);
528 r = (blcoeff * r).expand() - term;
532 return pow(blcoeff, delta - i) * r;
536 /** Sparse pseudo-remainder of polynomials a(x) and b(x) in Q[x].
538 * @param a first polynomial in x (dividend)
539 * @param b second polynomial in x (divisor)
540 * @param x a and b are polynomials in x
541 * @param check_args check whether a and b are polynomials with rational
542 * coefficients (defaults to "true")
543 * @return sparse pseudo-remainder of a(x) and b(x) in Q[x] */
544 ex sprem(const ex &a, const ex &b, const ex &x, bool check_args)
547 throw(std::overflow_error("prem: division by zero"));
548 if (is_exactly_a<numeric>(a)) {
549 if (is_exactly_a<numeric>(b))
554 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
555 throw(std::invalid_argument("prem: arguments must be polynomials over the rationals"));
557 // Polynomial long division
560 int rdeg = r.degree(x);
561 int bdeg = eb.degree(x);
564 blcoeff = eb.coeff(x, bdeg);
568 eb -= blcoeff * pow(x, bdeg);
572 while (rdeg >= bdeg && !r.is_zero()) {
573 ex rlcoeff = r.coeff(x, rdeg);
574 ex term = (pow(x, rdeg - bdeg) * eb * rlcoeff).expand();
578 r -= rlcoeff * pow(x, rdeg);
579 r = (blcoeff * r).expand() - term;
586 /** Exact polynomial division of a(X) by b(X) in Q[X].
588 * @param a first multivariate polynomial (dividend)
589 * @param b second multivariate polynomial (divisor)
590 * @param q quotient (returned)
591 * @param check_args check whether a and b are polynomials with rational
592 * coefficients (defaults to "true")
593 * @return "true" when exact division succeeds (quotient returned in q),
594 * "false" otherwise (q left untouched) */
595 bool divide(const ex &a, const ex &b, ex &q, bool check_args)
598 throw(std::overflow_error("divide: division by zero"));
603 if (is_exactly_a<numeric>(b)) {
606 } else if (is_exactly_a<numeric>(a))
614 if (check_args && (!a.info(info_flags::rational_polynomial) ||
615 !b.info(info_flags::rational_polynomial)))
616 throw(std::invalid_argument("divide: arguments must be polynomials over the rationals"));
620 if (!get_first_symbol(a, x) && !get_first_symbol(b, x))
621 throw(std::invalid_argument("invalid expression in divide()"));
623 // Try to avoid expanding partially factored expressions.
624 if (is_exactly_a<mul>(b)) {
625 // Divide sequentially by each term
626 ex rem_new, rem_old = a;
627 for (size_t i=0; i < b.nops(); i++) {
628 if (! divide(rem_old, b.op(i), rem_new, false))
634 } else if (is_exactly_a<power>(b)) {
635 const ex& bb(b.op(0));
636 int exp_b = ex_to<numeric>(b.op(1)).to_int();
637 ex rem_new, rem_old = a;
638 for (int i=exp_b; i>0; i--) {
639 if (! divide(rem_old, bb, rem_new, false))
647 if (is_exactly_a<mul>(a)) {
648 // Divide sequentially each term. If some term in a is divisible
649 // by b we are done... and if not, we can't really say anything.
652 bool divisible_p = false;
653 for (i=0; i < a.nops(); ++i) {
654 if (divide(a.op(i), b, rem_i, false)) {
661 resv.reserve(a.nops());
662 for (size_t j=0; j < a.nops(); j++) {
664 resv.push_back(rem_i);
666 resv.push_back(a.op(j));
668 q = dynallocate<mul>(resv);
671 } else if (is_exactly_a<power>(a)) {
672 // The base itself might be divisible by b, in that case we don't
674 const ex& ab(a.op(0));
675 int a_exp = ex_to<numeric>(a.op(1)).to_int();
677 if (divide(ab, b, rem_i, false)) {
678 q = rem_i * pow(ab, a_exp - 1);
681 // code below is commented-out because it leads to a significant slowdown
682 // for (int i=2; i < a_exp; i++) {
683 // if (divide(power(ab, i), b, rem_i, false)) {
684 // q = rem_i*power(ab, a_exp - i);
687 // } // ... so we *really* need to expand expression.
690 // Polynomial long division (recursive)
696 int bdeg = b.degree(x);
697 int rdeg = r.degree(x);
698 ex blcoeff = b.expand().coeff(x, bdeg);
699 bool blcoeff_is_numeric = is_exactly_a<numeric>(blcoeff);
700 exvector v; v.reserve(std::max(rdeg - bdeg + 1, 0));
701 while (rdeg >= bdeg) {
702 ex term, rcoeff = r.coeff(x, rdeg);
703 if (blcoeff_is_numeric)
704 term = rcoeff / blcoeff;
706 if (!divide(rcoeff, blcoeff, term, false))
708 term *= pow(x, rdeg - bdeg);
710 r -= (term * b).expand();
712 q = dynallocate<add>(v);
726 typedef std::pair<ex, ex> ex2;
727 typedef std::pair<ex, bool> exbool;
730 bool operator() (const ex2 &p, const ex2 &q) const
732 int cmp = p.first.compare(q.first);
733 return ((cmp<0) || (!(cmp>0) && p.second.compare(q.second)<0));
737 typedef std::map<ex2, exbool, ex2_less> ex2_exbool_remember;
741 /** Exact polynomial division of a(X) by b(X) in Z[X].
742 * This functions works like divide() but the input and output polynomials are
743 * in Z[X] instead of Q[X] (i.e. they have integer coefficients). Unlike
744 * divide(), it doesn't check whether the input polynomials really are integer
745 * polynomials, so be careful of what you pass in. Also, you have to run
746 * get_symbol_stats() over the input polynomials before calling this function
747 * and pass an iterator to the first element of the sym_desc vector. This
748 * function is used internally by the heur_gcd().
750 * @param a first multivariate polynomial (dividend)
751 * @param b second multivariate polynomial (divisor)
752 * @param q quotient (returned)
753 * @param var iterator to first element of vector of sym_desc structs
754 * @return "true" when exact division succeeds (the quotient is returned in
755 * q), "false" otherwise.
756 * @see get_symbol_stats, heur_gcd */
757 static bool divide_in_z(const ex &a, const ex &b, ex &q, sym_desc_vec::const_iterator var)
761 throw(std::overflow_error("divide_in_z: division by zero"));
762 if (b.is_equal(_ex1)) {
766 if (is_exactly_a<numeric>(a)) {
767 if (is_exactly_a<numeric>(b)) {
769 return q.info(info_flags::integer);
782 static ex2_exbool_remember dr_remember;
783 ex2_exbool_remember::const_iterator remembered = dr_remember.find(ex2(a, b));
784 if (remembered != dr_remember.end()) {
785 q = remembered->second.first;
786 return remembered->second.second;
790 if (is_exactly_a<power>(b)) {
791 const ex& bb(b.op(0));
793 int exp_b = ex_to<numeric>(b.op(1)).to_int();
794 for (int i=exp_b; i>0; i--) {
795 if (!divide_in_z(qbar, bb, q, var))
802 if (is_exactly_a<mul>(b)) {
804 for (const auto & it : b) {
805 sym_desc_vec sym_stats;
806 get_symbol_stats(a, it, sym_stats);
807 if (!divide_in_z(qbar, it, q, sym_stats.begin()))
816 const ex &x = var->sym;
819 int adeg = a.degree(x), bdeg = b.degree(x);
823 #if USE_TRIAL_DIVISION
825 // Trial division with polynomial interpolation
828 // Compute values at evaluation points 0..adeg
829 vector<numeric> alpha; alpha.reserve(adeg + 1);
830 exvector u; u.reserve(adeg + 1);
831 numeric point = *_num0_p;
833 for (i=0; i<=adeg; i++) {
834 ex bs = b.subs(x == point, subs_options::no_pattern);
835 while (bs.is_zero()) {
837 bs = b.subs(x == point, subs_options::no_pattern);
839 if (!divide_in_z(a.subs(x == point, subs_options::no_pattern), bs, c, var+1))
841 alpha.push_back(point);
847 vector<numeric> rcp; rcp.reserve(adeg + 1);
848 rcp.push_back(*_num0_p);
849 for (k=1; k<=adeg; k++) {
850 numeric product = alpha[k] - alpha[0];
852 product *= alpha[k] - alpha[i];
853 rcp.push_back(product.inverse());
856 // Compute Newton coefficients
857 exvector v; v.reserve(adeg + 1);
859 for (k=1; k<=adeg; k++) {
861 for (i=k-2; i>=0; i--)
862 temp = temp * (alpha[k] - alpha[i]) + v[i];
863 v.push_back((u[k] - temp) * rcp[k]);
866 // Convert from Newton form to standard form
868 for (k=adeg-1; k>=0; k--)
869 c = c * (x - alpha[k]) + v[k];
871 if (c.degree(x) == (adeg - bdeg)) {
879 // Polynomial long division (recursive)
885 ex blcoeff = eb.coeff(x, bdeg);
886 exvector v; v.reserve(std::max(rdeg - bdeg + 1, 0));
887 while (rdeg >= bdeg) {
888 ex term, rcoeff = r.coeff(x, rdeg);
889 if (!divide_in_z(rcoeff, blcoeff, term, var+1))
891 term = (term * pow(x, rdeg - bdeg)).expand();
893 r -= (term * eb).expand();
895 q = dynallocate<add>(v);
897 dr_remember[ex2(a, b)] = exbool(q, true);
904 dr_remember[ex2(a, b)] = exbool(q, false);
913 * Separation of unit part, content part and primitive part of polynomials
916 /** Compute unit part (= sign of leading coefficient) of a multivariate
917 * polynomial in Q[x]. The product of unit part, content part, and primitive
918 * part is the polynomial itself.
920 * @param x main variable
922 * @see ex::content, ex::primpart, ex::unitcontprim */
923 ex ex::unit(const ex &x) const
925 ex c = expand().lcoeff(x);
926 if (is_exactly_a<numeric>(c))
927 return c.info(info_flags::negative) ?_ex_1 : _ex1;
930 if (get_first_symbol(c, y))
933 throw(std::invalid_argument("invalid expression in unit()"));
938 /** Compute content part (= unit normal GCD of all coefficients) of a
939 * multivariate polynomial in Q[x]. The product of unit part, content part,
940 * and primitive part is the polynomial itself.
942 * @param x main variable
943 * @return content part
944 * @see ex::unit, ex::primpart, ex::unitcontprim */
945 ex ex::content(const ex &x) const
947 if (is_exactly_a<numeric>(*this))
948 return info(info_flags::negative) ? -*this : *this;
954 // First, divide out the integer content (which we can calculate very efficiently).
955 // If the leading coefficient of the quotient is an integer, we are done.
956 ex c = e.integer_content();
958 int deg = r.degree(x);
959 ex lcoeff = r.coeff(x, deg);
960 if (lcoeff.info(info_flags::integer))
963 // GCD of all coefficients
964 int ldeg = r.ldegree(x);
966 return lcoeff * c / lcoeff.unit(x);
968 for (int i=ldeg; i<=deg; i++)
969 cont = gcd(r.coeff(x, i), cont, nullptr, nullptr, false);
974 /** Compute primitive part of a multivariate polynomial in Q[x]. The result
975 * will be a unit-normal polynomial with a content part of 1. The product
976 * of unit part, content part, and primitive part is the polynomial itself.
978 * @param x main variable
979 * @return primitive part
980 * @see ex::unit, ex::content, ex::unitcontprim */
981 ex ex::primpart(const ex &x) const
983 // We need to compute the unit and content anyway, so call unitcontprim()
985 unitcontprim(x, u, c, p);
990 /** Compute primitive part of a multivariate polynomial in Q[x] when the
991 * content part is already known. This function is faster in computing the
992 * primitive part than the previous function.
994 * @param x main variable
995 * @param c previously computed content part
996 * @return primitive part */
997 ex ex::primpart(const ex &x, const ex &c) const
999 if (is_zero() || c.is_zero())
1001 if (is_exactly_a<numeric>(*this))
1004 // Divide by unit and content to get primitive part
1006 if (is_exactly_a<numeric>(c))
1007 return *this / (c * u);
1009 return quo(*this, c * u, x, false);
1013 /** Compute unit part, content part, and primitive part of a multivariate
1014 * polynomial in Q[x]. The product of the three parts is the polynomial
1017 * @param x main variable
1018 * @param u unit part (returned)
1019 * @param c content part (returned)
1020 * @param p primitive part (returned)
1021 * @see ex::unit, ex::content, ex::primpart */
1022 void ex::unitcontprim(const ex &x, ex &u, ex &c, ex &p) const
1024 // Quick check for zero (avoid expanding)
1031 // Special case: input is a number
1032 if (is_exactly_a<numeric>(*this)) {
1033 if (info(info_flags::negative)) {
1035 c = abs(ex_to<numeric>(*this));
1044 // Expand input polynomial
1052 // Compute unit and content
1056 // Divide by unit and content to get primitive part
1061 if (is_exactly_a<numeric>(c))
1062 p = *this / (c * u);
1064 p = quo(e, c * u, x, false);
1069 * GCD of multivariate polynomials
1072 /** Compute GCD of multivariate polynomials using the subresultant PRS
1073 * algorithm. This function is used internally by gcd().
1075 * @param a first multivariate polynomial
1076 * @param b second multivariate polynomial
1077 * @param var iterator to first element of vector of sym_desc structs
1078 * @return the GCD as a new expression
1081 static ex sr_gcd(const ex &a, const ex &b, sym_desc_vec::const_iterator var)
1087 // The first symbol is our main variable
1088 const ex &x = var->sym;
1090 // Sort c and d so that c has higher degree
1092 int adeg = a.degree(x), bdeg = b.degree(x);
1106 // Remove content from c and d, to be attached to GCD later
1107 ex cont_c = c.content(x);
1108 ex cont_d = d.content(x);
1109 ex gamma = gcd(cont_c, cont_d, nullptr, nullptr, false);
1112 c = c.primpart(x, cont_c);
1113 d = d.primpart(x, cont_d);
1115 // First element of subresultant sequence
1116 ex r = _ex0, ri = _ex1, psi = _ex1;
1117 int delta = cdeg - ddeg;
1121 // Calculate polynomial pseudo-remainder
1122 r = prem(c, d, x, false);
1124 return gamma * d.primpart(x);
1128 if (!divide_in_z(r, ri * pow(psi, delta), d, var))
1129 throw(std::runtime_error("invalid expression in sr_gcd(), division failed"));
1132 if (is_exactly_a<numeric>(r))
1135 return gamma * r.primpart(x);
1138 // Next element of subresultant sequence
1139 ri = c.expand().lcoeff(x);
1143 divide_in_z(pow(ri, delta), pow(psi, delta-1), psi, var+1);
1144 delta = cdeg - ddeg;
1149 /** Return maximum (absolute value) coefficient of a polynomial.
1150 * This function is used internally by heur_gcd().
1152 * @return maximum coefficient
1154 numeric ex::max_coefficient() const
1156 return bp->max_coefficient();
1159 /** Implementation ex::max_coefficient().
1161 numeric basic::max_coefficient() const
1166 numeric numeric::max_coefficient() const
1171 numeric add::max_coefficient() const
1173 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
1174 numeric cur_max = abs(ex_to<numeric>(overall_coeff));
1175 for (auto & it : seq) {
1177 GINAC_ASSERT(!is_exactly_a<numeric>(it.rest));
1178 a = abs(ex_to<numeric>(it.coeff));
1185 numeric mul::max_coefficient() const
1187 #ifdef DO_GINAC_ASSERT
1188 for (auto & it : seq) {
1189 GINAC_ASSERT(!is_exactly_a<numeric>(recombine_pair_to_ex(it)));
1191 #endif // def DO_GINAC_ASSERT
1192 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
1193 return abs(ex_to<numeric>(overall_coeff));
1197 /** Apply symmetric modular homomorphism to an expanded multivariate
1198 * polynomial. This function is usually used internally by heur_gcd().
1201 * @return mapped polynomial
1203 ex basic::smod(const numeric &xi) const
1208 ex numeric::smod(const numeric &xi) const
1210 return GiNaC::smod(*this, xi);
1213 ex add::smod(const numeric &xi) const
1216 newseq.reserve(seq.size()+1);
1217 for (auto & it : seq) {
1218 GINAC_ASSERT(!is_exactly_a<numeric>(it.rest));
1219 numeric coeff = GiNaC::smod(ex_to<numeric>(it.coeff), xi);
1220 if (!coeff.is_zero())
1221 newseq.push_back(expair(it.rest, coeff));
1223 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
1224 numeric coeff = GiNaC::smod(ex_to<numeric>(overall_coeff), xi);
1225 return dynallocate<add>(std::move(newseq), coeff);
1228 ex mul::smod(const numeric &xi) const
1230 #ifdef DO_GINAC_ASSERT
1231 for (auto & it : seq) {
1232 GINAC_ASSERT(!is_exactly_a<numeric>(recombine_pair_to_ex(it)));
1234 #endif // def DO_GINAC_ASSERT
1235 mul & mulcopy = dynallocate<mul>(*this);
1236 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
1237 mulcopy.overall_coeff = GiNaC::smod(ex_to<numeric>(overall_coeff),xi);
1238 mulcopy.clearflag(status_flags::evaluated);
1239 mulcopy.clearflag(status_flags::hash_calculated);
1244 /** xi-adic polynomial interpolation */
1245 static ex interpolate(const ex &gamma, const numeric &xi, const ex &x, int degree_hint = 1)
1247 exvector g; g.reserve(degree_hint);
1249 numeric rxi = xi.inverse();
1250 for (int i=0; !e.is_zero(); i++) {
1252 g.push_back(gi * pow(x, i));
1255 return dynallocate<add>(g);
1258 /** Exception thrown by heur_gcd() to signal failure. */
1259 class gcdheu_failed {};
1261 /** Compute GCD of multivariate polynomials using the heuristic GCD algorithm.
1262 * get_symbol_stats() must have been called previously with the input
1263 * polynomials and an iterator to the first element of the sym_desc vector
1264 * passed in. This function is used internally by gcd().
1266 * @param a first integer multivariate polynomial (expanded)
1267 * @param b second integer multivariate polynomial (expanded)
1268 * @param ca cofactor of polynomial a (returned), nullptr to suppress
1269 * calculation of cofactor
1270 * @param cb cofactor of polynomial b (returned), nullptr to suppress
1271 * calculation of cofactor
1272 * @param var iterator to first element of vector of sym_desc structs
1273 * @param res the GCD (returned)
1274 * @return true if GCD was computed, false otherwise.
1276 * @exception gcdheu_failed() */
1277 static bool heur_gcd_z(ex& res, const ex &a, const ex &b, ex *ca, ex *cb,
1278 sym_desc_vec::const_iterator var)
1284 // Algorithm only works for non-vanishing input polynomials
1285 if (a.is_zero() || b.is_zero())
1288 // GCD of two numeric values -> CLN
1289 if (is_exactly_a<numeric>(a) && is_exactly_a<numeric>(b)) {
1290 numeric g = gcd(ex_to<numeric>(a), ex_to<numeric>(b));
1292 *ca = ex_to<numeric>(a) / g;
1294 *cb = ex_to<numeric>(b) / g;
1299 // The first symbol is our main variable
1300 const ex &x = var->sym;
1302 // Remove integer content
1303 numeric gc = gcd(a.integer_content(), b.integer_content());
1304 numeric rgc = gc.inverse();
1307 int maxdeg = std::max(p.degree(x), q.degree(x));
1309 // Find evaluation point
1310 numeric mp = p.max_coefficient();
1311 numeric mq = q.max_coefficient();
1314 xi = mq * (*_num2_p) + (*_num2_p);
1316 xi = mp * (*_num2_p) + (*_num2_p);
1319 for (int t=0; t<6; t++) {
1320 if (xi.int_length() * maxdeg > 100000) {
1321 throw gcdheu_failed();
1324 // Apply evaluation homomorphism and calculate GCD
1327 bool found = heur_gcd_z(gamma,
1328 p.subs(x == xi, subs_options::no_pattern),
1329 q.subs(x == xi, subs_options::no_pattern),
1332 gamma = gamma.expand();
1333 // Reconstruct polynomial from GCD of mapped polynomials
1334 ex g = interpolate(gamma, xi, x, maxdeg);
1336 // Remove integer content
1337 g /= g.integer_content();
1339 // If the calculated polynomial divides both p and q, this is the GCD
1341 if (divide_in_z(p, g, ca ? *ca : dummy, var) && divide_in_z(q, g, cb ? *cb : dummy, var)) {
1348 // Next evaluation point
1349 xi = iquo(xi * isqrt(isqrt(xi)) * numeric(73794), numeric(27011));
1354 /** Compute GCD of multivariate polynomials using the heuristic GCD algorithm.
1355 * get_symbol_stats() must have been called previously with the input
1356 * polynomials and an iterator to the first element of the sym_desc vector
1357 * passed in. This function is used internally by gcd().
1359 * @param a first rational multivariate polynomial (expanded)
1360 * @param b second rational multivariate polynomial (expanded)
1361 * @param ca cofactor of polynomial a (returned), nullptr to suppress
1362 * calculation of cofactor
1363 * @param cb cofactor of polynomial b (returned), nullptr to suppress
1364 * calculation of cofactor
1365 * @param var iterator to first element of vector of sym_desc structs
1366 * @param res the GCD (returned)
1367 * @return true if GCD was computed, false otherwise.
1371 static bool heur_gcd(ex& res, const ex& a, const ex& b, ex *ca, ex *cb,
1372 sym_desc_vec::const_iterator var)
1374 if (a.info(info_flags::integer_polynomial) &&
1375 b.info(info_flags::integer_polynomial)) {
1377 return heur_gcd_z(res, a, b, ca, cb, var);
1378 } catch (gcdheu_failed) {
1383 // convert polynomials to Z[X]
1384 const numeric a_lcm = lcm_of_coefficients_denominators(a);
1385 const numeric ab_lcm = lcmcoeff(b, a_lcm);
1387 const ex ai = a*ab_lcm;
1388 const ex bi = b*ab_lcm;
1389 if (!ai.info(info_flags::integer_polynomial))
1390 throw std::logic_error("heur_gcd: not an integer polynomial [1]");
1392 if (!bi.info(info_flags::integer_polynomial))
1393 throw std::logic_error("heur_gcd: not an integer polynomial [2]");
1397 found = heur_gcd_z(res, ai, bi, ca, cb, var);
1398 } catch (gcdheu_failed) {
1402 // GCD is not unique, it's defined up to a unit (i.e. invertible
1403 // element). If the coefficient ring is a field, every its element is
1404 // invertible, so one can multiply the polynomial GCD with any element
1405 // of the coefficient field. We use this ambiguity to make cofactors
1406 // integer polynomials.
1413 // gcd helper to handle partially factored polynomials (to avoid expanding
1414 // large expressions). At least one of the arguments should be a power.
1415 static ex gcd_pf_pow(const ex& a, const ex& b, ex* ca, ex* cb);
1417 // gcd helper to handle partially factored polynomials (to avoid expanding
1418 // large expressions). At least one of the arguments should be a product.
1419 static ex gcd_pf_mul(const ex& a, const ex& b, ex* ca, ex* cb);
1421 /** Compute GCD (Greatest Common Divisor) of multivariate polynomials a(X)
1422 * and b(X) in Z[X]. Optionally also compute the cofactors of a and b,
1423 * defined by a = ca * gcd(a, b) and b = cb * gcd(a, b).
1425 * @param a first multivariate polynomial
1426 * @param b second multivariate polynomial
1427 * @param ca pointer to expression that will receive the cofactor of a, or nullptr
1428 * @param cb pointer to expression that will receive the cofactor of b, or nullptr
1429 * @param check_args check whether a and b are polynomials with rational
1430 * coefficients (defaults to "true")
1431 * @return the GCD as a new expression */
1432 ex gcd(const ex &a, const ex &b, ex *ca, ex *cb, bool check_args, unsigned options)
1438 // GCD of numerics -> CLN
1439 if (is_exactly_a<numeric>(a) && is_exactly_a<numeric>(b)) {
1440 numeric g = gcd(ex_to<numeric>(a), ex_to<numeric>(b));
1449 *ca = ex_to<numeric>(a) / g;
1451 *cb = ex_to<numeric>(b) / g;
1458 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial))) {
1459 throw(std::invalid_argument("gcd: arguments must be polynomials over the rationals"));
1462 // Partially factored cases (to avoid expanding large expressions)
1463 if (!(options & gcd_options::no_part_factored)) {
1464 if (is_exactly_a<mul>(a) || is_exactly_a<mul>(b))
1465 return gcd_pf_mul(a, b, ca, cb);
1467 if (is_exactly_a<power>(a) || is_exactly_a<power>(b))
1468 return gcd_pf_pow(a, b, ca, cb);
1472 // Some trivial cases
1473 ex aex = a.expand();
1474 if (aex.is_zero()) {
1481 ex bex = b.expand();
1482 if (bex.is_zero()) {
1489 if (aex.is_equal(_ex1) || bex.is_equal(_ex1)) {
1497 if (a.is_equal(b)) {
1506 if (is_a<symbol>(aex)) {
1507 if (! bex.subs(aex==_ex0, subs_options::no_pattern).is_zero()) {
1516 if (is_a<symbol>(bex)) {
1517 if (! aex.subs(bex==_ex0, subs_options::no_pattern).is_zero()) {
1526 if (is_exactly_a<numeric>(aex)) {
1527 numeric bcont = bex.integer_content();
1528 numeric g = gcd(ex_to<numeric>(aex), bcont);
1530 *ca = ex_to<numeric>(aex)/g;
1536 if (is_exactly_a<numeric>(bex)) {
1537 numeric acont = aex.integer_content();
1538 numeric g = gcd(ex_to<numeric>(bex), acont);
1542 *cb = ex_to<numeric>(bex)/g;
1546 // Gather symbol statistics
1547 sym_desc_vec sym_stats;
1548 get_symbol_stats(a, b, sym_stats);
1550 // The symbol with least degree which is contained in both polynomials
1551 // is our main variable
1552 auto vari = sym_stats.begin();
1553 while ((vari != sym_stats.end()) &&
1554 (((vari->ldeg_b == 0) && (vari->deg_b == 0)) ||
1555 ((vari->ldeg_a == 0) && (vari->deg_a == 0))))
1558 // No common symbols at all, just return 1:
1559 if (vari == sym_stats.end()) {
1560 // N.B: keep cofactors factored
1567 // move symbol contained only in one of the polynomials to the end:
1568 rotate(sym_stats.begin(), vari, sym_stats.end());
1570 sym_desc_vec::const_iterator var = sym_stats.begin();
1571 const ex &x = var->sym;
1573 // Cancel trivial common factor
1574 int ldeg_a = var->ldeg_a;
1575 int ldeg_b = var->ldeg_b;
1576 int min_ldeg = std::min(ldeg_a,ldeg_b);
1578 ex common = pow(x, min_ldeg);
1579 return gcd((aex / common).expand(), (bex / common).expand(), ca, cb, false) * common;
1582 // Try to eliminate variables
1583 if (var->deg_a == 0 && var->deg_b != 0 ) {
1584 ex bex_u, bex_c, bex_p;
1585 bex.unitcontprim(x, bex_u, bex_c, bex_p);
1586 ex g = gcd(aex, bex_c, ca, cb, false);
1588 *cb *= bex_u * bex_p;
1590 } else if (var->deg_b == 0 && var->deg_a != 0) {
1591 ex aex_u, aex_c, aex_p;
1592 aex.unitcontprim(x, aex_u, aex_c, aex_p);
1593 ex g = gcd(aex_c, bex, ca, cb, false);
1595 *ca *= aex_u * aex_p;
1599 // Try heuristic algorithm first, fall back to PRS if that failed
1601 if (!(options & gcd_options::no_heur_gcd)) {
1602 bool found = heur_gcd(g, aex, bex, ca, cb, var);
1604 // heur_gcd have already computed cofactors...
1605 if (g.is_equal(_ex1)) {
1606 // ... but we want to keep them factored if possible.
1620 if (options & gcd_options::use_sr_gcd) {
1621 g = sr_gcd(aex, bex, var);
1624 for (std::size_t n = sym_stats.size(); n-- != 0; )
1625 vars.push_back(sym_stats[n].sym);
1626 g = chinrem_gcd(aex, bex, vars);
1629 if (g.is_equal(_ex1)) {
1630 // Keep cofactors factored if possible
1637 divide(aex, g, *ca, false);
1639 divide(bex, g, *cb, false);
1644 // gcd helper to handle partially factored polynomials (to avoid expanding
1645 // large expressions). Both arguments should be powers.
1646 static ex gcd_pf_pow_pow(const ex& a, const ex& b, ex* ca, ex* cb)
1649 const ex& exp_a = a.op(1);
1651 const ex& exp_b = b.op(1);
1653 // a = p^n, b = p^m, gcd = p^min(n, m)
1654 if (p.is_equal(pb)) {
1655 if (exp_a < exp_b) {
1659 *cb = pow(p, exp_b - exp_a);
1660 return pow(p, exp_a);
1663 *ca = pow(p, exp_a - exp_b);
1666 return pow(p, exp_b);
1671 ex p_gcd = gcd(p, pb, &p_co, &pb_co, false);
1672 // a(x) = p(x)^n, b(x) = p_b(x)^m, gcd (p, p_b) = 1 ==> gcd(a,b) = 1
1673 if (p_gcd.is_equal(_ex1)) {
1681 // there are common factors:
1682 // a(x) = g(x)^n A(x)^n, b(x) = g(x)^m B(x)^m ==>
1683 // gcd(a, b) = g(x)^n gcd(A(x)^n, g(x)^(n-m) B(x)^m
1684 if (exp_a < exp_b) {
1685 ex pg = gcd(pow(p_co, exp_a), pow(p_gcd, exp_b-exp_a)*pow(pb_co, exp_b), ca, cb, false);
1686 return pow(p_gcd, exp_a)*pg;
1688 ex pg = gcd(pow(p_gcd, exp_a - exp_b)*pow(p_co, exp_a), pow(pb_co, exp_b), ca, cb, false);
1689 return pow(p_gcd, exp_b)*pg;
1693 static ex gcd_pf_pow(const ex& a, const ex& b, ex* ca, ex* cb)
1695 if (is_exactly_a<power>(a) && is_exactly_a<power>(b))
1696 return gcd_pf_pow_pow(a, b, ca, cb);
1698 if (is_exactly_a<power>(b) && (! is_exactly_a<power>(a)))
1699 return gcd_pf_pow(b, a, cb, ca);
1701 GINAC_ASSERT(is_exactly_a<power>(a));
1704 const ex& exp_a = a.op(1);
1705 if (p.is_equal(b)) {
1706 // a = p^n, b = p, gcd = p
1708 *ca = pow(p, exp_a - 1);
1713 if (is_a<symbol>(p)) {
1714 // Cancel trivial common factor
1715 int ldeg_a = ex_to<numeric>(exp_a).to_int();
1716 int ldeg_b = b.ldegree(p);
1717 int min_ldeg = std::min(ldeg_a, ldeg_b);
1719 ex common = pow(p, min_ldeg);
1720 return gcd(pow(p, ldeg_a - min_ldeg), (b / common).expand(), ca, cb, false) * common;
1725 ex p_gcd = gcd(p, b, &p_co, &bpart_co, false);
1727 if (p_gcd.is_equal(_ex1)) {
1728 // a(x) = p(x)^n, gcd(p, b) = 1 ==> gcd(a, b) = 1
1735 // 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))
1736 ex rg = gcd(pow(p_gcd, exp_a-1)*pow(p_co, exp_a), bpart_co, ca, cb, false);
1740 static ex gcd_pf_mul(const ex& a, const ex& b, ex* ca, ex* cb)
1742 if (is_exactly_a<mul>(a) && is_exactly_a<mul>(b)
1743 && (b.nops() > a.nops()))
1744 return gcd_pf_mul(b, a, cb, ca);
1746 if (is_exactly_a<mul>(b) && (!is_exactly_a<mul>(a)))
1747 return gcd_pf_mul(b, a, cb, ca);
1749 GINAC_ASSERT(is_exactly_a<mul>(a));
1750 size_t num = a.nops();
1751 exvector g; g.reserve(num);
1752 exvector acc_ca; acc_ca.reserve(num);
1754 for (size_t i=0; i<num; i++) {
1755 ex part_ca, part_cb;
1756 g.push_back(gcd(a.op(i), part_b, &part_ca, &part_cb, false));
1757 acc_ca.push_back(part_ca);
1761 *ca = dynallocate<mul>(acc_ca);
1764 return dynallocate<mul>(g);
1767 /** Compute LCM (Least Common Multiple) of multivariate polynomials in Z[X].
1769 * @param a first multivariate polynomial
1770 * @param b second multivariate polynomial
1771 * @param check_args check whether a and b are polynomials with rational
1772 * coefficients (defaults to "true")
1773 * @return the LCM as a new expression */
1774 ex lcm(const ex &a, const ex &b, bool check_args)
1776 if (is_exactly_a<numeric>(a) && is_exactly_a<numeric>(b))
1777 return lcm(ex_to<numeric>(a), ex_to<numeric>(b));
1778 if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
1779 throw(std::invalid_argument("lcm: arguments must be polynomials over the rationals"));
1782 ex g = gcd(a, b, &ca, &cb, false);
1788 * Square-free factorization
1791 /** Compute square-free factorization of multivariate polynomial a(x) using
1792 * Yun's algorithm. Used internally by sqrfree().
1794 * @param a multivariate polynomial over Z[X], treated here as univariate
1795 * polynomial in x (needs not be expanded).
1796 * @param x variable to factor in
1797 * @return vector of expairs (factor, exponent), sorted by exponents */
1798 static epvector sqrfree_yun(const ex &a, const symbol &x)
1804 // manifest zero or hidden zero
1807 if (g.is_equal(_ex1)) {
1808 // w(x) and w'(x) share no factors: w(x) is square-free
1809 return {expair(a, _ex1)};
1813 ex i = 0; // exponent
1820 z = quo(z, g, x) - w.diff(x);
1822 if (w.is_equal(x)) {
1823 // shortcut for x^n with n ∈ ℕ
1824 i += quo(z, w.diff(x), x);
1825 factors.push_back(expair(w, i));
1829 if (!g.is_equal(_ex1)) {
1830 factors.push_back(expair(g, i));
1832 } while (!z.is_zero());
1834 // correct for lost factor
1835 // (being based on GCDs, Yun's algorithm only finds factors up to a unit)
1836 const ex lost_factor = quo(a, mul{factors}, x);
1837 if (lost_factor.is_equal(_ex1)) {
1838 // trivial lost factor
1841 if (!factors.empty() && factors[0].coeff.is_equal(1)) {
1842 // multiply factor^1 with lost_factor
1843 factors[0].rest *= lost_factor;
1846 // no factor^1: prepend lost_factor^1 to the results
1847 epvector results = {expair(lost_factor, 1)};
1848 std::move(factors.begin(), factors.end(), std::back_inserter(results));
1853 /** Compute a square-free factorization of a multivariate polynomial in Q[X].
1855 * @param a multivariate polynomial over Q[X] (needs not be expanded)
1856 * @param l lst of variables to factor in, may be left empty for autodetection
1857 * @return a square-free factorization of \p a.
1860 * A polynomial \f$p(X) \in C[X]\f$ is said <EM>square-free</EM>
1861 * if, whenever any two polynomials \f$q(X)\f$ and \f$r(X)\f$
1864 * p(X) = q(X)^2 r(X),
1866 * we have \f$q(X) \in C\f$.
1867 * This means that \f$p(X)\f$ has no repeated factors, apart
1868 * eventually from constants.
1869 * Given a polynomial \f$p(X) \in C[X]\f$, we say that the
1872 * p(X) = b \cdot p_1(X)^{a_1} \cdot p_2(X)^{a_2} \cdots p_r(X)^{a_r}
1874 * is a <EM>square-free factorization</EM> of \f$p(X)\f$ if the
1875 * following conditions hold:
1876 * -# \f$b \in C\f$ and \f$b \neq 0\f$;
1877 * -# \f$a_i\f$ is a positive integer for \f$i = 1, \ldots, r\f$;
1878 * -# the degree of the polynomial \f$p_i\f$ is strictly positive
1879 * for \f$i = 1, \ldots, r\f$;
1880 * -# the polynomial \f$\Pi_{i=1}^r p_i(X)\f$ is square-free.
1882 * Square-free factorizations need not be unique. For example, if
1883 * \f$a_i\f$ is even, we could change the polynomial \f$p_i(X)\f$
1884 * into \f$-p_i(X)\f$.
1885 * Observe also that the factors \f$p_i(X)\f$ need not be irreducible
1888 ex sqrfree(const ex &a, const lst &l)
1890 if (is_exactly_a<numeric>(a) ||
1891 is_a<symbol>(a)) // shortcuts
1894 // If no lst of variables to factorize in was specified we have to
1895 // invent one now. Maybe one can optimize here by reversing the order
1896 // or so, I don't know.
1900 get_symbol_stats(a, _ex0, sdv);
1901 for (auto & it : sdv)
1902 args.append(it.sym);
1907 // Find the symbol to factor in at this stage
1908 if (!is_a<symbol>(args.op(0)))
1909 throw (std::runtime_error("sqrfree(): invalid factorization variable"));
1910 const symbol &x = ex_to<symbol>(args.op(0));
1912 // convert the argument from something in Q[X] to something in Z[X]
1913 const numeric lcm = lcm_of_coefficients_denominators(a);
1914 const ex tmp = multiply_lcm(a, lcm);
1917 epvector factors = sqrfree_yun(tmp, x);
1918 if (factors.empty()) {
1919 // the polynomial was a hidden zero
1923 // remove symbol x and proceed recursively with the remaining symbols
1924 args.remove_first();
1926 // recurse down the factors in remaining variables
1927 if (args.nops()>0) {
1928 for (auto & it : factors)
1929 it.rest = sqrfree(it.rest, args);
1932 // Done with recursion, now construct the final result
1933 ex result = mul(factors);
1935 // Put in the rational overall factor again and return
1936 return result * lcm.inverse();
1940 /** Compute square-free partial fraction decomposition of rational function
1943 * @param a rational function over Z[x], treated as univariate polynomial
1945 * @param x variable to factor in
1946 * @return decomposed rational function */
1947 ex sqrfree_parfrac(const ex & a, const symbol & x)
1949 // Find numerator and denominator
1950 ex nd = numer_denom(a);
1951 ex numer = nd.op(0), denom = nd.op(1);
1952 //std::clog << "numer = " << numer << ", denom = " << denom << std::endl;
1954 // Convert N(x)/D(x) -> Q(x) + R(x)/D(x), so degree(R) < degree(D)
1955 ex red_poly = quo(numer, denom, x), red_numer = rem(numer, denom, x).expand();
1956 //std::clog << "red_poly = " << red_poly << ", red_numer = " << red_numer << std::endl;
1958 // Factorize denominator and compute cofactors
1959 epvector yun = sqrfree_yun(denom, x);
1960 size_t yun_max_exponent = yun.empty() ? 0 : ex_to<numeric>(yun.back().coeff).to_int();
1961 exvector factor, cofac;
1962 for (size_t i=0; i<yun.size(); i++) {
1963 numeric i_exponent = ex_to<numeric>(yun[i].coeff);
1964 for (size_t j=0; j<i_exponent; j++) {
1965 factor.push_back(pow(yun[i].rest, j+1));
1967 for (size_t k=0; k<yun.size(); k++) {
1968 if (yun[k].coeff == i_exponent)
1969 prod *= pow(yun[k].rest, i_exponent-1-j);
1971 prod *= pow(yun[k].rest, yun[k].coeff);
1973 cofac.push_back(prod.expand());
1976 size_t num_factors = factor.size();
1977 //std::clog << "factors : " << exprseq(factor) << std::endl;
1978 //std::clog << "cofactors: " << exprseq(cofac) << std::endl;
1980 // Construct coefficient matrix for decomposition
1981 int max_denom_deg = denom.degree(x);
1982 matrix sys(max_denom_deg + 1, num_factors);
1983 matrix rhs(max_denom_deg + 1, 1);
1984 for (int i=0; i<=max_denom_deg; i++) {
1985 for (size_t j=0; j<num_factors; j++)
1986 sys(i, j) = cofac[j].coeff(x, i);
1987 rhs(i, 0) = red_numer.coeff(x, i);
1989 //std::clog << "coeffs: " << sys << std::endl;
1990 //std::clog << "rhs : " << rhs << std::endl;
1992 // Solve resulting linear system
1993 matrix vars(num_factors, 1);
1994 for (size_t i=0; i<num_factors; i++)
1995 vars(i, 0) = symbol();
1996 matrix sol = sys.solve(vars, rhs);
1998 // Sum up decomposed fractions
2000 for (size_t i=0; i<num_factors; i++)
2001 sum += sol(i, 0) / factor[i];
2003 return red_poly + sum;
2008 * Normal form of rational functions
2012 * Note: The internal normal() functions (= basic::normal() and overloaded
2013 * functions) all return lists of the form {numerator, denominator}. This
2014 * is to get around mul::eval()'s automatic expansion of numeric coefficients.
2015 * E.g. (a+b)/3 is automatically converted to a/3+b/3 but we want to keep
2016 * the information that (a+b) is the numerator and 3 is the denominator.
2020 /** Create a symbol for replacing the expression "e" (or return a previously
2021 * assigned symbol). The symbol and expression are appended to repl, for
2022 * a later application of subs().
2023 * An entry in the replacement table repl can be changed in some cases.
2024 * If it was altered, we need to provide the modifier for the previously build expressions.
2025 * The modifier is an (ordered) list, because those substitutions need to be done in the
2026 * incremental order.
2027 * As an example let us consider a rationalisation of the expression
2028 * e = exp(2*x)*cos(exp(2*x)+1)*exp(x)
2029 * The first factor GiNaC denotes by something like symbol1 and will record:
2030 * e =symbol1*cos(symbol1 + 1)*exp(x)
2031 * repl = {symbol1 : exp(2*x)}
2032 * Similarly, the second factor would be denoted as symbol2 and we will have
2033 * e =symbol1*symbol2*exp(x)
2034 * repl = {symbol1 : exp(2*x), symbol2 : cos(symbol1 + 1)}
2035 * Denoting the third term as symbol3 GiNaC is willing to re-think exp(2*x) as
2036 * symbol3^2 rather than just symbol1. Here are two issues:
2037 * 1) The replacement "symbol1 -> symbol3^2" in the previous part of the expression
2038 * needs to be done outside of the present routine;
2039 * 2) The pair "symbol1 : exp(2*x)" shall be deleted from the replacement table repl.
2040 * However, this will create illegal substitution "symbol2 : cos(symbol1 + 1)" with
2041 * undefined symbol1.
2042 * These both problems are mitigated through the additions of the record
2043 * "symbol1==symbol3^2" to the list modifier. Changed length of the modifier signals
2044 * to the calling code that the previous portion of the expression needs to be
2045 * altered (it solves 1). Thus GiNaC can record now
2046 * e =symbol3^2*symbol2*symbol3
2047 * repl = {symbol2 : cos(symbol1 + 1), symbol3 : exp(x)}
2048 * modifier = {symbol1==symbol3^2}
2049 * Then, doing the backward substitutions the list modifier will be used to restore
2050 * such iterative substitutions in the right way (this solves 2).
2051 * @see ex::normal */
2052 static ex replace_with_symbol(const ex & e, exmap & repl, exmap & rev_lookup, lst & modifier)
2054 // Since the repl contains replaced expressions we should search for them
2055 ex e_replaced = e.subs(repl, subs_options::no_pattern);
2057 // Expression already replaced? Then return the assigned symbol
2058 auto it = rev_lookup.find(e_replaced);
2059 if (it != rev_lookup.end())
2062 // The expression can be the base of substituted power, which requires a more careful search
2063 if (! is_a<numeric>(e_replaced))
2064 for (auto & it : repl)
2065 if (is_a<power>(it.second) && e_replaced.is_equal(it.second.op(0))) {
2066 ex degree = pow(it.second.op(1), _ex_1);
2067 if (is_a<numeric>(degree) && ex_to<numeric>(degree).is_integer())
2068 return pow(it.first, degree);
2071 // We treat powers and the exponent functions differently because
2072 // they can be rationalised more efficiently
2073 if (is_a<function>(e_replaced) && is_ex_the_function(e_replaced, exp)) {
2074 for (auto & it : repl) {
2075 if (is_a<function>(it.second) && is_ex_the_function(it.second, exp)) {
2076 ex ratio = normal(e_replaced.op(0) / it.second.op(0));
2077 if (is_a<numeric>(ratio) && ex_to<numeric>(ratio).is_rational()) {
2078 // Different exponents can be treated as powers of the same basic equation
2079 if (ex_to<numeric>(ratio).is_integer()) {
2080 // If ratio is an integer then this is simply the power of the existing symbol.
2081 // std::clog << e_replaced << " is a " << ratio << " power of " << it.first << std::endl;
2082 return dynallocate<power>(it.first, ratio);
2084 // otherwise we need to give the replacement pattern to change
2085 // the previous expression...
2086 ex es = dynallocate<symbol>();
2087 ex Num = numer(ratio);
2088 modifier.append(it.first == power(es, denom(ratio)));
2089 // std::clog << e_replaced << " is power " << Num << " and "
2090 // << it.first << " is power " << denom(ratio) << " of the common base "
2091 // << exp(e_replaced.op(0)/Num) << std::endl;
2092 // ... and modify the replacement tables
2093 rev_lookup.erase(it.second);
2094 rev_lookup.insert({exp(e_replaced.op(0)/Num), es});
2095 repl.erase(it.first);
2096 repl.insert({es, exp(e_replaced.op(0)/Num)});
2097 return dynallocate<power>(es, Num);
2102 } else if (is_a<power>(e_replaced) && !is_a<numeric>(e_replaced.op(0)) // We do not replace simple monomials like x^3 or sqrt(2)
2103 && ! (is_a<symbol>(e_replaced.op(0))
2104 && is_a<numeric>(e_replaced.op(1)) && ex_to<numeric>(e_replaced.op(1)).is_integer())) {
2105 for (auto & it : repl) {
2106 if (e_replaced.op(0).is_equal(it.second) // The base is an allocated symbol or base of power
2107 || (is_a<power>(it.second) && e_replaced.op(0).is_equal(it.second.op(0)))) {
2108 ex ratio; // We bind together two above cases
2109 if (is_a<power>(it.second))
2110 ratio = normal(e_replaced.op(1) / it.second.op(1));
2112 ratio = e_replaced.op(1);
2113 if (is_a<numeric>(ratio) && ex_to<numeric>(ratio).is_rational()) {
2114 // Different powers can be treated as powers of the same basic equation
2115 if (ex_to<numeric>(ratio).is_integer()) {
2116 // If ratio is an integer then this is simply the power of the existing symbol.
2117 //std::clog << e_replaced << " is a " << ratio << " power of " << it.first << std::endl;
2118 return dynallocate<power>(it.first, ratio);
2120 // otherwise we need to give the replacement pattern to change
2121 // the previous expression...
2122 ex es = dynallocate<symbol>();
2123 ex Num = numer(ratio);
2124 modifier.append(it.first == power(es, denom(ratio)));
2125 //std::clog << e_replaced << " is power " << Num << " and "
2126 // << it.first << " is power " << denom(ratio) << " of the common base "
2127 // << pow(e_replaced.op(0), e_replaced.op(1)/Num) << std::endl;
2128 // ... and modify the replacement tables
2129 rev_lookup.erase(it.second);
2130 rev_lookup.insert({pow(e_replaced.op(0), e_replaced.op(1)/Num), es});
2131 repl.erase(it.first);
2132 repl.insert({es, pow(e_replaced.op(0), e_replaced.op(1)/Num)});
2133 return dynallocate<power>(es, Num);
2138 // There is no existing substitution, thus we are creating a new one.
2139 // This needs to be done separately to treat possible occurrences of
2140 // b = e_replaced.op(0) elsewhere in the expression as pow(b, 1).
2141 ex degree = pow(e_replaced.op(1), _ex_1);
2142 if (is_a<numeric>(degree) && ex_to<numeric>(degree).is_integer()) {
2143 ex es = dynallocate<symbol>();
2144 modifier.append(e_replaced.op(0) == power(es, degree));
2145 repl.insert({es, e_replaced});
2146 rev_lookup.insert({e_replaced, es});
2151 // Otherwise create new symbol and add to list, taking care that the
2152 // replacement expression doesn't itself contain symbols from repl,
2153 // because subs() is not recursive
2154 ex es = dynallocate<symbol>();
2155 repl.insert(std::make_pair(es, e_replaced));
2156 rev_lookup.insert(std::make_pair(e_replaced, es));
2160 /** Create a symbol for replacing the expression "e" (or return a previously
2161 * assigned symbol). The symbol and expression are appended to repl, and the
2162 * symbol is returned.
2163 * @see basic::to_rational
2164 * @see basic::to_polynomial */
2165 static ex replace_with_symbol(const ex & e, exmap & repl)
2167 // Since the repl contains replaced expressions we should search for them
2168 ex e_replaced = e.subs(repl, subs_options::no_pattern);
2170 // Expression already replaced? Then return the assigned symbol
2171 for (auto & it : repl)
2172 if (it.second.is_equal(e_replaced))
2175 // Otherwise create new symbol and add to list, taking care that the
2176 // replacement expression doesn't itself contain symbols from repl,
2177 // because subs() is not recursive
2178 ex es = dynallocate<symbol>();
2179 repl.insert(std::make_pair(es, e_replaced));
2184 /** Function object to be applied by basic::normal(). */
2185 struct normal_map_function : public map_function {
2186 ex operator()(const ex & e) override { return normal(e); }
2189 /** Default implementation of ex::normal(). It normalizes the children and
2190 * replaces the object with a temporary symbol.
2191 * @see ex::normal */
2192 ex basic::normal(exmap & repl, exmap & rev_lookup, lst & modifier) const
2195 return dynallocate<lst>({replace_with_symbol(*this, repl, rev_lookup, modifier), _ex1});
2197 normal_map_function map_normal;
2198 int nmod = modifier.nops(); // To watch new modifiers to the replacement list
2199 ex result = replace_with_symbol(map(map_normal), repl, rev_lookup, modifier);
2200 for (int imod = nmod; imod < modifier.nops(); ++imod) {
2202 this_repl.insert(std::make_pair(modifier.op(imod).op(0), modifier.op(imod).op(1)));
2203 result = result.subs(this_repl, subs_options::no_pattern);
2206 // Sometimes we may obtain negative powers, they need to be placed to denominator
2207 if (is_a<power>(result) && result.op(1).info(info_flags::negative))
2208 return dynallocate<lst>({_ex1, power(result.op(0), -result.op(1))});
2210 return dynallocate<lst>({result, _ex1});
2214 /** Implementation of ex::normal() for symbols. This returns the unmodified symbol.
2215 * @see ex::normal */
2216 ex symbol::normal(exmap & repl, exmap & rev_lookup, lst & modifier) const
2218 return dynallocate<lst>({*this, _ex1});
2222 /** Implementation of ex::normal() for a numeric. It splits complex numbers
2223 * into re+I*im and replaces I and non-rational real numbers with a temporary
2225 * @see ex::normal */
2226 ex numeric::normal(exmap & repl, exmap & rev_lookup, lst & modifier) const
2228 numeric num = numer();
2231 if (num.is_real()) {
2232 if (!num.is_integer())
2233 numex = replace_with_symbol(numex, repl, rev_lookup, modifier);
2235 numeric re = num.real(), im = num.imag();
2236 ex re_ex = re.is_rational() ? re : replace_with_symbol(re, repl, rev_lookup, modifier);
2237 ex im_ex = im.is_rational() ? im : replace_with_symbol(im, repl, rev_lookup, modifier);
2238 numex = re_ex + im_ex * replace_with_symbol(I, repl, rev_lookup, modifier);
2241 // Denominator is always a real integer (see numeric::denom())
2242 return dynallocate<lst>({numex, denom()});
2246 /** Fraction cancellation.
2247 * @param n numerator
2248 * @param d denominator
2249 * @return cancelled fraction {n, d} as a list */
2250 static ex frac_cancel(const ex &n, const ex &d)
2254 numeric pre_factor = *_num1_p;
2256 //std::clog << "frac_cancel num = " << num << ", den = " << den << std::endl;
2258 // Handle trivial case where denominator is 1
2259 if (den.is_equal(_ex1))
2260 return dynallocate<lst>({num, den});
2262 // Handle special cases where numerator or denominator is 0
2264 return dynallocate<lst>({num, _ex1});
2265 if (den.expand().is_zero())
2266 throw(std::overflow_error("frac_cancel: division by zero in frac_cancel"));
2268 // Bring numerator and denominator to Z[X] by multiplying with
2269 // LCM of all coefficients' denominators
2270 numeric num_lcm = lcm_of_coefficients_denominators(num);
2271 numeric den_lcm = lcm_of_coefficients_denominators(den);
2272 num = multiply_lcm(num, num_lcm);
2273 den = multiply_lcm(den, den_lcm);
2274 pre_factor = den_lcm / num_lcm;
2276 // Cancel GCD from numerator and denominator
2278 if (gcd(num, den, &cnum, &cden, false) != _ex1) {
2283 // Make denominator unit normal (i.e. coefficient of first symbol
2284 // as defined by get_first_symbol() is made positive)
2285 if (is_exactly_a<numeric>(den)) {
2286 if (ex_to<numeric>(den).is_negative()) {
2292 if (get_first_symbol(den, x)) {
2293 GINAC_ASSERT(is_exactly_a<numeric>(den.unit(x)));
2294 if (ex_to<numeric>(den.unit(x)).is_negative()) {
2301 // Return result as list
2302 //std::clog << " returns num = " << num << ", den = " << den << ", pre_factor = " << pre_factor << std::endl;
2303 return dynallocate<lst>({num * pre_factor.numer(), den * pre_factor.denom()});
2307 /** Implementation of ex::normal() for a sum. It expands terms and performs
2308 * fractional addition.
2309 * @see ex::normal */
2310 ex add::normal(exmap & repl, exmap & rev_lookup, lst & modifier) const
2312 // Normalize children and split each one into numerator and denominator
2313 exvector nums, dens;
2314 nums.reserve(seq.size()+1);
2315 dens.reserve(seq.size()+1);
2316 int nmod = modifier.nops(); // To watch new modifiers to the replacement list
2317 for (auto & it : seq) {
2318 ex n = ex_to<basic>(recombine_pair_to_ex(it)).normal(repl, rev_lookup, modifier);
2319 nums.push_back(n.op(0));
2320 dens.push_back(n.op(1));
2322 ex n = ex_to<numeric>(overall_coeff).normal(repl, rev_lookup, modifier);
2323 nums.push_back(n.op(0));
2324 dens.push_back(n.op(1));
2325 GINAC_ASSERT(nums.size() == dens.size());
2327 // Now, nums is a vector of all numerators and dens is a vector of
2329 //std::clog << "add::normal uses " << nums.size() << " summands:\n";
2331 // Add fractions sequentially
2332 auto num_it = nums.begin(), num_itend = nums.end();
2333 auto den_it = dens.begin(), den_itend = dens.end();
2334 //std::clog << " num = " << *num_it << ", den = " << *den_it << std::endl;
2335 for (int imod = nmod; imod < modifier.nops(); ++imod) {
2336 while (num_it != num_itend) {
2337 *num_it = num_it->subs(modifier.op(imod), subs_options::no_pattern);
2339 *den_it = den_it->subs(modifier.op(imod), subs_options::no_pattern);
2342 // Reset iterators for the next round
2343 num_it = nums.begin();
2344 den_it = dens.begin();
2347 ex num = *num_it++, den = *den_it++;
2348 while (num_it != num_itend) {
2349 //std::clog << " num = " << *num_it << ", den = " << *den_it << std::endl;
2350 ex next_num = *num_it++, next_den = *den_it++;
2352 // Trivially add sequences of fractions with identical denominators
2353 while ((den_it != den_itend) && next_den.is_equal(*den_it)) {
2354 next_num += *num_it;
2358 // Addition of two fractions, taking advantage of the fact that
2359 // the heuristic GCD algorithm computes the cofactors at no extra cost
2360 ex co_den1, co_den2;
2361 ex g = gcd(den, next_den, &co_den1, &co_den2, false);
2362 num = ((num * co_den2) + (next_num * co_den1)).expand();
2363 den *= co_den2; // this is the lcm(den, next_den)
2365 //std::clog << " common denominator = " << den << std::endl;
2367 // Cancel common factors from num/den
2368 return frac_cancel(num, den);
2372 /** Implementation of ex::normal() for a product. It cancels common factors
2374 * @see ex::normal() */
2375 ex mul::normal(exmap & repl, exmap & rev_lookup, lst & modifier) const
2377 // Normalize children, separate into numerator and denominator
2378 exvector num; num.reserve(seq.size());
2379 exvector den; den.reserve(seq.size());
2381 int nmod = modifier.nops(); // To watch new modifiers to the replacement list
2382 for (auto & it : seq) {
2383 n = ex_to<basic>(recombine_pair_to_ex(it)).normal(repl, rev_lookup, modifier);
2384 num.push_back(n.op(0));
2385 den.push_back(n.op(1));
2387 n = ex_to<numeric>(overall_coeff).normal(repl, rev_lookup, modifier);
2388 num.push_back(n.op(0));
2389 den.push_back(n.op(1));
2390 auto num_it = num.begin(), num_itend = num.end();
2391 auto den_it = den.begin(), den_itend = den.end();
2392 for (int imod = nmod; imod < modifier.nops(); ++imod) {
2393 while (num_it != num_itend) {
2394 *num_it = num_it->subs(modifier.op(imod), subs_options::no_pattern);
2396 *den_it = den_it->subs(modifier.op(imod), subs_options::no_pattern);
2399 num_it = num.begin();
2400 den_it = den.begin();
2403 // Perform fraction cancellation
2404 return frac_cancel(dynallocate<mul>(num), dynallocate<mul>(den));
2408 /** Implementation of ex::normal() for powers. It normalizes the basis,
2409 * distributes integer exponents to numerator and denominator, and replaces
2410 * non-integer powers by temporary symbols.
2411 * @see ex::normal */
2412 ex power::normal(exmap & repl, exmap & rev_lookup, lst & modifier) const
2414 // Normalize basis and exponent (exponent gets reassembled)
2415 int nmod = modifier.nops(); // To watch new modifiers to the replacement list
2416 ex n_basis = ex_to<basic>(basis).normal(repl, rev_lookup, modifier);
2417 for (int imod = nmod; imod < modifier.nops(); ++imod)
2418 n_basis = n_basis.subs(modifier.op(imod), subs_options::no_pattern);
2420 nmod = modifier.nops();
2421 ex n_exponent = ex_to<basic>(exponent).normal(repl, rev_lookup, modifier);
2422 for (int imod = nmod; imod < modifier.nops(); ++imod)
2423 n_exponent = n_exponent.subs(modifier.op(imod), subs_options::no_pattern);
2424 n_exponent = n_exponent.op(0) / n_exponent.op(1);
2426 if (n_exponent.info(info_flags::integer)) {
2428 if (n_exponent.info(info_flags::positive)) {
2430 // (a/b)^n -> {a^n, b^n}
2431 return dynallocate<lst>({pow(n_basis.op(0), n_exponent), pow(n_basis.op(1), n_exponent)});
2433 } else if (n_exponent.info(info_flags::negative)) {
2435 // (a/b)^-n -> {b^n, a^n}
2436 return dynallocate<lst>({pow(n_basis.op(1), -n_exponent), pow(n_basis.op(0), -n_exponent)});
2441 if (n_exponent.info(info_flags::positive)) {
2443 // (a/b)^x -> {sym((a/b)^x), 1}
2444 return dynallocate<lst>({replace_with_symbol(pow(n_basis.op(0) / n_basis.op(1), n_exponent), repl, rev_lookup, modifier), _ex1});
2446 } else if (n_exponent.info(info_flags::negative)) {
2448 if (n_basis.op(1).is_equal(_ex1)) {
2450 // a^-x -> {1, sym(a^x)}
2451 return dynallocate<lst>({_ex1, replace_with_symbol(pow(n_basis.op(0), -n_exponent), repl, rev_lookup, modifier)});
2455 // (a/b)^-x -> {sym((b/a)^x), 1}
2456 return dynallocate<lst>({replace_with_symbol(pow(n_basis.op(1) / n_basis.op(0), -n_exponent), repl, rev_lookup, modifier), _ex1});
2461 // (a/b)^x -> {sym((a/b)^x, 1}
2462 return dynallocate<lst>({replace_with_symbol(pow(n_basis.op(0) / n_basis.op(1), n_exponent), repl, rev_lookup, modifier), _ex1});
2466 /** Implementation of ex::normal() for pseries. It normalizes each coefficient
2467 * and replaces the series by a temporary symbol.
2468 * @see ex::normal */
2469 ex pseries::normal(exmap & repl, exmap & rev_lookup, lst & modifier) const
2472 for (auto & it : seq) {
2473 ex restexp = it.rest.normal();
2474 if (!restexp.is_zero())
2475 newseq.push_back(expair(restexp, it.coeff));
2477 ex n = pseries(relational(var,point), std::move(newseq));
2478 return dynallocate<lst>({replace_with_symbol(n, repl, rev_lookup, modifier), _ex1});
2482 /** Normalization of rational functions.
2483 * This function converts an expression to its normal form
2484 * "numerator/denominator", where numerator and denominator are (relatively
2485 * prime) polynomials. Any subexpressions which are not rational functions
2486 * (like non-rational numbers, non-integer powers or functions like sin(),
2487 * cos() etc.) are replaced by temporary symbols which are re-substituted by
2488 * the (normalized) subexpressions before normal() returns (this way, any
2489 * expression can be treated as a rational function). normal() is applied
2490 * recursively to arguments of functions etc.
2492 * @return normalized expression */
2493 ex ex::normal() const
2495 exmap repl, rev_lookup;
2498 ex e = bp->normal(repl, rev_lookup, modifier);
2499 GINAC_ASSERT(is_a<lst>(e));
2501 // Re-insert replaced symbols
2502 if (!repl.empty()) {
2503 for(int i=0; i < modifier.nops(); ++i)
2504 e = e.subs(modifier.op(i), subs_options::no_pattern);
2505 e = e.subs(repl, subs_options::no_pattern);
2508 // Convert {numerator, denominator} form back to fraction
2509 return e.op(0) / e.op(1);
2512 /** Get numerator of an expression. If the expression is not of the normal
2513 * form "numerator/denominator", it is first converted to this form and
2514 * then the numerator is returned.
2517 * @return numerator */
2518 ex ex::numer() const
2520 exmap repl, rev_lookup;
2523 ex e = bp->normal(repl, rev_lookup, modifier);
2524 GINAC_ASSERT(is_a<lst>(e));
2526 // Re-insert replaced symbols
2530 for(int i=0; i < modifier.nops(); ++i)
2531 e = e.subs(modifier.op(i), subs_options::no_pattern);
2533 return e.op(0).subs(repl, subs_options::no_pattern);
2537 /** Get denominator of an expression. If the expression is not of the normal
2538 * form "numerator/denominator", it is first converted to this form and
2539 * then the denominator is returned.
2542 * @return denominator */
2543 ex ex::denom() const
2545 exmap repl, rev_lookup;
2548 ex e = bp->normal(repl, rev_lookup, modifier);
2549 GINAC_ASSERT(is_a<lst>(e));
2551 // Re-insert replaced symbols
2555 for(int i=0; i < modifier.nops(); ++i)
2556 e = e.subs(modifier.op(i), subs_options::no_pattern);
2558 return e.op(1).subs(repl, subs_options::no_pattern);
2562 /** Get numerator and denominator of an expression. If the expression is not
2563 * of the normal form "numerator/denominator", it is first converted to this
2564 * form and then a list [numerator, denominator] is returned.
2567 * @return a list [numerator, denominator] */
2568 ex ex::numer_denom() const
2570 exmap repl, rev_lookup;
2573 ex e = bp->normal(repl, rev_lookup, modifier);
2574 GINAC_ASSERT(is_a<lst>(e));
2576 // Re-insert replaced symbols
2580 for(int i=0; i < modifier.nops(); ++i)
2581 e = e.subs(modifier.op(i), subs_options::no_pattern);
2583 return e.subs(repl, subs_options::no_pattern);
2588 /** Rationalization of non-rational functions.
2589 * This function converts a general expression to a rational function
2590 * by replacing all non-rational subexpressions (like non-rational numbers,
2591 * non-integer powers or functions like sin(), cos() etc.) to temporary
2592 * symbols. This makes it possible to use functions like gcd() and divide()
2593 * on non-rational functions by applying to_rational() on the arguments,
2594 * calling the desired function and re-substituting the temporary symbols
2595 * in the result. To make the last step possible, all temporary symbols and
2596 * their associated expressions are collected in the map specified by the
2597 * repl parameter, ready to be passed as an argument to ex::subs().
2599 * @param repl collects all temporary symbols and their replacements
2600 * @return rationalized expression */
2601 ex ex::to_rational(exmap & repl) const
2603 return bp->to_rational(repl);
2606 ex ex::to_polynomial(exmap & repl) const
2608 return bp->to_polynomial(repl);
2611 /** Default implementation of ex::to_rational(). This replaces the object with
2612 * a temporary symbol. */
2613 ex basic::to_rational(exmap & repl) const
2615 return replace_with_symbol(*this, repl);
2618 ex basic::to_polynomial(exmap & repl) const
2620 return replace_with_symbol(*this, repl);
2624 /** Implementation of ex::to_rational() for symbols. This returns the
2625 * unmodified symbol. */
2626 ex symbol::to_rational(exmap & repl) const
2631 /** Implementation of ex::to_polynomial() for symbols. This returns the
2632 * unmodified symbol. */
2633 ex symbol::to_polynomial(exmap & repl) const
2639 /** Implementation of ex::to_rational() for a numeric. It splits complex
2640 * numbers into re+I*im and replaces I and non-rational real numbers with a
2641 * temporary symbol. */
2642 ex numeric::to_rational(exmap & repl) const
2646 return replace_with_symbol(*this, repl);
2648 numeric re = real();
2649 numeric im = imag();
2650 ex re_ex = re.is_rational() ? re : replace_with_symbol(re, repl);
2651 ex im_ex = im.is_rational() ? im : replace_with_symbol(im, repl);
2652 return re_ex + im_ex * replace_with_symbol(I, repl);
2657 /** Implementation of ex::to_polynomial() for a numeric. It splits complex
2658 * numbers into re+I*im and replaces I and non-integer real numbers with a
2659 * temporary symbol. */
2660 ex numeric::to_polynomial(exmap & repl) const
2664 return replace_with_symbol(*this, repl);
2666 numeric re = real();
2667 numeric im = imag();
2668 ex re_ex = re.is_integer() ? re : replace_with_symbol(re, repl);
2669 ex im_ex = im.is_integer() ? im : replace_with_symbol(im, repl);
2670 return re_ex + im_ex * replace_with_symbol(I, repl);
2676 /** Implementation of ex::to_rational() for powers. It replaces non-integer
2677 * powers by temporary symbols. */
2678 ex power::to_rational(exmap & repl) const
2680 if (exponent.info(info_flags::integer))
2681 return pow(basis.to_rational(repl), exponent);
2683 return replace_with_symbol(*this, repl);
2686 /** Implementation of ex::to_polynomial() for powers. It replaces non-posint
2687 * powers by temporary symbols. */
2688 ex power::to_polynomial(exmap & repl) const
2690 if (exponent.info(info_flags::posint))
2691 return pow(basis.to_polynomial(repl), exponent);
2692 else if (exponent.info(info_flags::negint))
2694 ex basis_pref = collect_common_factors(basis);
2695 if (is_exactly_a<mul>(basis_pref) || is_exactly_a<power>(basis_pref)) {
2696 // (A*B)^n will be automagically transformed to A^n*B^n
2697 ex t = pow(basis_pref, exponent);
2698 return t.to_polynomial(repl);
2701 return pow(replace_with_symbol(pow(basis, _ex_1), repl), -exponent);
2704 return replace_with_symbol(*this, repl);
2708 /** Implementation of ex::to_rational() for expairseqs. */
2709 ex expairseq::to_rational(exmap & repl) const
2712 s.reserve(seq.size());
2713 for (auto & it : seq)
2714 s.push_back(split_ex_to_pair(recombine_pair_to_ex(it).to_rational(repl)));
2716 ex oc = overall_coeff.to_rational(repl);
2717 if (oc.info(info_flags::numeric))
2718 return thisexpairseq(std::move(s), overall_coeff);
2720 s.push_back(expair(oc, _ex1));
2721 return thisexpairseq(std::move(s), default_overall_coeff());
2724 /** Implementation of ex::to_polynomial() for expairseqs. */
2725 ex expairseq::to_polynomial(exmap & repl) const
2728 s.reserve(seq.size());
2729 for (auto & it : seq)
2730 s.push_back(split_ex_to_pair(recombine_pair_to_ex(it).to_polynomial(repl)));
2732 ex oc = overall_coeff.to_polynomial(repl);
2733 if (oc.info(info_flags::numeric))
2734 return thisexpairseq(std::move(s), overall_coeff);
2736 s.push_back(expair(oc, _ex1));
2737 return thisexpairseq(std::move(s), default_overall_coeff());
2741 /** Remove the common factor in the terms of a sum 'e' by calculating the GCD,
2742 * and multiply it into the expression 'factor' (which needs to be initialized
2743 * to 1, unless you're accumulating factors). */
2744 static ex find_common_factor(const ex & e, ex & factor, exmap & repl)
2746 if (is_exactly_a<add>(e)) {
2748 size_t num = e.nops();
2749 exvector terms; terms.reserve(num);
2752 // Find the common GCD
2753 for (size_t i=0; i<num; i++) {
2754 ex x = e.op(i).to_polynomial(repl);
2756 if (is_exactly_a<add>(x) || is_exactly_a<mul>(x) || is_a<power>(x)) {
2758 x = find_common_factor(x, f, repl);
2770 if (gc.is_equal(_ex1))
2776 // The GCD is the factor we pull out
2779 // Now divide all terms by the GCD
2780 for (size_t i=0; i<num; i++) {
2783 // Try to avoid divide() because it expands the polynomial
2785 if (is_exactly_a<mul>(t)) {
2786 for (size_t j=0; j<t.nops(); j++) {
2787 if (t.op(j).is_equal(gc)) {
2788 exvector v; v.reserve(t.nops());
2789 for (size_t k=0; k<t.nops(); k++) {
2793 v.push_back(t.op(k));
2795 t = dynallocate<mul>(v);
2805 return dynallocate<add>(terms);
2807 } else if (is_exactly_a<mul>(e)) {
2809 size_t num = e.nops();
2810 exvector v; v.reserve(num);
2812 for (size_t i=0; i<num; i++)
2813 v.push_back(find_common_factor(e.op(i), factor, repl));
2815 return dynallocate<mul>(v);
2817 } else if (is_exactly_a<power>(e)) {
2818 const ex e_exp(e.op(1));
2819 if (e_exp.info(info_flags::integer)) {
2820 ex eb = e.op(0).to_polynomial(repl);
2821 ex factor_local(_ex1);
2822 ex pre_res = find_common_factor(eb, factor_local, repl);
2823 factor *= pow(factor_local, e_exp);
2824 return pow(pre_res, e_exp);
2827 return e.to_polynomial(repl);
2834 /** Collect common factors in sums. This converts expressions like
2835 * 'a*(b*x+b*y)' to 'a*b*(x+y)'. */
2836 ex collect_common_factors(const ex & e)
2838 if (is_exactly_a<add>(e) || is_exactly_a<mul>(e) || is_exactly_a<power>(e)) {
2842 ex r = find_common_factor(e, factor, repl);
2843 return factor.subs(repl, subs_options::no_pattern) * r.subs(repl, subs_options::no_pattern);
2850 /** Resultant of two expressions e1,e2 with respect to symbol s.
2851 * Method: Compute determinant of Sylvester matrix of e1,e2,s. */
2852 ex resultant(const ex & e1, const ex & e2, const ex & s)
2854 const ex ee1 = e1.expand();
2855 const ex ee2 = e2.expand();
2856 if (!ee1.info(info_flags::polynomial) ||
2857 !ee2.info(info_flags::polynomial))
2858 throw(std::runtime_error("resultant(): arguments must be polynomials"));
2860 const int h1 = ee1.degree(s);
2861 const int l1 = ee1.ldegree(s);
2862 const int h2 = ee2.degree(s);
2863 const int l2 = ee2.ldegree(s);
2865 const int msize = h1 + h2;
2866 matrix m(msize, msize);
2868 for (int l = h1; l >= l1; --l) {
2869 const ex e = ee1.coeff(s, l);
2870 for (int k = 0; k < h2; ++k)
2873 for (int l = h2; l >= l2; --l) {
2874 const ex e = ee2.coeff(s, l);
2875 for (int k = 0; k < h1; ++k)
2876 m(k+h2, k+h2-l) = e;
2879 return m.determinant();
2883 } // namespace GiNaC