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