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