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