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