]> www.ginac.de Git - ginac.git/blob - ginac/normal.cpp
81841e0f7f847de7d8e706d3a74deb1744ac3852
[ginac.git] / ginac / normal.cpp
1 /** @file normal.cpp
2  *
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. */
7
8 /*
9  *  GiNaC Copyright (C) 1999-2016 Johannes Gutenberg University Mainz, Germany
10  *
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.
15  *
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.
20  *
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
24  */
25
26 #include "normal.h"
27 #include "basic.h"
28 #include "ex.h"
29 #include "add.h"
30 #include "constant.h"
31 #include "expairseq.h"
32 #include "fail.h"
33 #include "inifcns.h"
34 #include "lst.h"
35 #include "mul.h"
36 #include "numeric.h"
37 #include "power.h"
38 #include "relational.h"
39 #include "operators.h"
40 #include "matrix.h"
41 #include "pseries.h"
42 #include "symbol.h"
43 #include "utils.h"
44 #include "polynomial/chinrem_gcd.h"
45
46 #include <algorithm>
47 #include <map>
48
49 namespace GiNaC {
50
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
55
56 // Set this if you want divide_in_z() to use remembering
57 #define USE_REMEMBER 0
58
59 // Set this if you want divide_in_z() to use trial division followed by
60 // polynomial interpolation (always slower except for completely dense
61 // polynomials)
62 #define USE_TRIAL_DIVISION 0
63
64 // Set this to enable some statistical output for the GCD routines
65 #define STATISTICS 0
66
67
68 #if STATISTICS
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;
74
75 // Print statistics at end of program
76 static struct _stat_print {
77         _stat_print() {}
78         ~_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";
83         }
84 } stat_print;
85 #endif
86
87
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.
91  *
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)
96 {
97         if (is_a<symbol>(e)) {
98                 x = e;
99                 return true;
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))
103                                 return true;
104         } else if (is_exactly_a<power>(e)) {
105                 if (get_first_symbol(e.op(0), x))
106                         return true;
107         }
108         return false;
109 }
110
111
112 /*
113  *  Statistical information about symbols in polynomials
114  */
115
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().
120  *
121  *  @see get_symbol_stats */
122 struct sym_desc {
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)
126         { }
127
128         /** Reference to symbol */
129         ex sym;
130
131         /** Highest degree of symbol in polynomial "a" */
132         int deg_a;
133
134         /** Highest degree of symbol in polynomial "b" */
135         int deg_b;
136
137         /** Lowest degree of symbol in polynomial "a" */
138         int ldeg_a;
139
140         /** Lowest degree of symbol in polynomial "b" */
141         int ldeg_b;
142
143         /** Maximum of deg_a and deg_b (Used for sorting) */
144         int max_deg;
145
146         /** Maximum number of terms of leading coefficient of symbol in both polynomials */
147         size_t max_lcnops;
148
149         /** Commparison operator for sorting */
150         bool operator<(const sym_desc &x) const
151         {
152                 if (max_deg == x.max_deg)
153                         return max_lcnops < x.max_lcnops;
154                 else
155                         return max_deg < x.max_deg;
156         }
157 };
158
159 // Vector of sym_desc structures
160 typedef std::vector<sym_desc> sym_desc_vec;
161
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)
164 {
165         for (auto & it : v)
166                 if (it.sym.is_equal(s))  // If it's already in there, don't add it a second time
167                         return;
168
169         v.push_back(sym_desc(s));
170 }
171
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)
174 {
175         if (is_a<symbol>(e)) {
176                 add_symbol(e, v);
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);
182         }
183 }
184
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.
193  *
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)
198 {
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);
204                 it.deg_a = deg_a;
205                 it.deg_b = deg_b;
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);
210         }
211         std::sort(v.begin(), v.end());
212
213 #if 0
214         std::clog << "Symbols:\n";
215         it = v.begin(); itend = v.end();
216         while (it != itend) {
217                 std::clog << " " << it->sym << ": deg_a=" << it->deg_a << ", deg_b=" << it->deg_b << ", ldeg_a=" << it->ldeg_a << ", ldeg_b=" << it->ldeg_b << ", max_deg=" << it->max_deg << ", max_lcnops=" << it->max_lcnops << endl;
218                 std::clog << "  lcoeff_a=" << a.lcoeff(it->sym) << ", lcoeff_b=" << b.lcoeff(it->sym) << endl;
219                 ++it;
220         }
221 #endif
222 }
223
224
225 /*
226  *  Computation of LCM of denominators of coefficients of a polynomial
227  */
228
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)
232 {
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);
239                 return lcm(c, l);
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);
244                 return lcm(c, l);
245         } else if (is_exactly_a<power>(e)) {
246                 if (is_a<symbol>(e.op(0)))
247                         return l;
248                 else
249                         return pow(lcmcoeff(e.op(0), l), ex_to<numeric>(e.op(1)));
250         }
251         return l;
252 }
253
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].
258  *
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)
262 {
263         return lcmcoeff(e, *_num1_p);
264 }
265
266 /** Bring polynomial from Q[X] to Z[X] by multiplying in the previously
267  *  determined LCM of the coefficient's denominators.
268  *
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)
272 {
273         if (lcm.is_equal(*_num1_p))
274                 // e * 1 -> e;
275                 return e;
276
277         if (is_exactly_a<mul>(e)) {
278                 // (a*b*...)*lcm -> (a*lcma)*(b*lcmb)*...*(lcm/(lcma*lcmb*...))
279                 size_t num = e.nops();
280                 exvector v;
281                 v.reserve(num + 1);
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));
286                         lcm_accum *= op_lcm;
287                 }
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();
293                 exvector v;
294                 v.reserve(num);
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));
305                 }
306         }
307         // can't recurse down into e
308         return dynallocate<mul>(e, lcm);
309 }
310
311
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.
316  *
317  *  @return integer content */
318 numeric ex::integer_content() const
319 {
320         return bp->integer_content();
321 }
322
323 numeric basic::integer_content() const
324 {
325         return *_num1_p;
326 }
327
328 numeric numeric::integer_content() const
329 {
330         return abs(*this);
331 }
332
333 numeric add::integer_content() const
334 {
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);
341         }
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);
345         return c/l;
346 }
347
348 numeric mul::integer_content() const
349 {
350 #ifdef DO_GINAC_ASSERT
351         for (auto & it : seq) {
352                 GINAC_ASSERT(!is_exactly_a<numeric>(recombine_pair_to_ex(it)));
353         }
354 #endif // def DO_GINAC_ASSERT
355         GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
356         return abs(ex_to<numeric>(overall_coeff));
357 }
358
359
360 /*
361  *  Polynomial quotients and remainders
362  */
363
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).
366  *
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)
374 {
375         if (b.is_zero())
376                 throw(std::overflow_error("quo: division by zero"));
377         if (is_exactly_a<numeric>(a) && is_exactly_a<numeric>(b))
378                 return a / b;
379 #if FAST_COMPARE
380         if (a.is_equal(b))
381                 return _ex1;
382 #endif
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"));
385
386         // Polynomial long division
387         ex r = a.expand();
388         if (r.is_zero())
389                 return r;
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;
399                 else {
400                         if (!divide(rcoeff, blcoeff, term, false))
401                                 return dynallocate<fail>();
402                 }
403                 term *= pow(x, rdeg - bdeg);
404                 v.push_back(term);
405                 r -= (term * b).expand();
406                 if (r.is_zero())
407                         break;
408                 rdeg = r.degree(x);
409         }
410         return dynallocate<add>(v);
411 }
412
413
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).
416  *
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)
424 {
425         if (b.is_zero())
426                 throw(std::overflow_error("rem: division by zero"));
427         if (is_exactly_a<numeric>(a)) {
428                 if  (is_exactly_a<numeric>(b))
429                         return _ex0;
430                 else
431                         return a;
432         }
433 #if FAST_COMPARE
434         if (a.is_equal(b))
435                 return _ex0;
436 #endif
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"));
439
440         // Polynomial long division
441         ex r = a.expand();
442         if (r.is_zero())
443                 return r;
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;
452                 else {
453                         if (!divide(rcoeff, blcoeff, term, false))
454                                 return dynallocate<fail>();
455                 }
456                 term *= pow(x, rdeg - bdeg);
457                 r -= (term * b).expand();
458                 if (r.is_zero())
459                         break;
460                 rdeg = r.degree(x);
461         }
462         return r;
463 }
464
465
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).
468  *
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)
473 {
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))
478                 return a;
479         else
480                 return q + rem(numer, denom, x) / denom;
481 }
482
483
484 /** Pseudo-remainder of polynomials a(x) and b(x) in Q[x].
485  *
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)
493 {
494         if (b.is_zero())
495                 throw(std::overflow_error("prem: division by zero"));
496         if (is_exactly_a<numeric>(a)) {
497                 if (is_exactly_a<numeric>(b))
498                         return _ex0;
499                 else
500                         return b;
501         }
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"));
504
505         // Polynomial long division
506         ex r = a.expand();
507         ex eb = b.expand();
508         int rdeg = r.degree(x);
509         int bdeg = eb.degree(x);
510         ex blcoeff;
511         if (bdeg <= rdeg) {
512                 blcoeff = eb.coeff(x, bdeg);
513                 if (bdeg == 0)
514                         eb = _ex0;
515                 else
516                         eb -= blcoeff * pow(x, bdeg);
517         } else
518                 blcoeff = _ex1;
519
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();
524                 if (rdeg == 0)
525                         r = _ex0;
526                 else
527                         r -= rlcoeff * pow(x, rdeg);
528                 r = (blcoeff * r).expand() - term;
529                 rdeg = r.degree(x);
530                 i++;
531         }
532         return pow(blcoeff, delta - i) * r;
533 }
534
535
536 /** Sparse pseudo-remainder of polynomials a(x) and b(x) in Q[x].
537  *
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)
545 {
546         if (b.is_zero())
547                 throw(std::overflow_error("prem: division by zero"));
548         if (is_exactly_a<numeric>(a)) {
549                 if (is_exactly_a<numeric>(b))
550                         return _ex0;
551                 else
552                         return b;
553         }
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"));
556
557         // Polynomial long division
558         ex r = a.expand();
559         ex eb = b.expand();
560         int rdeg = r.degree(x);
561         int bdeg = eb.degree(x);
562         ex blcoeff;
563         if (bdeg <= rdeg) {
564                 blcoeff = eb.coeff(x, bdeg);
565                 if (bdeg == 0)
566                         eb = _ex0;
567                 else
568                         eb -= blcoeff * pow(x, bdeg);
569         } else
570                 blcoeff = _ex1;
571
572         while (rdeg >= bdeg && !r.is_zero()) {
573                 ex rlcoeff = r.coeff(x, rdeg);
574                 ex term = (pow(x, rdeg - bdeg) * eb * rlcoeff).expand();
575                 if (rdeg == 0)
576                         r = _ex0;
577                 else
578                         r -= rlcoeff * pow(x, rdeg);
579                 r = (blcoeff * r).expand() - term;
580                 rdeg = r.degree(x);
581         }
582         return r;
583 }
584
585
586 /** Exact polynomial division of a(X) by b(X) in Q[X].
587  *  
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)
596 {
597         if (b.is_zero())
598                 throw(std::overflow_error("divide: division by zero"));
599         if (a.is_zero()) {
600                 q = _ex0;
601                 return true;
602         }
603         if (is_exactly_a<numeric>(b)) {
604                 q = a / b;
605                 return true;
606         } else if (is_exactly_a<numeric>(a))
607                 return false;
608 #if FAST_COMPARE
609         if (a.is_equal(b)) {
610                 q = _ex1;
611                 return true;
612         }
613 #endif
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"));
617
618         // Find first symbol
619         ex x;
620         if (!get_first_symbol(a, x) && !get_first_symbol(b, x))
621                 throw(std::invalid_argument("invalid expression in divide()"));
622
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))
629                                 return false;
630                         rem_old = rem_new;
631                 }
632                 q = rem_new;
633                 return true;
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))
640                                 return false;
641                         rem_old = rem_new;
642                 }
643                 q = rem_new;
644                 return true;
645         } 
646         
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.
650                 size_t i;
651                 ex rem_i;
652                 bool divisible_p = false;
653                 for (i=0; i < a.nops(); ++i) {
654                         if (divide(a.op(i), b, rem_i, false)) {
655                                 divisible_p = true;
656                                 break;
657                         }
658                 }
659                 if (divisible_p) {
660                         exvector resv;
661                         resv.reserve(a.nops());
662                         for (size_t j=0; j < a.nops(); j++) {
663                                 if (j==i)
664                                         resv.push_back(rem_i);
665                                 else
666                                         resv.push_back(a.op(j));
667                         }
668                         q = dynallocate<mul>(resv);
669                         return true;
670                 }
671         } else if (is_exactly_a<power>(a)) {
672                 // The base itself might be divisible by b, in that case we don't
673                 // need to expand a
674                 const ex& ab(a.op(0));
675                 int a_exp = ex_to<numeric>(a.op(1)).to_int();
676                 ex rem_i;
677                 if (divide(ab, b, rem_i, false)) {
678                         q = rem_i * pow(ab, a_exp - 1);
679                         return true;
680                 }
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);
685 //                              return true;
686 //                      }
687 //              } // ... so we *really* need to expand expression.
688         }
689         
690         // Polynomial long division (recursive)
691         ex r = a.expand();
692         if (r.is_zero()) {
693                 q = _ex0;
694                 return true;
695         }
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;
705                 else
706                         if (!divide(rcoeff, blcoeff, term, false))
707                                 return false;
708                 term *= pow(x, rdeg - bdeg);
709                 v.push_back(term);
710                 r -= (term * b).expand();
711                 if (r.is_zero()) {
712                         q = dynallocate<add>(v);
713                         return true;
714                 }
715                 rdeg = r.degree(x);
716         }
717         return false;
718 }
719
720
721 #if USE_REMEMBER
722 /*
723  *  Remembering
724  */
725
726 typedef std::pair<ex, ex> ex2;
727 typedef std::pair<ex, bool> exbool;
728
729 struct ex2_less {
730         bool operator() (const ex2 &p, const ex2 &q) const 
731         {
732                 int cmp = p.first.compare(q.first);
733                 return ((cmp<0) || (!(cmp>0) && p.second.compare(q.second)<0));
734         }
735 };
736
737 typedef std::map<ex2, exbool, ex2_less> ex2_exbool_remember;
738 #endif
739
740
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().
749  *  
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)
758 {
759         q = _ex0;
760         if (b.is_zero())
761                 throw(std::overflow_error("divide_in_z: division by zero"));
762         if (b.is_equal(_ex1)) {
763                 q = a;
764                 return true;
765         }
766         if (is_exactly_a<numeric>(a)) {
767                 if (is_exactly_a<numeric>(b)) {
768                         q = a / b;
769                         return q.info(info_flags::integer);
770                 } else
771                         return false;
772         }
773 #if FAST_COMPARE
774         if (a.is_equal(b)) {
775                 q = _ex1;
776                 return true;
777         }
778 #endif
779
780 #if USE_REMEMBER
781         // Remembering
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;
787         }
788 #endif
789
790         if (is_exactly_a<power>(b)) {
791                 const ex& bb(b.op(0));
792                 ex qbar = a;
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))
796                                 return false;
797                         qbar = q;
798                 }
799                 return true;
800         }
801
802         if (is_exactly_a<mul>(b)) {
803                 ex qbar = a;
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()))
808                                 return false;
809
810                         qbar = q;
811                 }
812                 return true;
813         }
814
815         // Main symbol
816         const ex &x = var->sym;
817
818         // Compare degrees
819         int adeg = a.degree(x), bdeg = b.degree(x);
820         if (bdeg > adeg)
821                 return false;
822
823 #if USE_TRIAL_DIVISION
824
825         // Trial division with polynomial interpolation
826         int i, k;
827
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;
832         ex c;
833         for (i=0; i<=adeg; i++) {
834                 ex bs = b.subs(x == point, subs_options::no_pattern);
835                 while (bs.is_zero()) {
836                         point += *_num1_p;
837                         bs = b.subs(x == point, subs_options::no_pattern);
838                 }
839                 if (!divide_in_z(a.subs(x == point, subs_options::no_pattern), bs, c, var+1))
840                         return false;
841                 alpha.push_back(point);
842                 u.push_back(c);
843                 point += *_num1_p;
844         }
845
846         // Compute inverses
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];
851                 for (i=1; i<k; i++)
852                         product *= alpha[k] - alpha[i];
853                 rcp.push_back(product.inverse());
854         }
855
856         // Compute Newton coefficients
857         exvector v; v.reserve(adeg + 1);
858         v.push_back(u[0]);
859         for (k=1; k<=adeg; k++) {
860                 ex temp = v[k - 1];
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]);
864         }
865
866         // Convert from Newton form to standard form
867         c = v[adeg];
868         for (k=adeg-1; k>=0; k--)
869                 c = c * (x - alpha[k]) + v[k];
870
871         if (c.degree(x) == (adeg - bdeg)) {
872                 q = c.expand();
873                 return true;
874         } else
875                 return false;
876
877 #else
878
879         // Polynomial long division (recursive)
880         ex r = a.expand();
881         if (r.is_zero())
882                 return true;
883         int rdeg = adeg;
884         ex eb = b.expand();
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))
890                         break;
891                 term = (term * pow(x, rdeg - bdeg)).expand();
892                 v.push_back(term);
893                 r -= (term * eb).expand();
894                 if (r.is_zero()) {
895                         q = dynallocate<add>(v);
896 #if USE_REMEMBER
897                         dr_remember[ex2(a, b)] = exbool(q, true);
898 #endif
899                         return true;
900                 }
901                 rdeg = r.degree(x);
902         }
903 #if USE_REMEMBER
904         dr_remember[ex2(a, b)] = exbool(q, false);
905 #endif
906         return false;
907
908 #endif
909 }
910
911
912 /*
913  *  Separation of unit part, content part and primitive part of polynomials
914  */
915
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.
919  *
920  *  @param x  main variable
921  *  @return unit part
922  *  @see ex::content, ex::primpart, ex::unitcontprim */
923 ex ex::unit(const ex &x) const
924 {
925         ex c = expand().lcoeff(x);
926         if (is_exactly_a<numeric>(c))
927                 return c.info(info_flags::negative) ?_ex_1 : _ex1;
928         else {
929                 ex y;
930                 if (get_first_symbol(c, y))
931                         return c.unit(y);
932                 else
933                         throw(std::invalid_argument("invalid expression in unit()"));
934         }
935 }
936
937
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.
941  *
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
946 {
947         if (is_exactly_a<numeric>(*this))
948                 return info(info_flags::negative) ? -*this : *this;
949
950         ex e = expand();
951         if (e.is_zero())
952                 return _ex0;
953
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();
957         ex r = e / c;
958         int deg = r.degree(x);
959         ex lcoeff = r.coeff(x, deg);
960         if (lcoeff.info(info_flags::integer))
961                 return c;
962
963         // GCD of all coefficients
964         int ldeg = r.ldegree(x);
965         if (deg == ldeg)
966                 return lcoeff * c / lcoeff.unit(x);
967         ex cont = _ex0;
968         for (int i=ldeg; i<=deg; i++)
969                 cont = gcd(r.coeff(x, i), cont, nullptr, nullptr, false);
970         return cont * c;
971 }
972
973
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.
977  *
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
982 {
983         // We need to compute the unit and content anyway, so call unitcontprim()
984         ex u, c, p;
985         unitcontprim(x, u, c, p);
986         return p;
987 }
988
989
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.
993  *
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
998 {
999         if (is_zero() || c.is_zero())
1000                 return _ex0;
1001         if (is_exactly_a<numeric>(*this))
1002                 return _ex1;
1003
1004         // Divide by unit and content to get primitive part
1005         ex u = unit(x);
1006         if (is_exactly_a<numeric>(c))
1007                 return *this / (c * u);
1008         else
1009                 return quo(*this, c * u, x, false);
1010 }
1011
1012
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
1015  *  itself.
1016  *
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
1023 {
1024         // Quick check for zero (avoid expanding)
1025         if (is_zero()) {
1026                 u = _ex1;
1027                 c = p = _ex0;
1028                 return;
1029         }
1030
1031         // Special case: input is a number
1032         if (is_exactly_a<numeric>(*this)) {
1033                 if (info(info_flags::negative)) {
1034                         u = _ex_1;
1035                         c = abs(ex_to<numeric>(*this));
1036                 } else {
1037                         u = _ex1;
1038                         c = *this;
1039                 }
1040                 p = _ex1;
1041                 return;
1042         }
1043
1044         // Expand input polynomial
1045         ex e = expand();
1046         if (e.is_zero()) {
1047                 u = _ex1;
1048                 c = p = _ex0;
1049                 return;
1050         }
1051
1052         // Compute unit and content
1053         u = unit(x);
1054         c = content(x);
1055
1056         // Divide by unit and content to get primitive part
1057         if (c.is_zero()) {
1058                 p = _ex0;
1059                 return;
1060         }
1061         if (is_exactly_a<numeric>(c))
1062                 p = *this / (c * u);
1063         else
1064                 p = quo(e, c * u, x, false);
1065 }
1066
1067
1068 /*
1069  *  GCD of multivariate polynomials
1070  */
1071
1072 /** Compute GCD of multivariate polynomials using the subresultant PRS
1073  *  algorithm. This function is used internally by gcd().
1074  *
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
1079  *  @see gcd */
1080
1081 static ex sr_gcd(const ex &a, const ex &b, sym_desc_vec::const_iterator var)
1082 {
1083 #if STATISTICS
1084         sr_gcd_called++;
1085 #endif
1086
1087         // The first symbol is our main variable
1088         const ex &x = var->sym;
1089
1090         // Sort c and d so that c has higher degree
1091         ex c, d;
1092         int adeg = a.degree(x), bdeg = b.degree(x);
1093         int cdeg, ddeg;
1094         if (adeg >= bdeg) {
1095                 c = a;
1096                 d = b;
1097                 cdeg = adeg;
1098                 ddeg = bdeg;
1099         } else {
1100                 c = b;
1101                 d = a;
1102                 cdeg = bdeg;
1103                 ddeg = adeg;
1104         }
1105
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);
1110         if (ddeg == 0)
1111                 return gamma;
1112         c = c.primpart(x, cont_c);
1113         d = d.primpart(x, cont_d);
1114
1115         // First element of subresultant sequence
1116         ex r = _ex0, ri = _ex1, psi = _ex1;
1117         int delta = cdeg - ddeg;
1118
1119         for (;;) {
1120
1121                 // Calculate polynomial pseudo-remainder
1122                 r = prem(c, d, x, false);
1123                 if (r.is_zero())
1124                         return gamma * d.primpart(x);
1125
1126                 c = d;
1127                 cdeg = ddeg;
1128                 if (!divide_in_z(r, ri * pow(psi, delta), d, var))
1129                         throw(std::runtime_error("invalid expression in sr_gcd(), division failed"));
1130                 ddeg = d.degree(x);
1131                 if (ddeg == 0) {
1132                         if (is_exactly_a<numeric>(r))
1133                                 return gamma;
1134                         else
1135                                 return gamma * r.primpart(x);
1136                 }
1137
1138                 // Next element of subresultant sequence
1139                 ri = c.expand().lcoeff(x);
1140                 if (delta == 1)
1141                         psi = ri;
1142                 else if (delta)
1143                         divide_in_z(pow(ri, delta), pow(psi, delta-1), psi, var+1);
1144                 delta = cdeg - ddeg;
1145         }
1146 }
1147
1148
1149 /** Return maximum (absolute value) coefficient of a polynomial.
1150  *  This function is used internally by heur_gcd().
1151  *
1152  *  @return maximum coefficient
1153  *  @see heur_gcd */
1154 numeric ex::max_coefficient() const
1155 {
1156         return bp->max_coefficient();
1157 }
1158
1159 /** Implementation ex::max_coefficient().
1160  *  @see heur_gcd */
1161 numeric basic::max_coefficient() const
1162 {
1163         return *_num1_p;
1164 }
1165
1166 numeric numeric::max_coefficient() const
1167 {
1168         return abs(*this);
1169 }
1170
1171 numeric add::max_coefficient() const
1172 {
1173         GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
1174         numeric cur_max = abs(ex_to<numeric>(overall_coeff));
1175         for (auto & it : seq) {
1176                 numeric a;
1177                 GINAC_ASSERT(!is_exactly_a<numeric>(it.rest));
1178                 a = abs(ex_to<numeric>(it.coeff));
1179                 if (a > cur_max)
1180                         cur_max = a;
1181         }
1182         return cur_max;
1183 }
1184
1185 numeric mul::max_coefficient() const
1186 {
1187 #ifdef DO_GINAC_ASSERT
1188         for (auto & it : seq) {
1189                 GINAC_ASSERT(!is_exactly_a<numeric>(recombine_pair_to_ex(it)));
1190         }
1191 #endif // def DO_GINAC_ASSERT
1192         GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
1193         return abs(ex_to<numeric>(overall_coeff));
1194 }
1195
1196
1197 /** Apply symmetric modular homomorphism to an expanded multivariate
1198  *  polynomial.  This function is usually used internally by heur_gcd().
1199  *
1200  *  @param xi  modulus
1201  *  @return mapped polynomial
1202  *  @see heur_gcd */
1203 ex basic::smod(const numeric &xi) const
1204 {
1205         return *this;
1206 }
1207
1208 ex numeric::smod(const numeric &xi) const
1209 {
1210         return GiNaC::smod(*this, xi);
1211 }
1212
1213 ex add::smod(const numeric &xi) const
1214 {
1215         epvector newseq;
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));
1222         }
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);
1226 }
1227
1228 ex mul::smod(const numeric &xi) const
1229 {
1230 #ifdef DO_GINAC_ASSERT
1231         for (auto & it : seq) {
1232                 GINAC_ASSERT(!is_exactly_a<numeric>(recombine_pair_to_ex(it)));
1233         }
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);
1240         return mulcopy;
1241 }
1242
1243
1244 /** xi-adic polynomial interpolation */
1245 static ex interpolate(const ex &gamma, const numeric &xi, const ex &x, int degree_hint = 1)
1246 {
1247         exvector g; g.reserve(degree_hint);
1248         ex e = gamma;
1249         numeric rxi = xi.inverse();
1250         for (int i=0; !e.is_zero(); i++) {
1251                 ex gi = e.smod(xi);
1252                 g.push_back(gi * pow(x, i));
1253                 e = (e - gi) * rxi;
1254         }
1255         return dynallocate<add>(g);
1256 }
1257
1258 /** Exception thrown by heur_gcd() to signal failure. */
1259 class gcdheu_failed {};
1260
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().
1265  *
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.
1275  *  @see gcd
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)
1279 {
1280 #if STATISTICS
1281         heur_gcd_called++;
1282 #endif
1283
1284         // Algorithm only works for non-vanishing input polynomials
1285         if (a.is_zero() || b.is_zero())
1286                 return false;
1287
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));
1291                 if (ca)
1292                         *ca = ex_to<numeric>(a) / g;
1293                 if (cb)
1294                         *cb = ex_to<numeric>(b) / g;
1295                 res = g;
1296                 return true;
1297         }
1298
1299         // The first symbol is our main variable
1300         const ex &x = var->sym;
1301
1302         // Remove integer content
1303         numeric gc = gcd(a.integer_content(), b.integer_content());
1304         numeric rgc = gc.inverse();
1305         ex p = a * rgc;
1306         ex q = b * rgc;
1307         int maxdeg =  std::max(p.degree(x), q.degree(x));
1308         
1309         // Find evaluation point
1310         numeric mp = p.max_coefficient();
1311         numeric mq = q.max_coefficient();
1312         numeric xi;
1313         if (mp > mq)
1314                 xi = mq * (*_num2_p) + (*_num2_p);
1315         else
1316                 xi = mp * (*_num2_p) + (*_num2_p);
1317
1318         // 6 tries maximum
1319         for (int t=0; t<6; t++) {
1320                 if (xi.int_length() * maxdeg > 100000) {
1321                         throw gcdheu_failed();
1322                 }
1323
1324                 // Apply evaluation homomorphism and calculate GCD
1325                 ex cp, cq;
1326                 ex gamma;
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),
1330                                         &cp, &cq, var+1);
1331                 if (found) {
1332                         gamma = gamma.expand();
1333                         // Reconstruct polynomial from GCD of mapped polynomials
1334                         ex g = interpolate(gamma, xi, x, maxdeg);
1335
1336                         // Remove integer content
1337                         g /= g.integer_content();
1338
1339                         // If the calculated polynomial divides both p and q, this is the GCD
1340                         ex dummy;
1341                         if (divide_in_z(p, g, ca ? *ca : dummy, var) && divide_in_z(q, g, cb ? *cb : dummy, var)) {
1342                                 g *= gc;
1343                                 res = g;
1344                                 return true;
1345                         }
1346                 }
1347
1348                 // Next evaluation point
1349                 xi = iquo(xi * isqrt(isqrt(xi)) * numeric(73794), numeric(27011));
1350         }
1351         return false;
1352 }
1353
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().
1358  *
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.
1368  *  @see heur_gcd_z
1369  *  @see gcd
1370  */
1371 static bool heur_gcd(ex& res, const ex& a, const ex& b, ex *ca, ex *cb,
1372                      sym_desc_vec::const_iterator var)
1373 {
1374         if (a.info(info_flags::integer_polynomial) && 
1375             b.info(info_flags::integer_polynomial)) {
1376                 try {
1377                         return heur_gcd_z(res, a, b, ca, cb, var);
1378                 } catch (gcdheu_failed) {
1379                         return false;
1380                 }
1381         }
1382
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);
1386
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]");
1391
1392         if (!bi.info(info_flags::integer_polynomial))
1393                 throw std::logic_error("heur_gcd: not an integer polynomial [2]");
1394
1395         bool found = false;
1396         try {
1397                 found = heur_gcd_z(res, ai, bi, ca, cb, var);
1398         } catch (gcdheu_failed) {
1399                 return false;
1400         }
1401         
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.
1407         if (found)
1408                 res /= ab_lcm;
1409         return found;
1410 }
1411
1412
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);
1416
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);
1420
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).
1424  *
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)
1433 {
1434 #if STATISTICS
1435         gcd_called++;
1436 #endif
1437
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));
1441                 if (ca || cb) {
1442                         if (g.is_zero()) {
1443                                 if (ca)
1444                                         *ca = _ex0;
1445                                 if (cb)
1446                                         *cb = _ex0;
1447                         } else {
1448                                 if (ca)
1449                                         *ca = ex_to<numeric>(a) / g;
1450                                 if (cb)
1451                                         *cb = ex_to<numeric>(b) / g;
1452                         }
1453                 }
1454                 return g;
1455         }
1456
1457         // Check arguments
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"));
1460         }
1461
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);
1466 #if FAST_COMPARE
1467                 if (is_exactly_a<power>(a) || is_exactly_a<power>(b))
1468                         return gcd_pf_pow(a, b, ca, cb);
1469 #endif
1470         }
1471
1472         // Some trivial cases
1473         ex aex = a.expand(), bex = b.expand();
1474         if (aex.is_zero()) {
1475                 if (ca)
1476                         *ca = _ex0;
1477                 if (cb)
1478                         *cb = _ex1;
1479                 return b;
1480         }
1481         if (bex.is_zero()) {
1482                 if (ca)
1483                         *ca = _ex1;
1484                 if (cb)
1485                         *cb = _ex0;
1486                 return a;
1487         }
1488         if (aex.is_equal(_ex1) || bex.is_equal(_ex1)) {
1489                 if (ca)
1490                         *ca = a;
1491                 if (cb)
1492                         *cb = b;
1493                 return _ex1;
1494         }
1495 #if FAST_COMPARE
1496         if (a.is_equal(b)) {
1497                 if (ca)
1498                         *ca = _ex1;
1499                 if (cb)
1500                         *cb = _ex1;
1501                 return a;
1502         }
1503 #endif
1504
1505         if (is_a<symbol>(aex)) {
1506                 if (! bex.subs(aex==_ex0, subs_options::no_pattern).is_zero()) {
1507                         if (ca)
1508                                 *ca = a;
1509                         if (cb)
1510                                 *cb = b;
1511                         return _ex1;
1512                 }
1513         }
1514
1515         if (is_a<symbol>(bex)) {
1516                 if (! aex.subs(bex==_ex0, subs_options::no_pattern).is_zero()) {
1517                         if (ca)
1518                                 *ca = a;
1519                         if (cb)
1520                                 *cb = b;
1521                         return _ex1;
1522                 }
1523         }
1524
1525         if (is_exactly_a<numeric>(aex)) {
1526                 numeric bcont = bex.integer_content();
1527                 numeric g = gcd(ex_to<numeric>(aex), bcont);
1528                 if (ca)
1529                         *ca = ex_to<numeric>(aex)/g;
1530                 if (cb)
1531                         *cb = bex/g;
1532                 return g;
1533         }
1534
1535         if (is_exactly_a<numeric>(bex)) {
1536                 numeric acont = aex.integer_content();
1537                 numeric g = gcd(ex_to<numeric>(bex), acont);
1538                 if (ca)
1539                         *ca = aex/g;
1540                 if (cb)
1541                         *cb = ex_to<numeric>(bex)/g;
1542                 return g;
1543         }
1544
1545         // Gather symbol statistics
1546         sym_desc_vec sym_stats;
1547         get_symbol_stats(a, b, sym_stats);
1548
1549         // The symbol with least degree which is contained in both polynomials
1550         // is our main variable
1551         sym_desc_vec::iterator vari = sym_stats.begin();
1552         while ((vari != sym_stats.end()) && 
1553                (((vari->ldeg_b == 0) && (vari->deg_b == 0)) ||
1554                 ((vari->ldeg_a == 0) && (vari->deg_a == 0))))
1555                 vari++;
1556
1557         // No common symbols at all, just return 1:
1558         if (vari == sym_stats.end()) {
1559                 // N.B: keep cofactors factored
1560                 if (ca)
1561                         *ca = a;
1562                 if (cb)
1563                         *cb = b;
1564                 return _ex1;
1565         }
1566         // move symbols which contained only in one of the polynomials
1567         // to the end:
1568         rotate(sym_stats.begin(), vari, sym_stats.end());
1569
1570         sym_desc_vec::const_iterator var = sym_stats.begin();
1571         const ex &x = var->sym;
1572
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);
1577         if (min_ldeg > 0) {
1578                 ex common = pow(x, min_ldeg);
1579                 return gcd((aex / common).expand(), (bex / common).expand(), ca, cb, false) * common;
1580         }
1581
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);
1587                 if (cb)
1588                         *cb *= bex_u * bex_p;
1589                 return g;
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);
1594                 if (ca)
1595                         *ca *= aex_u * aex_p;
1596                 return g;
1597         }
1598
1599         // Try heuristic algorithm first, fall back to PRS if that failed
1600         ex g;
1601         if (!(options & gcd_options::no_heur_gcd)) {
1602                 bool found = heur_gcd(g, aex, bex, ca, cb, var);
1603                 if (found) {
1604                         // heur_gcd have already computed cofactors...
1605                         if (g.is_equal(_ex1)) {
1606                                 // ... but we want to keep them factored if possible.
1607                                 if (ca)
1608                                         *ca = a;
1609                                 if (cb)
1610                                         *cb = b;
1611                         }
1612                         return g;
1613                 }
1614 #if STATISTICS
1615                 else {
1616                         heur_gcd_failed++;
1617                 }
1618 #endif
1619         }
1620         if (options & gcd_options::use_sr_gcd) {
1621                 g = sr_gcd(aex, bex, var);
1622         } else {
1623                 exvector vars;
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);
1627         }
1628
1629         if (g.is_equal(_ex1)) {
1630                 // Keep cofactors factored if possible
1631                 if (ca)
1632                         *ca = a;
1633                 if (cb)
1634                         *cb = b;
1635         } else {
1636                 if (ca)
1637                         divide(aex, g, *ca, false);
1638                 if (cb)
1639                         divide(bex, g, *cb, false);
1640         }
1641         return g;
1642 }
1643
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)
1647 {
1648         ex p = a.op(0);
1649         const ex& exp_a = a.op(1);
1650         ex pb = b.op(0);
1651         const ex& exp_b = b.op(1);
1652
1653         // a = p^n, b = p^m, gcd = p^min(n, m)
1654         if (p.is_equal(pb)) {
1655                 if (exp_a < exp_b) {
1656                         if (ca)
1657                                 *ca = _ex1;
1658                         if (cb)
1659                                 *cb = pow(p, exp_b - exp_a);
1660                         return pow(p, exp_a);
1661                 } else {
1662                         if (ca)
1663                                 *ca = pow(p, exp_a - exp_b);
1664                         if (cb)
1665                                 *cb = _ex1;
1666                         return pow(p, exp_b);
1667                 }
1668         }
1669
1670         ex p_co, pb_co;
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)) {
1674                         if (ca)
1675                                 *ca = a;
1676                         if (cb)
1677                                 *cb = b;
1678                         return _ex1;
1679                         // XXX: do I need to check for p_gcd = -1?
1680         }
1681
1682         // there are common factors:
1683         // a(x) = g(x)^n A(x)^n, b(x) = g(x)^m B(x)^m ==>
1684         // gcd(a, b) = g(x)^n gcd(A(x)^n, g(x)^(n-m) B(x)^m
1685         if (exp_a < exp_b) {
1686                 ex pg =  gcd(pow(p_co, exp_a), pow(p_gcd, exp_b-exp_a)*pow(pb_co, exp_b), ca, cb, false);
1687                 return pow(p_gcd, exp_a)*pg;
1688         } else {
1689                 ex pg = gcd(pow(p_gcd, exp_a - exp_b)*pow(p_co, exp_a), pow(pb_co, exp_b), ca, cb, false);
1690                 return pow(p_gcd, exp_b)*pg;
1691         }
1692 }
1693
1694 static ex gcd_pf_pow(const ex& a, const ex& b, ex* ca, ex* cb)
1695 {
1696         if (is_exactly_a<power>(a) && is_exactly_a<power>(b))
1697                 return gcd_pf_pow_pow(a, b, ca, cb);
1698
1699         if (is_exactly_a<power>(b) && (! is_exactly_a<power>(a)))
1700                 return gcd_pf_pow(b, a, cb, ca);
1701
1702         GINAC_ASSERT(is_exactly_a<power>(a));
1703
1704         ex p = a.op(0);
1705         const ex& exp_a = a.op(1);
1706         if (p.is_equal(b)) {
1707                 // a = p^n, b = p, gcd = p
1708                 if (ca)
1709                         *ca = pow(p, a.op(1) - 1);
1710                 if (cb)
1711                         *cb = _ex1;
1712                 return p;
1713         } 
1714
1715         ex p_co, bpart_co;
1716         ex p_gcd = gcd(p, b, &p_co, &bpart_co, false);
1717
1718         // a(x) = p(x)^n, gcd(p, b) = 1 ==> gcd(a, b) = 1
1719         if (p_gcd.is_equal(_ex1)) {
1720                 if (ca)
1721                         *ca = a;
1722                 if (cb)
1723                         *cb = b;
1724                 return _ex1;
1725         }
1726         // 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))
1727         ex rg = gcd(pow(p_gcd, exp_a-1)*pow(p_co, exp_a), bpart_co, ca, cb, false);
1728         return p_gcd*rg;
1729 }
1730
1731 static ex gcd_pf_mul(const ex& a, const ex& b, ex* ca, ex* cb)
1732 {
1733         if (is_exactly_a<mul>(a) && is_exactly_a<mul>(b)
1734                                  && (b.nops() >  a.nops()))
1735                 return gcd_pf_mul(b, a, cb, ca);
1736
1737         if (is_exactly_a<mul>(b) && (!is_exactly_a<mul>(a)))
1738                 return gcd_pf_mul(b, a, cb, ca);
1739
1740         GINAC_ASSERT(is_exactly_a<mul>(a));
1741         size_t num = a.nops();
1742         exvector g; g.reserve(num);
1743         exvector acc_ca; acc_ca.reserve(num);
1744         ex part_b = b;
1745         for (size_t i=0; i<num; i++) {
1746                 ex part_ca, part_cb;
1747                 g.push_back(gcd(a.op(i), part_b, &part_ca, &part_cb, false));
1748                 acc_ca.push_back(part_ca);
1749                 part_b = part_cb;
1750         }
1751         if (ca)
1752                 *ca = dynallocate<mul>(acc_ca);
1753         if (cb)
1754                 *cb = part_b;
1755         return dynallocate<mul>(g);
1756 }
1757
1758 /** Compute LCM (Least Common Multiple) of multivariate polynomials in Z[X].
1759  *
1760  *  @param a  first multivariate polynomial
1761  *  @param b  second multivariate polynomial
1762  *  @param check_args  check whether a and b are polynomials with rational
1763  *         coefficients (defaults to "true")
1764  *  @return the LCM as a new expression */
1765 ex lcm(const ex &a, const ex &b, bool check_args)
1766 {
1767         if (is_exactly_a<numeric>(a) && is_exactly_a<numeric>(b))
1768                 return lcm(ex_to<numeric>(a), ex_to<numeric>(b));
1769         if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
1770                 throw(std::invalid_argument("lcm: arguments must be polynomials over the rationals"));
1771         
1772         ex ca, cb;
1773         ex g = gcd(a, b, &ca, &cb, false);
1774         return ca * cb * g;
1775 }
1776
1777
1778 /*
1779  *  Square-free factorization
1780  */
1781
1782 /** Compute square-free factorization of multivariate polynomial a(x) using
1783  *  Yun's algorithm.  Used internally by sqrfree().
1784  *
1785  *  @param a  multivariate polynomial over Z[X], treated here as univariate
1786  *            polynomial in x (needs not be expanded).
1787  *  @param x  variable to factor in
1788  *  @return   vector of factors sorted in ascending degree */
1789 static exvector sqrfree_yun(const ex &a, const symbol &x)
1790 {
1791         exvector res;
1792         ex w = a;
1793         ex z = w.diff(x);
1794         ex g = gcd(w, z);
1795         if (g.is_zero()) {
1796                 return res;
1797         }
1798         if (g.is_equal(_ex1)) {
1799                 res.push_back(a);
1800                 return res;
1801         }
1802         ex y;
1803         do {
1804                 w = quo(w, g, x);
1805                 if (w.is_zero()) {
1806                         return res;
1807                 }
1808                 y = quo(z, g, x);
1809                 z = y - w.diff(x);
1810                 g = gcd(w, z);
1811                 res.push_back(g);
1812         } while (!z.is_zero());
1813         return res;
1814 }
1815
1816
1817 /** Compute a square-free factorization of a multivariate polynomial in Q[X].
1818  *
1819  *  @param a  multivariate polynomial over Q[X] (needs not be expanded)
1820  *  @param l  lst of variables to factor in, may be left empty for autodetection
1821  *  @return   a square-free factorization of \p a.
1822  *
1823  * \note
1824  * A polynomial \f$p(X) \in C[X]\f$ is said <EM>square-free</EM>
1825  * if, whenever any two polynomials \f$q(X)\f$ and \f$r(X)\f$
1826  * are such that
1827  * \f[
1828  *     p(X) = q(X)^2 r(X),
1829  * \f]
1830  * we have \f$q(X) \in C\f$.
1831  * This means that \f$p(X)\f$ has no repeated factors, apart
1832  * eventually from constants.
1833  * Given a polynomial \f$p(X) \in C[X]\f$, we say that the
1834  * decomposition
1835  * \f[
1836  *   p(X) = b \cdot p_1(X)^{a_1} \cdot p_2(X)^{a_2} \cdots p_r(X)^{a_r}
1837  * \f]
1838  * is a <EM>square-free factorization</EM> of \f$p(X)\f$ if the
1839  * following conditions hold:
1840  * -#  \f$b \in C\f$ and \f$b \neq 0\f$;
1841  * -#  \f$a_i\f$ is a positive integer for \f$i = 1, \ldots, r\f$;
1842  * -#  the degree of the polynomial \f$p_i\f$ is strictly positive
1843  *     for \f$i = 1, \ldots, r\f$;
1844  * -#  the polynomial \f$\Pi_{i=1}^r p_i(X)\f$ is square-free.
1845  *
1846  * Square-free factorizations need not be unique.  For example, if
1847  * \f$a_i\f$ is even, we could change the polynomial \f$p_i(X)\f$
1848  * into \f$-p_i(X)\f$.
1849  * Observe also that the factors \f$p_i(X)\f$ need not be irreducible
1850  * polynomials.
1851  */
1852 ex sqrfree(const ex &a, const lst &l)
1853 {
1854         if (is_exactly_a<numeric>(a) ||
1855             is_a<symbol>(a))        // shortcuts
1856                 return a;
1857
1858         // If no lst of variables to factorize in was specified we have to
1859         // invent one now.  Maybe one can optimize here by reversing the order
1860         // or so, I don't know.
1861         lst args;
1862         if (l.nops()==0) {
1863                 sym_desc_vec sdv;
1864                 get_symbol_stats(a, _ex0, sdv);
1865                 for (auto & it : sdv)
1866                         args.append(it.sym);
1867         } else {
1868                 args = l;
1869         }
1870
1871         // Find the symbol to factor in at this stage
1872         if (!is_a<symbol>(args.op(0)))
1873                 throw (std::runtime_error("sqrfree(): invalid factorization variable"));
1874         const symbol &x = ex_to<symbol>(args.op(0));
1875
1876         // convert the argument from something in Q[X] to something in Z[X]
1877         const numeric lcm = lcm_of_coefficients_denominators(a);
1878         const ex tmp = multiply_lcm(a,lcm);
1879
1880         // find the factors
1881         exvector factors = sqrfree_yun(tmp, x);
1882
1883         // construct the next list of symbols with the first element popped
1884         lst newargs = args;
1885         newargs.remove_first();
1886
1887         // recurse down the factors in remaining variables
1888         if (newargs.nops()>0) {
1889                 for (auto & it : factors)
1890                         it = sqrfree(it, newargs);
1891         }
1892
1893         // Done with recursion, now construct the final result
1894         ex result = _ex1;
1895         int p = 1;
1896         for (auto & it : factors)
1897                 result *= pow(it, p++);
1898
1899         // Yun's algorithm does not account for constant factors.  (For univariate
1900         // polynomials it works only in the monic case.)  We can correct this by
1901         // inserting what has been lost back into the result.  For completeness
1902         // we'll also have to recurse down that factor in the remaining variables.
1903         if (newargs.nops()>0)
1904                 result *= sqrfree(quo(tmp, result, x), newargs);
1905         else
1906                 result *= quo(tmp, result, x);
1907
1908         // Put in the rational overall factor again and return
1909         return result * lcm.inverse();
1910 }
1911
1912
1913 /** Compute square-free partial fraction decomposition of rational function
1914  *  a(x).
1915  *
1916  *  @param a rational function over Z[x], treated as univariate polynomial
1917  *           in x
1918  *  @param x variable to factor in
1919  *  @return decomposed rational function */
1920 ex sqrfree_parfrac(const ex & a, const symbol & x)
1921 {
1922         // Find numerator and denominator
1923         ex nd = numer_denom(a);
1924         ex numer = nd.op(0), denom = nd.op(1);
1925 //clog << "numer = " << numer << ", denom = " << denom << endl;
1926
1927         // Convert N(x)/D(x) -> Q(x) + R(x)/D(x), so degree(R) < degree(D)
1928         ex red_poly = quo(numer, denom, x), red_numer = rem(numer, denom, x).expand();
1929 //clog << "red_poly = " << red_poly << ", red_numer = " << red_numer << endl;
1930
1931         // Factorize denominator and compute cofactors
1932         exvector yun = sqrfree_yun(denom, x);
1933 //clog << "yun factors: " << exprseq(yun) << endl;
1934         size_t num_yun = yun.size();
1935         exvector factor; factor.reserve(num_yun);
1936         exvector cofac; cofac.reserve(num_yun);
1937         for (size_t i=0; i<num_yun; i++) {
1938                 if (!yun[i].is_equal(_ex1)) {
1939                         for (size_t j=0; j<=i; j++) {
1940                                 factor.push_back(pow(yun[i], j+1));
1941                                 ex prod = _ex1;
1942                                 for (size_t k=0; k<num_yun; k++) {
1943                                         if (k == i)
1944                                                 prod *= pow(yun[k], i-j);
1945                                         else
1946                                                 prod *= pow(yun[k], k+1);
1947                                 }
1948                                 cofac.push_back(prod.expand());
1949                         }
1950                 }
1951         }
1952         size_t num_factors = factor.size();
1953 //clog << "factors  : " << exprseq(factor) << endl;
1954 //clog << "cofactors: " << exprseq(cofac) << endl;
1955
1956         // Construct coefficient matrix for decomposition
1957         int max_denom_deg = denom.degree(x);
1958         matrix sys(max_denom_deg + 1, num_factors);
1959         matrix rhs(max_denom_deg + 1, 1);
1960         for (int i=0; i<=max_denom_deg; i++) {
1961                 for (size_t j=0; j<num_factors; j++)
1962                         sys(i, j) = cofac[j].coeff(x, i);
1963                 rhs(i, 0) = red_numer.coeff(x, i);
1964         }
1965 //clog << "coeffs: " << sys << endl;
1966 //clog << "rhs   : " << rhs << endl;
1967
1968         // Solve resulting linear system
1969         matrix vars(num_factors, 1);
1970         for (size_t i=0; i<num_factors; i++)
1971                 vars(i, 0) = symbol();
1972         matrix sol = sys.solve(vars, rhs);
1973
1974         // Sum up decomposed fractions
1975         ex sum = 0;
1976         for (size_t i=0; i<num_factors; i++)
1977                 sum += sol(i, 0) / factor[i];
1978
1979         return red_poly + sum;
1980 }
1981
1982
1983 /*
1984  *  Normal form of rational functions
1985  */
1986
1987 /*
1988  *  Note: The internal normal() functions (= basic::normal() and overloaded
1989  *  functions) all return lists of the form {numerator, denominator}. This
1990  *  is to get around mul::eval()'s automatic expansion of numeric coefficients.
1991  *  E.g. (a+b)/3 is automatically converted to a/3+b/3 but we want to keep
1992  *  the information that (a+b) is the numerator and 3 is the denominator.
1993  */
1994
1995
1996 /** Create a symbol for replacing the expression "e" (or return a previously
1997  *  assigned symbol). The symbol and expression are appended to repl, for
1998  *  a later application of subs().
1999  *  @see ex::normal */
2000 static ex replace_with_symbol(const ex & e, exmap & repl, exmap & rev_lookup)
2001 {
2002         // Since the repl contains replaced expressions we should search for them
2003         ex e_replaced = e.subs(repl, subs_options::no_pattern);
2004
2005         // Expression already replaced? Then return the assigned symbol
2006         auto it = rev_lookup.find(e_replaced);
2007         if (it != rev_lookup.end())
2008                 return it->second;
2009
2010         // Otherwise create new symbol and add to list, taking care that the
2011         // replacement expression doesn't itself contain symbols from repl,
2012         // because subs() is not recursive
2013         ex es = dynallocate<symbol>();
2014         repl.insert(std::make_pair(es, e_replaced));
2015         rev_lookup.insert(std::make_pair(e_replaced, es));
2016         return es;
2017 }
2018
2019 /** Create a symbol for replacing the expression "e" (or return a previously
2020  *  assigned symbol). The symbol and expression are appended to repl, and the
2021  *  symbol is returned.
2022  *  @see basic::to_rational
2023  *  @see basic::to_polynomial */
2024 static ex replace_with_symbol(const ex & e, exmap & repl)
2025 {
2026         // Since the repl contains replaced expressions we should search for them
2027         ex e_replaced = e.subs(repl, subs_options::no_pattern);
2028
2029         // Expression already replaced? Then return the assigned symbol
2030         for (auto & it : repl)
2031                 if (it.second.is_equal(e_replaced))
2032                         return it.first;
2033
2034         // Otherwise create new symbol and add to list, taking care that the
2035         // replacement expression doesn't itself contain symbols from repl,
2036         // because subs() is not recursive
2037         ex es = dynallocate<symbol>();
2038         repl.insert(std::make_pair(es, e_replaced));
2039         return es;
2040 }
2041
2042
2043 /** Function object to be applied by basic::normal(). */
2044 struct normal_map_function : public map_function {
2045         ex operator()(const ex & e) override { return normal(e); }
2046 };
2047
2048 /** Default implementation of ex::normal(). It normalizes the children and
2049  *  replaces the object with a temporary symbol.
2050  *  @see ex::normal */
2051 ex basic::normal(exmap & repl, exmap & rev_lookup) const
2052 {
2053         if (nops() == 0)
2054                 return dynallocate<lst>({replace_with_symbol(*this, repl, rev_lookup), _ex1});
2055
2056         normal_map_function map_normal;
2057         return dynallocate<lst>({replace_with_symbol(map(map_normal), repl, rev_lookup), _ex1});
2058 }
2059
2060
2061 /** Implementation of ex::normal() for symbols. This returns the unmodified symbol.
2062  *  @see ex::normal */
2063 ex symbol::normal(exmap & repl, exmap & rev_lookup) const
2064 {
2065         return dynallocate<lst>({*this, _ex1});
2066 }
2067
2068
2069 /** Implementation of ex::normal() for a numeric. It splits complex numbers
2070  *  into re+I*im and replaces I and non-rational real numbers with a temporary
2071  *  symbol.
2072  *  @see ex::normal */
2073 ex numeric::normal(exmap & repl, exmap & rev_lookup) const
2074 {
2075         numeric num = numer();
2076         ex numex = num;
2077
2078         if (num.is_real()) {
2079                 if (!num.is_integer())
2080                         numex = replace_with_symbol(numex, repl, rev_lookup);
2081         } else { // complex
2082                 numeric re = num.real(), im = num.imag();
2083                 ex re_ex = re.is_rational() ? re : replace_with_symbol(re, repl, rev_lookup);
2084                 ex im_ex = im.is_rational() ? im : replace_with_symbol(im, repl, rev_lookup);
2085                 numex = re_ex + im_ex * replace_with_symbol(I, repl, rev_lookup);
2086         }
2087
2088         // Denominator is always a real integer (see numeric::denom())
2089         return dynallocate<lst>({numex, denom()});
2090 }
2091
2092
2093 /** Fraction cancellation.
2094  *  @param n  numerator
2095  *  @param d  denominator
2096  *  @return cancelled fraction {n, d} as a list */
2097 static ex frac_cancel(const ex &n, const ex &d)
2098 {
2099         ex num = n;
2100         ex den = d;
2101         numeric pre_factor = *_num1_p;
2102
2103 //std::clog << "frac_cancel num = " << num << ", den = " << den << std::endl;
2104
2105         // Handle trivial case where denominator is 1
2106         if (den.is_equal(_ex1))
2107                 return dynallocate<lst>({num, den});
2108
2109         // Handle special cases where numerator or denominator is 0
2110         if (num.is_zero())
2111                 return dynallocate<lst>({num, _ex1});
2112         if (den.expand().is_zero())
2113                 throw(std::overflow_error("frac_cancel: division by zero in frac_cancel"));
2114
2115         // Bring numerator and denominator to Z[X] by multiplying with
2116         // LCM of all coefficients' denominators
2117         numeric num_lcm = lcm_of_coefficients_denominators(num);
2118         numeric den_lcm = lcm_of_coefficients_denominators(den);
2119         num = multiply_lcm(num, num_lcm);
2120         den = multiply_lcm(den, den_lcm);
2121         pre_factor = den_lcm / num_lcm;
2122
2123         // Cancel GCD from numerator and denominator
2124         ex cnum, cden;
2125         if (gcd(num, den, &cnum, &cden, false) != _ex1) {
2126                 num = cnum;
2127                 den = cden;
2128         }
2129
2130         // Make denominator unit normal (i.e. coefficient of first symbol
2131         // as defined by get_first_symbol() is made positive)
2132         if (is_exactly_a<numeric>(den)) {
2133                 if (ex_to<numeric>(den).is_negative()) {
2134                         num *= _ex_1;
2135                         den *= _ex_1;
2136                 }
2137         } else {
2138                 ex x;
2139                 if (get_first_symbol(den, x)) {
2140                         GINAC_ASSERT(is_exactly_a<numeric>(den.unit(x)));
2141                         if (ex_to<numeric>(den.unit(x)).is_negative()) {
2142                                 num *= _ex_1;
2143                                 den *= _ex_1;
2144                         }
2145                 }
2146         }
2147
2148         // Return result as list
2149 //std::clog << " returns num = " << num << ", den = " << den << ", pre_factor = " << pre_factor << std::endl;
2150         return dynallocate<lst>({num * pre_factor.numer(), den * pre_factor.denom()});
2151 }
2152
2153
2154 /** Implementation of ex::normal() for a sum. It expands terms and performs
2155  *  fractional addition.
2156  *  @see ex::normal */
2157 ex add::normal(exmap & repl, exmap & rev_lookup) const
2158 {
2159         // Normalize children and split each one into numerator and denominator
2160         exvector nums, dens;
2161         nums.reserve(seq.size()+1);
2162         dens.reserve(seq.size()+1);
2163         for (auto & it : seq) {
2164                 ex n = ex_to<basic>(recombine_pair_to_ex(it)).normal(repl, rev_lookup);
2165                 nums.push_back(n.op(0));
2166                 dens.push_back(n.op(1));
2167         }
2168         ex n = ex_to<numeric>(overall_coeff).normal(repl, rev_lookup);
2169         nums.push_back(n.op(0));
2170         dens.push_back(n.op(1));
2171         GINAC_ASSERT(nums.size() == dens.size());
2172
2173         // Now, nums is a vector of all numerators and dens is a vector of
2174         // all denominators
2175 //std::clog << "add::normal uses " << nums.size() << " summands:\n";
2176
2177         // Add fractions sequentially
2178         auto num_it = nums.begin(), num_itend = nums.end();
2179         auto den_it = dens.begin(), den_itend = dens.end();
2180 //std::clog << " num = " << *num_it << ", den = " << *den_it << std::endl;
2181         ex num = *num_it++, den = *den_it++;
2182         while (num_it != num_itend) {
2183 //std::clog << " num = " << *num_it << ", den = " << *den_it << std::endl;
2184                 ex next_num = *num_it++, next_den = *den_it++;
2185
2186                 // Trivially add sequences of fractions with identical denominators
2187                 while ((den_it != den_itend) && next_den.is_equal(*den_it)) {
2188                         next_num += *num_it;
2189                         num_it++; den_it++;
2190                 }
2191
2192                 // Addition of two fractions, taking advantage of the fact that
2193                 // the heuristic GCD algorithm computes the cofactors at no extra cost
2194                 ex co_den1, co_den2;
2195                 ex g = gcd(den, next_den, &co_den1, &co_den2, false);
2196                 num = ((num * co_den2) + (next_num * co_den1)).expand();
2197                 den *= co_den2;         // this is the lcm(den, next_den)
2198         }
2199 //std::clog << " common denominator = " << den << std::endl;
2200
2201         // Cancel common factors from num/den
2202         return frac_cancel(num, den);
2203 }
2204
2205
2206 /** Implementation of ex::normal() for a product. It cancels common factors
2207  *  from fractions.
2208  *  @see ex::normal() */
2209 ex mul::normal(exmap & repl, exmap & rev_lookup) const
2210 {
2211         // Normalize children, separate into numerator and denominator
2212         exvector num; num.reserve(seq.size());
2213         exvector den; den.reserve(seq.size());
2214         ex n;
2215         for (auto & it : seq) {
2216                 n = ex_to<basic>(recombine_pair_to_ex(it)).normal(repl, rev_lookup);
2217                 num.push_back(n.op(0));
2218                 den.push_back(n.op(1));
2219         }
2220         n = ex_to<numeric>(overall_coeff).normal(repl, rev_lookup);
2221         num.push_back(n.op(0));
2222         den.push_back(n.op(1));
2223
2224         // Perform fraction cancellation
2225         return frac_cancel(dynallocate<mul>(num), dynallocate<mul>(den));
2226 }
2227
2228
2229 /** Implementation of ex::normal([B) for powers. It normalizes the basis,
2230  *  distributes integer exponents to numerator and denominator, and replaces
2231  *  non-integer powers by temporary symbols.
2232  *  @see ex::normal */
2233 ex power::normal(exmap & repl, exmap & rev_lookup) const
2234 {
2235         // Normalize basis and exponent (exponent gets reassembled)
2236         ex n_basis = ex_to<basic>(basis).normal(repl, rev_lookup);
2237         ex n_exponent = ex_to<basic>(exponent).normal(repl, rev_lookup);
2238         n_exponent = n_exponent.op(0) / n_exponent.op(1);
2239
2240         if (n_exponent.info(info_flags::integer)) {
2241
2242                 if (n_exponent.info(info_flags::positive)) {
2243
2244                         // (a/b)^n -> {a^n, b^n}
2245                         return dynallocate<lst>({pow(n_basis.op(0), n_exponent), pow(n_basis.op(1), n_exponent)});
2246
2247                 } else if (n_exponent.info(info_flags::negative)) {
2248
2249                         // (a/b)^-n -> {b^n, a^n}
2250                         return dynallocate<lst>({pow(n_basis.op(1), -n_exponent), pow(n_basis.op(0), -n_exponent)});
2251                 }
2252
2253         } else {
2254
2255                 if (n_exponent.info(info_flags::positive)) {
2256
2257                         // (a/b)^x -> {sym((a/b)^x), 1}
2258                         return dynallocate<lst>({replace_with_symbol(pow(n_basis.op(0) / n_basis.op(1), n_exponent), repl, rev_lookup), _ex1});
2259
2260                 } else if (n_exponent.info(info_flags::negative)) {
2261
2262                         if (n_basis.op(1).is_equal(_ex1)) {
2263
2264                                 // a^-x -> {1, sym(a^x)}
2265                                 return dynallocate<lst>({_ex1, replace_with_symbol(pow(n_basis.op(0), -n_exponent), repl, rev_lookup)});
2266
2267                         } else {
2268
2269                                 // (a/b)^-x -> {sym((b/a)^x), 1}
2270                                 return dynallocate<lst>({replace_with_symbol(pow(n_basis.op(1) / n_basis.op(0), -n_exponent), repl, rev_lookup), _ex1});
2271                         }
2272                 }
2273         }
2274
2275         // (a/b)^x -> {sym((a/b)^x, 1}
2276         return dynallocate<lst>({replace_with_symbol(pow(n_basis.op(0) / n_basis.op(1), n_exponent), repl, rev_lookup), _ex1});
2277 }
2278
2279
2280 /** Implementation of ex::normal() for pseries. It normalizes each coefficient
2281  *  and replaces the series by a temporary symbol.
2282  *  @see ex::normal */
2283 ex pseries::normal(exmap & repl, exmap & rev_lookup) const
2284 {
2285         epvector newseq;
2286         for (auto & it : seq) {
2287                 ex restexp = it.rest.normal();
2288                 if (!restexp.is_zero())
2289                         newseq.push_back(expair(restexp, it.coeff));
2290         }
2291         ex n = pseries(relational(var,point), std::move(newseq));
2292         return dynallocate<lst>({replace_with_symbol(n, repl, rev_lookup), _ex1});
2293 }
2294
2295
2296 /** Normalization of rational functions.
2297  *  This function converts an expression to its normal form
2298  *  "numerator/denominator", where numerator and denominator are (relatively
2299  *  prime) polynomials. Any subexpressions which are not rational functions
2300  *  (like non-rational numbers, non-integer powers or functions like sin(),
2301  *  cos() etc.) are replaced by temporary symbols which are re-substituted by
2302  *  the (normalized) subexpressions before normal() returns (this way, any
2303  *  expression can be treated as a rational function). normal() is applied
2304  *  recursively to arguments of functions etc.
2305  *
2306  *  @return normalized expression */
2307 ex ex::normal() const
2308 {
2309         exmap repl, rev_lookup;
2310
2311         ex e = bp->normal(repl, rev_lookup);
2312         GINAC_ASSERT(is_a<lst>(e));
2313
2314         // Re-insert replaced symbols
2315         if (!repl.empty())
2316                 e = e.subs(repl, subs_options::no_pattern);
2317
2318         // Convert {numerator, denominator} form back to fraction
2319         return e.op(0) / e.op(1);
2320 }
2321
2322 /** Get numerator of an expression. If the expression is not of the normal
2323  *  form "numerator/denominator", it is first converted to this form and
2324  *  then the numerator is returned.
2325  *
2326  *  @see ex::normal
2327  *  @return numerator */
2328 ex ex::numer() const
2329 {
2330         exmap repl, rev_lookup;
2331
2332         ex e = bp->normal(repl, rev_lookup);
2333         GINAC_ASSERT(is_a<lst>(e));
2334
2335         // Re-insert replaced symbols
2336         if (repl.empty())
2337                 return e.op(0);
2338         else
2339                 return e.op(0).subs(repl, subs_options::no_pattern);
2340 }
2341
2342 /** Get denominator of an expression. If the expression is not of the normal
2343  *  form "numerator/denominator", it is first converted to this form and
2344  *  then the denominator is returned.
2345  *
2346  *  @see ex::normal
2347  *  @return denominator */
2348 ex ex::denom() const
2349 {
2350         exmap repl, rev_lookup;
2351
2352         ex e = bp->normal(repl, rev_lookup);
2353         GINAC_ASSERT(is_a<lst>(e));
2354
2355         // Re-insert replaced symbols
2356         if (repl.empty())
2357                 return e.op(1);
2358         else
2359                 return e.op(1).subs(repl, subs_options::no_pattern);
2360 }
2361
2362 /** Get numerator and denominator of an expression. If the expression is not
2363  *  of the normal form "numerator/denominator", it is first converted to this
2364  *  form and then a list [numerator, denominator] is returned.
2365  *
2366  *  @see ex::normal
2367  *  @return a list [numerator, denominator] */
2368 ex ex::numer_denom() const
2369 {
2370         exmap repl, rev_lookup;
2371
2372         ex e = bp->normal(repl, rev_lookup);
2373         GINAC_ASSERT(is_a<lst>(e));
2374
2375         // Re-insert replaced symbols
2376         if (repl.empty())
2377                 return e;
2378         else
2379                 return e.subs(repl, subs_options::no_pattern);
2380 }
2381
2382
2383 /** Rationalization of non-rational functions.
2384  *  This function converts a general expression to a rational function
2385  *  by replacing all non-rational subexpressions (like non-rational numbers,
2386  *  non-integer powers or functions like sin(), cos() etc.) to temporary
2387  *  symbols. This makes it possible to use functions like gcd() and divide()
2388  *  on non-rational functions by applying to_rational() on the arguments,
2389  *  calling the desired function and re-substituting the temporary symbols
2390  *  in the result. To make the last step possible, all temporary symbols and
2391  *  their associated expressions are collected in the map specified by the
2392  *  repl parameter, ready to be passed as an argument to ex::subs().
2393  *
2394  *  @param repl collects all temporary symbols and their replacements
2395  *  @return rationalized expression */
2396 ex ex::to_rational(exmap & repl) const
2397 {
2398         return bp->to_rational(repl);
2399 }
2400
2401 // GiNaC 1.1 compatibility function
2402 ex ex::to_rational(lst & repl_lst) const
2403 {
2404         // Convert lst to exmap
2405         exmap m;
2406         for (auto & it : repl_lst)
2407                 m.insert(std::make_pair(it.op(0), it.op(1)));
2408
2409         ex ret = bp->to_rational(m);
2410
2411         // Convert exmap back to lst
2412         repl_lst.remove_all();
2413         for (auto & it : m)
2414                 repl_lst.append(it.first == it.second);
2415
2416         return ret;
2417 }
2418
2419 ex ex::to_polynomial(exmap & repl) const
2420 {
2421         return bp->to_polynomial(repl);
2422 }
2423
2424 // GiNaC 1.1 compatibility function
2425 ex ex::to_polynomial(lst & repl_lst) const
2426 {
2427         // Convert lst to exmap
2428         exmap m;
2429         for (auto & it : repl_lst)
2430                 m.insert(std::make_pair(it.op(0), it.op(1)));
2431
2432         ex ret = bp->to_polynomial(m);
2433
2434         // Convert exmap back to lst
2435         repl_lst.remove_all();
2436         for (auto & it : m)
2437                 repl_lst.append(it.first == it.second);
2438
2439         return ret;
2440 }
2441
2442 /** Default implementation of ex::to_rational(). This replaces the object with
2443  *  a temporary symbol. */
2444 ex basic::to_rational(exmap & repl) const
2445 {
2446         return replace_with_symbol(*this, repl);
2447 }
2448
2449 ex basic::to_polynomial(exmap & repl) const
2450 {
2451         return replace_with_symbol(*this, repl);
2452 }
2453
2454
2455 /** Implementation of ex::to_rational() for symbols. This returns the
2456  *  unmodified symbol. */
2457 ex symbol::to_rational(exmap & repl) const
2458 {
2459         return *this;
2460 }
2461
2462 /** Implementation of ex::to_polynomial() for symbols. This returns the
2463  *  unmodified symbol. */
2464 ex symbol::to_polynomial(exmap & repl) const
2465 {
2466         return *this;
2467 }
2468
2469
2470 /** Implementation of ex::to_rational() for a numeric. It splits complex
2471  *  numbers into re+I*im and replaces I and non-rational real numbers with a
2472  *  temporary symbol. */
2473 ex numeric::to_rational(exmap & repl) const
2474 {
2475         if (is_real()) {
2476                 if (!is_rational())
2477                         return replace_with_symbol(*this, repl);
2478         } else { // complex
2479                 numeric re = real();
2480                 numeric im = imag();
2481                 ex re_ex = re.is_rational() ? re : replace_with_symbol(re, repl);
2482                 ex im_ex = im.is_rational() ? im : replace_with_symbol(im, repl);
2483                 return re_ex + im_ex * replace_with_symbol(I, repl);
2484         }
2485         return *this;
2486 }
2487
2488 /** Implementation of ex::to_polynomial() for a numeric. It splits complex
2489  *  numbers into re+I*im and replaces I and non-integer real numbers with a
2490  *  temporary symbol. */
2491 ex numeric::to_polynomial(exmap & repl) const
2492 {
2493         if (is_real()) {
2494                 if (!is_integer())
2495                         return replace_with_symbol(*this, repl);
2496         } else { // complex
2497                 numeric re = real();
2498                 numeric im = imag();
2499                 ex re_ex = re.is_integer() ? re : replace_with_symbol(re, repl);
2500                 ex im_ex = im.is_integer() ? im : replace_with_symbol(im, repl);
2501                 return re_ex + im_ex * replace_with_symbol(I, repl);
2502         }
2503         return *this;
2504 }
2505
2506
2507 /** Implementation of ex::to_rational() for powers. It replaces non-integer
2508  *  powers by temporary symbols. */
2509 ex power::to_rational(exmap & repl) const
2510 {
2511         if (exponent.info(info_flags::integer))
2512                 return pow(basis.to_rational(repl), exponent);
2513         else
2514                 return replace_with_symbol(*this, repl);
2515 }
2516
2517 /** Implementation of ex::to_polynomial() for powers. It replaces non-posint
2518  *  powers by temporary symbols. */
2519 ex power::to_polynomial(exmap & repl) const
2520 {
2521         if (exponent.info(info_flags::posint))
2522                 return pow(basis.to_rational(repl), exponent);
2523         else if (exponent.info(info_flags::negint))
2524         {
2525                 ex basis_pref = collect_common_factors(basis);
2526                 if (is_exactly_a<mul>(basis_pref) || is_exactly_a<power>(basis_pref)) {
2527                         // (A*B)^n will be automagically transformed to A^n*B^n
2528                         ex t = pow(basis_pref, exponent);
2529                         return t.to_polynomial(repl);
2530                 }
2531                 else
2532                         return pow(replace_with_symbol(pow(basis, _ex_1), repl), -exponent);
2533         } 
2534         else
2535                 return replace_with_symbol(*this, repl);
2536 }
2537
2538
2539 /** Implementation of ex::to_rational() for expairseqs. */
2540 ex expairseq::to_rational(exmap & repl) const
2541 {
2542         epvector s;
2543         s.reserve(seq.size());
2544         for (auto & it : seq)
2545                 s.push_back(split_ex_to_pair(recombine_pair_to_ex(it).to_rational(repl)));
2546
2547         ex oc = overall_coeff.to_rational(repl);
2548         if (oc.info(info_flags::numeric))
2549                 return thisexpairseq(std::move(s), overall_coeff);
2550         else
2551                 s.push_back(expair(oc, _ex1));
2552         return thisexpairseq(std::move(s), default_overall_coeff());
2553 }
2554
2555 /** Implementation of ex::to_polynomial() for expairseqs. */
2556 ex expairseq::to_polynomial(exmap & repl) const
2557 {
2558         epvector s;
2559         s.reserve(seq.size());
2560         for (auto & it : seq)
2561                 s.push_back(split_ex_to_pair(recombine_pair_to_ex(it).to_polynomial(repl)));
2562
2563         ex oc = overall_coeff.to_polynomial(repl);
2564         if (oc.info(info_flags::numeric))
2565                 return thisexpairseq(std::move(s), overall_coeff);
2566         else
2567                 s.push_back(expair(oc, _ex1));
2568         return thisexpairseq(std::move(s), default_overall_coeff());
2569 }
2570
2571
2572 /** Remove the common factor in the terms of a sum 'e' by calculating the GCD,
2573  *  and multiply it into the expression 'factor' (which needs to be initialized
2574  *  to 1, unless you're accumulating factors). */
2575 static ex find_common_factor(const ex & e, ex & factor, exmap & repl)
2576 {
2577         if (is_exactly_a<add>(e)) {
2578
2579                 size_t num = e.nops();
2580                 exvector terms; terms.reserve(num);
2581                 ex gc;
2582
2583                 // Find the common GCD
2584                 for (size_t i=0; i<num; i++) {
2585                         ex x = e.op(i).to_polynomial(repl);
2586
2587                         if (is_exactly_a<add>(x) || is_exactly_a<mul>(x) || is_a<power>(x)) {
2588                                 ex f = 1;
2589                                 x = find_common_factor(x, f, repl);
2590                                 x *= f;
2591                         }
2592
2593                         if (i == 0)
2594                                 gc = x;
2595                         else
2596                                 gc = gcd(gc, x);
2597
2598                         terms.push_back(x);
2599                 }
2600
2601                 if (gc.is_equal(_ex1))
2602                         return e;
2603
2604                 // The GCD is the factor we pull out
2605                 factor *= gc;
2606
2607                 // Now divide all terms by the GCD
2608                 for (size_t i=0; i<num; i++) {
2609                         ex x;
2610
2611                         // Try to avoid divide() because it expands the polynomial
2612                         ex &t = terms[i];
2613                         if (is_exactly_a<mul>(t)) {
2614                                 for (size_t j=0; j<t.nops(); j++) {
2615                                         if (t.op(j).is_equal(gc)) {
2616                                                 exvector v; v.reserve(t.nops());
2617                                                 for (size_t k=0; k<t.nops(); k++) {
2618                                                         if (k == j)
2619                                                                 v.push_back(_ex1);
2620                                                         else
2621                                                                 v.push_back(t.op(k));
2622                                                 }
2623                                                 t = dynallocate<mul>(v);
2624                                                 goto term_done;
2625                                         }
2626                                 }
2627                         }
2628
2629                         divide(t, gc, x);
2630                         t = x;
2631 term_done:      ;
2632                 }
2633                 return dynallocate<add>(terms);
2634
2635         } else if (is_exactly_a<mul>(e)) {
2636
2637                 size_t num = e.nops();
2638                 exvector v; v.reserve(num);
2639
2640                 for (size_t i=0; i<num; i++)
2641                         v.push_back(find_common_factor(e.op(i), factor, repl));
2642
2643                 return dynallocate<mul>(v);
2644
2645         } else if (is_exactly_a<power>(e)) {
2646                 const ex e_exp(e.op(1));
2647                 if (e_exp.info(info_flags::integer)) {
2648                         ex eb = e.op(0).to_polynomial(repl);
2649                         ex factor_local(_ex1);
2650                         ex pre_res = find_common_factor(eb, factor_local, repl);
2651                         factor *= pow(factor_local, e_exp);
2652                         return pow(pre_res, e_exp);
2653                         
2654                 } else
2655                         return e.to_polynomial(repl);
2656
2657         } else
2658                 return e;
2659 }
2660
2661
2662 /** Collect common factors in sums. This converts expressions like
2663  *  'a*(b*x+b*y)' to 'a*b*(x+y)'. */
2664 ex collect_common_factors(const ex & e)
2665 {
2666         if (is_exactly_a<add>(e) || is_exactly_a<mul>(e) || is_exactly_a<power>(e)) {
2667
2668                 exmap repl;
2669                 ex factor = 1;
2670                 ex r = find_common_factor(e, factor, repl);
2671                 return factor.subs(repl, subs_options::no_pattern) * r.subs(repl, subs_options::no_pattern);
2672
2673         } else
2674                 return e;
2675 }
2676
2677
2678 /** Resultant of two expressions e1,e2 with respect to symbol s.
2679  *  Method: Compute determinant of Sylvester matrix of e1,e2,s.  */
2680 ex resultant(const ex & e1, const ex & e2, const ex & s)
2681 {
2682         const ex ee1 = e1.expand();
2683         const ex ee2 = e2.expand();
2684         if (!ee1.info(info_flags::polynomial) ||
2685             !ee2.info(info_flags::polynomial))
2686                 throw(std::runtime_error("resultant(): arguments must be polynomials"));
2687
2688         const int h1 = ee1.degree(s);
2689         const int l1 = ee1.ldegree(s);
2690         const int h2 = ee2.degree(s);
2691         const int l2 = ee2.ldegree(s);
2692
2693         const int msize = h1 + h2;
2694         matrix m(msize, msize);
2695
2696         for (int l = h1; l >= l1; --l) {
2697                 const ex e = ee1.coeff(s, l);
2698                 for (int k = 0; k < h2; ++k)
2699                         m(k, k+h1-l) = e;
2700         }
2701         for (int l = h2; l >= l2; --l) {
2702                 const ex e = ee2.coeff(s, l);
2703                 for (int k = 0; k < h1; ++k)
2704                         m(k+h2, k+h2-l) = e;
2705         }
2706
2707         return m.determinant();
2708 }
2709
2710
2711 } // namespace GiNaC