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