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