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