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