]> www.ginac.de Git - ginac.git/blob - ginac/normal.cpp
- introduced info_flag::algebraic.
[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 /** Exact polynomial division of a(X) by b(X) in Q[X].
493  *  
494  *  @param a  first multivariate polynomial (dividend)
495  *  @param b  second multivariate polynomial (divisor)
496  *  @param q  quotient (returned)
497  *  @param check_args  check whether a and b are polynomials with rational
498  *         coefficients (defaults to "true")
499  *  @return "true" when exact division succeeds (quotient returned in q),
500  *          "false" otherwise */
501 bool divide(const ex &a, const ex &b, ex &q, bool check_args)
502 {
503     q = _ex0();
504     if (b.is_zero())
505         throw(std::overflow_error("divide: division by zero"));
506     if (a.is_zero())
507         return true;
508     if (is_ex_exactly_of_type(b, numeric)) {
509         q = a / b;
510         return true;
511     } else if (is_ex_exactly_of_type(a, numeric))
512         return false;
513 #if FAST_COMPARE
514     if (a.is_equal(b)) {
515         q = _ex1();
516         return true;
517     }
518 #endif
519     if (check_args && (!a.info(info_flags::rational_polynomial) ||
520                        !b.info(info_flags::rational_polynomial)))
521         throw(std::invalid_argument("divide: arguments must be polynomials over the rationals"));
522
523     // Find first symbol
524     const symbol *x;
525     if (!get_first_symbol(a, x) && !get_first_symbol(b, x))
526         throw(std::invalid_argument("invalid expression in divide()"));
527
528     // Polynomial long division (recursive)
529     ex r = a.expand();
530     if (r.is_zero())
531         return true;
532     int bdeg = b.degree(*x);
533     int rdeg = r.degree(*x);
534     ex blcoeff = b.expand().coeff(*x, bdeg);
535     bool blcoeff_is_numeric = is_ex_exactly_of_type(blcoeff, numeric);
536     while (rdeg >= bdeg) {
537         ex term, rcoeff = r.coeff(*x, rdeg);
538         if (blcoeff_is_numeric)
539             term = rcoeff / blcoeff;
540         else
541             if (!divide(rcoeff, blcoeff, term, false))
542                 return false;
543         term *= power(*x, rdeg - bdeg);
544         q += term;
545         r -= (term * b).expand();
546         if (r.is_zero())
547             return true;
548         rdeg = r.degree(*x);
549     }
550     return false;
551 }
552
553
554 #if USE_REMEMBER
555 /*
556  *  Remembering
557  */
558
559 typedef pair<ex, ex> ex2;
560 typedef pair<ex, bool> exbool;
561
562 struct ex2_less {
563     bool operator() (const ex2 p, const ex2 q) const 
564     {
565         return p.first.compare(q.first) < 0 || (!(q.first.compare(p.first) < 0) && p.second.compare(q.second) < 0);        
566     }
567 };
568
569 typedef map<ex2, exbool, ex2_less> ex2_exbool_remember;
570 #endif
571
572
573 /** Exact polynomial division of a(X) by b(X) in Z[X].
574  *  This functions works like divide() but the input and output polynomials are
575  *  in Z[X] instead of Q[X] (i.e. they have integer coefficients). Unlike
576  *  divide(), it doesnĀ“t check whether the input polynomials really are integer
577  *  polynomials, so be careful of what you pass in. Also, you have to run
578  *  get_symbol_stats() over the input polynomials before calling this function
579  *  and pass an iterator to the first element of the sym_desc vector. This
580  *  function is used internally by the heur_gcd().
581  *  
582  *  @param a  first multivariate polynomial (dividend)
583  *  @param b  second multivariate polynomial (divisor)
584  *  @param q  quotient (returned)
585  *  @param var  iterator to first element of vector of sym_desc structs
586  *  @return "true" when exact division succeeds (the quotient is returned in
587  *          q), "false" otherwise.
588  *  @see get_symbol_stats, heur_gcd */
589 static bool divide_in_z(const ex &a, const ex &b, ex &q, sym_desc_vec::const_iterator var)
590 {
591     q = _ex0();
592     if (b.is_zero())
593         throw(std::overflow_error("divide_in_z: division by zero"));
594     if (b.is_equal(_ex1())) {
595         q = a;
596         return true;
597     }
598     if (is_ex_exactly_of_type(a, numeric)) {
599         if (is_ex_exactly_of_type(b, numeric)) {
600             q = a / b;
601             return q.info(info_flags::integer);
602         } else
603             return false;
604     }
605 #if FAST_COMPARE
606     if (a.is_equal(b)) {
607         q = _ex1();
608         return true;
609     }
610 #endif
611
612 #if USE_REMEMBER
613     // Remembering
614     static ex2_exbool_remember dr_remember;
615     ex2_exbool_remember::const_iterator remembered = dr_remember.find(ex2(a, b));
616     if (remembered != dr_remember.end()) {
617         q = remembered->second.first;
618         return remembered->second.second;
619     }
620 #endif
621
622     // Main symbol
623     const symbol *x = var->sym;
624
625     // Compare degrees
626     int adeg = a.degree(*x), bdeg = b.degree(*x);
627     if (bdeg > adeg)
628         return false;
629
630 #if USE_TRIAL_DIVISION
631
632     // Trial division with polynomial interpolation
633     int i, k;
634
635     // Compute values at evaluation points 0..adeg
636     vector<numeric> alpha; alpha.reserve(adeg + 1);
637     exvector u; u.reserve(adeg + 1);
638     numeric point = _num0();
639     ex c;
640     for (i=0; i<=adeg; i++) {
641         ex bs = b.subs(*x == point);
642         while (bs.is_zero()) {
643             point += _num1();
644             bs = b.subs(*x == point);
645         }
646         if (!divide_in_z(a.subs(*x == point), bs, c, var+1))
647             return false;
648         alpha.push_back(point);
649         u.push_back(c);
650         point += _num1();
651     }
652
653     // Compute inverses
654     vector<numeric> rcp; rcp.reserve(adeg + 1);
655     rcp.push_back(_num0());
656     for (k=1; k<=adeg; k++) {
657         numeric product = alpha[k] - alpha[0];
658         for (i=1; i<k; i++)
659             product *= alpha[k] - alpha[i];
660         rcp.push_back(product.inverse());
661     }
662
663     // Compute Newton coefficients
664     exvector v; v.reserve(adeg + 1);
665     v.push_back(u[0]);
666     for (k=1; k<=adeg; k++) {
667         ex temp = v[k - 1];
668         for (i=k-2; i>=0; i--)
669             temp = temp * (alpha[k] - alpha[i]) + v[i];
670         v.push_back((u[k] - temp) * rcp[k]);
671     }
672
673     // Convert from Newton form to standard form
674     c = v[adeg];
675     for (k=adeg-1; k>=0; k--)
676         c = c * (*x - alpha[k]) + v[k];
677
678     if (c.degree(*x) == (adeg - bdeg)) {
679         q = c.expand();
680         return true;
681     } else
682         return false;
683
684 #else
685
686     // Polynomial long division (recursive)
687     ex r = a.expand();
688     if (r.is_zero())
689         return true;
690     int rdeg = adeg;
691     ex eb = b.expand();
692     ex blcoeff = eb.coeff(*x, bdeg);
693     while (rdeg >= bdeg) {
694         ex term, rcoeff = r.coeff(*x, rdeg);
695         if (!divide_in_z(rcoeff, blcoeff, term, var+1))
696             break;
697         term = (term * power(*x, rdeg - bdeg)).expand();
698         q += term;
699         r -= (term * eb).expand();
700         if (r.is_zero()) {
701 #if USE_REMEMBER
702             dr_remember[ex2(a, b)] = exbool(q, true);
703 #endif
704             return true;
705         }
706         rdeg = r.degree(*x);
707     }
708 #if USE_REMEMBER
709     dr_remember[ex2(a, b)] = exbool(q, false);
710 #endif
711     return false;
712
713 #endif
714 }
715
716
717 /*
718  *  Separation of unit part, content part and primitive part of polynomials
719  */
720
721 /** Compute unit part (= sign of leading coefficient) of a multivariate
722  *  polynomial in Z[x]. The product of unit part, content part, and primitive
723  *  part is the polynomial itself.
724  *
725  *  @param x  variable in which to compute the unit part
726  *  @return unit part
727  *  @see ex::content, ex::primpart */
728 ex ex::unit(const symbol &x) const
729 {
730     ex c = expand().lcoeff(x);
731     if (is_ex_exactly_of_type(c, numeric))
732         return c < _ex0() ? _ex_1() : _ex1();
733     else {
734         const symbol *y;
735         if (get_first_symbol(c, y))
736             return c.unit(*y);
737         else
738             throw(std::invalid_argument("invalid expression in unit()"));
739     }
740 }
741
742
743 /** Compute content part (= unit normal GCD of all coefficients) of a
744  *  multivariate polynomial in Z[x].  The product of unit part, content part,
745  *  and primitive part is the polynomial itself.
746  *
747  *  @param x  variable in which to compute the content part
748  *  @return content part
749  *  @see ex::unit, ex::primpart */
750 ex ex::content(const symbol &x) const
751 {
752     if (is_zero())
753         return _ex0();
754     if (is_ex_exactly_of_type(*this, numeric))
755         return info(info_flags::negative) ? -*this : *this;
756     ex e = expand();
757     if (e.is_zero())
758         return _ex0();
759
760     // First, try the integer content
761     ex c = e.integer_content();
762     ex r = e / c;
763     ex lcoeff = r.lcoeff(x);
764     if (lcoeff.info(info_flags::integer))
765         return c;
766
767     // GCD of all coefficients
768     int deg = e.degree(x);
769     int ldeg = e.ldegree(x);
770     if (deg == ldeg)
771         return e.lcoeff(x) / e.unit(x);
772     c = _ex0();
773     for (int i=ldeg; i<=deg; i++)
774         c = gcd(e.coeff(x, i), c, NULL, NULL, false);
775     return c;
776 }
777
778
779 /** Compute primitive part of a multivariate polynomial in Z[x].
780  *  The product of unit part, content part, and primitive part is the
781  *  polynomial itself.
782  *
783  *  @param x  variable in which to compute the primitive part
784  *  @return primitive part
785  *  @see ex::unit, ex::content */
786 ex ex::primpart(const symbol &x) const
787 {
788     if (is_zero())
789         return _ex0();
790     if (is_ex_exactly_of_type(*this, numeric))
791         return _ex1();
792
793     ex c = content(x);
794     if (c.is_zero())
795         return _ex0();
796     ex u = unit(x);
797     if (is_ex_exactly_of_type(c, numeric))
798         return *this / (c * u);
799     else
800         return quo(*this, c * u, x, false);
801 }
802
803
804 /** Compute primitive part of a multivariate polynomial in Z[x] when the
805  *  content part is already known. This function is faster in computing the
806  *  primitive part than the previous function.
807  *
808  *  @param x  variable in which to compute the primitive part
809  *  @param c  previously computed content part
810  *  @return primitive part */
811 ex ex::primpart(const symbol &x, const ex &c) const
812 {
813     if (is_zero())
814         return _ex0();
815     if (c.is_zero())
816         return _ex0();
817     if (is_ex_exactly_of_type(*this, numeric))
818         return _ex1();
819
820     ex u = unit(x);
821     if (is_ex_exactly_of_type(c, numeric))
822         return *this / (c * u);
823     else
824         return quo(*this, c * u, x, false);
825 }
826
827
828 /*
829  *  GCD of multivariate polynomials
830  */
831
832 /** Compute GCD of multivariate polynomials using the Euclidean PRS algorithm
833  *  (not really suited for multivariate GCDs). This function is only provided
834  *  for testing purposes.
835  *
836  *  @param a  first multivariate polynomial
837  *  @param b  second multivariate polynomial
838  *  @param x  pointer to symbol (main variable) in which to compute the GCD in
839  *  @return the GCD as a new expression
840  *  @see gcd */
841
842 static ex eu_gcd(const ex &a, const ex &b, const symbol *x)
843 {
844 //clog << "eu_gcd(" << a << "," << b << ")\n";
845
846     // Sort c and d so that c has higher degree
847     ex c, d;
848     int adeg = a.degree(*x), bdeg = b.degree(*x);
849     if (adeg >= bdeg) {
850         c = a;
851         d = b;
852     } else {
853         c = b;
854         d = a;
855     }
856
857         // Euclidean algorithm
858     ex r;
859     for (;;) {
860 //clog << " d = " << d << endl;
861         r = rem(c, d, *x, false);
862         if (r.is_zero())
863             return d.primpart(*x);
864         c = d;
865                 d = r;
866     }
867 }
868
869
870 /** Compute GCD of multivariate polynomials using the Euclidean PRS algorithm
871  *  with pseudo-remainders ("World's Worst GCD Algorithm", staying in Z[X]).
872  *  This function is only provided for testing purposes.
873  *
874  *  @param a  first multivariate polynomial
875  *  @param b  second multivariate polynomial
876  *  @param x  pointer to symbol (main variable) in which to compute the GCD in
877  *  @return the GCD as a new expression
878  *  @see gcd */
879
880 static ex euprem_gcd(const ex &a, const ex &b, const symbol *x)
881 {
882 //clog << "euprem_gcd(" << a << "," << b << ")\n";
883
884     // Sort c and d so that c has higher degree
885     ex c, d;
886     int adeg = a.degree(*x), bdeg = b.degree(*x);
887     if (adeg >= bdeg) {
888         c = a;
889         d = b;
890     } else {
891         c = b;
892         d = a;
893     }
894
895         // Euclidean algorithm with pseudo-remainders
896     ex r;
897     for (;;) {
898 //clog << " d = " << d << endl;
899         r = prem(c, d, *x, false);
900         if (r.is_zero())
901             return d.primpart(*x);
902         c = d;
903                 d = r;
904     }
905 }
906
907
908 /** Compute GCD of multivariate polynomials using the primitive Euclidean
909  *  PRS algorithm (complete content removal at each step). This function is
910  *  only provided for testing purposes.
911  *
912  *  @param a  first multivariate polynomial
913  *  @param b  second multivariate polynomial
914  *  @param x  pointer to symbol (main variable) in which to compute the GCD in
915  *  @return the GCD as a new expression
916  *  @see gcd */
917
918 static ex peu_gcd(const ex &a, const ex &b, const symbol *x)
919 {
920 //clog << "peu_gcd(" << a << "," << b << ")\n";
921
922     // Sort c and d so that c has higher degree
923     ex c, d;
924     int adeg = a.degree(*x), bdeg = b.degree(*x);
925     int ddeg;
926     if (adeg >= bdeg) {
927         c = a;
928         d = b;
929         ddeg = bdeg;
930     } else {
931         c = b;
932         d = a;
933         ddeg = adeg;
934     }
935
936     // Remove content from c and d, to be attached to GCD later
937     ex cont_c = c.content(*x);
938     ex cont_d = d.content(*x);
939     ex gamma = gcd(cont_c, cont_d, NULL, NULL, false);
940     if (ddeg == 0)
941         return gamma;
942     c = c.primpart(*x, cont_c);
943     d = d.primpart(*x, cont_d);
944
945     // Euclidean algorithm with content removal
946         ex r;
947     for (;;) {
948 //clog << " d = " << d << endl;
949         r = prem(c, d, *x, false);
950         if (r.is_zero())
951             return gamma * d;
952         c = d;
953                 d = r.primpart(*x);
954     }
955 }
956
957
958 /** Compute GCD of multivariate polynomials using the reduced PRS algorithm.
959  *  This function is only provided for testing purposes.
960  *
961  *  @param a  first multivariate polynomial
962  *  @param b  second multivariate polynomial
963  *  @param x  pointer to symbol (main variable) in which to compute the GCD in
964  *  @return the GCD as a new expression
965  *  @see gcd */
966
967 static ex red_gcd(const ex &a, const ex &b, const symbol *x)
968 {
969 //clog << "red_gcd(" << a << "," << b << ")\n";
970
971     // Sort c and d so that c has higher degree
972     ex c, d;
973     int adeg = a.degree(*x), bdeg = b.degree(*x);
974     int cdeg, ddeg;
975     if (adeg >= bdeg) {
976         c = a;
977         d = b;
978         cdeg = adeg;
979         ddeg = bdeg;
980     } else {
981         c = b;
982         d = a;
983         cdeg = bdeg;
984         ddeg = adeg;
985     }
986
987     // Remove content from c and d, to be attached to GCD later
988     ex cont_c = c.content(*x);
989     ex cont_d = d.content(*x);
990     ex gamma = gcd(cont_c, cont_d, NULL, NULL, false);
991     if (ddeg == 0)
992         return gamma;
993     c = c.primpart(*x, cont_c);
994     d = d.primpart(*x, cont_d);
995
996     // First element of subresultant sequence
997     ex r, ri = _ex1();
998     int delta = cdeg - ddeg;
999
1000     for (;;) {
1001         // Calculate polynomial pseudo-remainder
1002 //clog << " d = " << d << endl;
1003         r = prem(c, d, *x, false);
1004         if (r.is_zero())
1005             return gamma * d.primpart(*x);
1006         c = d;
1007         cdeg = ddeg;
1008
1009         if (!divide(r, pow(ri, delta), d, false))
1010             throw(std::runtime_error("invalid expression in red_gcd(), division failed"));
1011         ddeg = d.degree(*x);
1012         if (ddeg == 0) {
1013             if (is_ex_exactly_of_type(r, numeric))
1014                 return gamma;
1015             else
1016                 return gamma * r.primpart(*x);
1017         }
1018
1019         ri = c.expand().lcoeff(*x);
1020         delta = cdeg - ddeg;
1021     }
1022 }
1023
1024
1025 /** Compute GCD of multivariate polynomials using the subresultant PRS
1026  *  algorithm. This function is used internally by gcd().
1027  *
1028  *  @param a  first multivariate polynomial
1029  *  @param b  second multivariate polynomial
1030  *  @param x  pointer to symbol (main variable) in which to compute the GCD in
1031  *  @return the GCD as a new expression
1032  *  @see gcd */
1033 static ex sr_gcd(const ex &a, const ex &b, const symbol *x)
1034 {
1035 //clog << "sr_gcd(" << a << "," << b << ")\n";
1036 #if STATISTICS
1037         sr_gcd_called++;
1038 #endif
1039
1040     // Sort c and d so that c has higher degree
1041     ex c, d;
1042     int adeg = a.degree(*x), bdeg = b.degree(*x);
1043     int cdeg, ddeg;
1044     if (adeg >= bdeg) {
1045         c = a;
1046         d = b;
1047         cdeg = adeg;
1048         ddeg = bdeg;
1049     } else {
1050         c = b;
1051         d = a;
1052         cdeg = bdeg;
1053         ddeg = adeg;
1054     }
1055
1056     // Remove content from c and d, to be attached to GCD later
1057     ex cont_c = c.content(*x);
1058     ex cont_d = d.content(*x);
1059     ex gamma = gcd(cont_c, cont_d, NULL, NULL, false);
1060     if (ddeg == 0)
1061         return gamma;
1062     c = c.primpart(*x, cont_c);
1063     d = d.primpart(*x, cont_d);
1064 //clog << " content " << gamma << " removed, continuing with sr_gcd(" << c << "," << d << ")\n";
1065
1066     // First element of subresultant sequence
1067     ex r = _ex0(), ri = _ex1(), psi = _ex1();
1068     int delta = cdeg - ddeg;
1069
1070     for (;;) {
1071         // Calculate polynomial pseudo-remainder
1072 //clog << " start of loop, psi = " << psi << ", calculating pseudo-remainder...\n";
1073 //clog << " d = " << d << endl;
1074         r = prem(c, d, *x, false);
1075         if (r.is_zero())
1076             return gamma * d.primpart(*x);
1077         c = d;
1078         cdeg = ddeg;
1079 //clog << " dividing...\n";
1080         if (!divide(r, ri * pow(psi, delta), d, false))
1081             throw(std::runtime_error("invalid expression in sr_gcd(), division failed"));
1082         ddeg = d.degree(*x);
1083         if (ddeg == 0) {
1084             if (is_ex_exactly_of_type(r, numeric))
1085                 return gamma;
1086             else
1087                 return gamma * r.primpart(*x);
1088         }
1089
1090         // Next element of subresultant sequence
1091 //clog << " calculating next subresultant...\n";
1092         ri = c.expand().lcoeff(*x);
1093         if (delta == 1)
1094             psi = ri;
1095         else if (delta)
1096             divide(pow(ri, delta), pow(psi, delta-1), psi, false);
1097         delta = cdeg - ddeg;
1098     }
1099 }
1100
1101
1102 /** Return maximum (absolute value) coefficient of a polynomial.
1103  *  This function is used internally by heur_gcd().
1104  *
1105  *  @param e  expanded multivariate polynomial
1106  *  @return maximum coefficient
1107  *  @see heur_gcd */
1108 numeric ex::max_coefficient(void) const
1109 {
1110     GINAC_ASSERT(bp!=0);
1111     return bp->max_coefficient();
1112 }
1113
1114 numeric basic::max_coefficient(void) const
1115 {
1116     return _num1();
1117 }
1118
1119 numeric numeric::max_coefficient(void) const
1120 {
1121     return abs(*this);
1122 }
1123
1124 numeric add::max_coefficient(void) const
1125 {
1126     epvector::const_iterator it = seq.begin();
1127     epvector::const_iterator itend = seq.end();
1128     GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
1129     numeric cur_max = abs(ex_to_numeric(overall_coeff));
1130     while (it != itend) {
1131         numeric a;
1132         GINAC_ASSERT(!is_ex_exactly_of_type(it->rest,numeric));
1133         a = abs(ex_to_numeric(it->coeff));
1134         if (a > cur_max)
1135             cur_max = a;
1136         it++;
1137     }
1138     return cur_max;
1139 }
1140
1141 numeric mul::max_coefficient(void) const
1142 {
1143 #ifdef DO_GINAC_ASSERT
1144     epvector::const_iterator it = seq.begin();
1145     epvector::const_iterator itend = seq.end();
1146     while (it != itend) {
1147         GINAC_ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*it),numeric));
1148         it++;
1149     }
1150 #endif // def DO_GINAC_ASSERT
1151     GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
1152     return abs(ex_to_numeric(overall_coeff));
1153 }
1154
1155
1156 /** Apply symmetric modular homomorphism to a multivariate polynomial.
1157  *  This function is used internally by heur_gcd().
1158  *
1159  *  @param e  expanded multivariate polynomial
1160  *  @param xi  modulus
1161  *  @return mapped polynomial
1162  *  @see heur_gcd */
1163 ex ex::smod(const numeric &xi) const
1164 {
1165     GINAC_ASSERT(bp!=0);
1166     return bp->smod(xi);
1167 }
1168
1169 ex basic::smod(const numeric &xi) const
1170 {
1171     return *this;
1172 }
1173
1174 ex numeric::smod(const numeric &xi) const
1175 {
1176 #ifndef NO_NAMESPACE_GINAC
1177     return GiNaC::smod(*this, xi);
1178 #else // ndef NO_NAMESPACE_GINAC
1179     return ::smod(*this, xi);
1180 #endif // ndef NO_NAMESPACE_GINAC
1181 }
1182
1183 ex add::smod(const numeric &xi) const
1184 {
1185     epvector newseq;
1186     newseq.reserve(seq.size()+1);
1187     epvector::const_iterator it = seq.begin();
1188     epvector::const_iterator itend = seq.end();
1189     while (it != itend) {
1190         GINAC_ASSERT(!is_ex_exactly_of_type(it->rest,numeric));
1191 #ifndef NO_NAMESPACE_GINAC
1192         numeric coeff = GiNaC::smod(ex_to_numeric(it->coeff), xi);
1193 #else // ndef NO_NAMESPACE_GINAC
1194         numeric coeff = ::smod(ex_to_numeric(it->coeff), xi);
1195 #endif // ndef NO_NAMESPACE_GINAC
1196         if (!coeff.is_zero())
1197             newseq.push_back(expair(it->rest, coeff));
1198         it++;
1199     }
1200     GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
1201 #ifndef NO_NAMESPACE_GINAC
1202     numeric coeff = GiNaC::smod(ex_to_numeric(overall_coeff), xi);
1203 #else // ndef NO_NAMESPACE_GINAC
1204     numeric coeff = ::smod(ex_to_numeric(overall_coeff), xi);
1205 #endif // ndef NO_NAMESPACE_GINAC
1206     return (new add(newseq,coeff))->setflag(status_flags::dynallocated);
1207 }
1208
1209 ex mul::smod(const numeric &xi) const
1210 {
1211 #ifdef DO_GINAC_ASSERT
1212     epvector::const_iterator it = seq.begin();
1213     epvector::const_iterator itend = seq.end();
1214     while (it != itend) {
1215         GINAC_ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*it),numeric));
1216         it++;
1217     }
1218 #endif // def DO_GINAC_ASSERT
1219     mul * mulcopyp=new mul(*this);
1220     GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
1221 #ifndef NO_NAMESPACE_GINAC
1222     mulcopyp->overall_coeff = GiNaC::smod(ex_to_numeric(overall_coeff),xi);
1223 #else // ndef NO_NAMESPACE_GINAC
1224     mulcopyp->overall_coeff = ::smod(ex_to_numeric(overall_coeff),xi);
1225 #endif // ndef NO_NAMESPACE_GINAC
1226     mulcopyp->clearflag(status_flags::evaluated);
1227     mulcopyp->clearflag(status_flags::hash_calculated);
1228     return mulcopyp->setflag(status_flags::dynallocated);
1229 }
1230
1231
1232 /** Exception thrown by heur_gcd() to signal failure. */
1233 class gcdheu_failed {};
1234
1235 /** Compute GCD of multivariate polynomials using the heuristic GCD algorithm.
1236  *  get_symbol_stats() must have been called previously with the input
1237  *  polynomials and an iterator to the first element of the sym_desc vector
1238  *  passed in. This function is used internally by gcd().
1239  *
1240  *  @param a  first multivariate polynomial (expanded)
1241  *  @param b  second multivariate polynomial (expanded)
1242  *  @param ca  cofactor of polynomial a (returned), NULL to suppress
1243  *             calculation of cofactor
1244  *  @param cb  cofactor of polynomial b (returned), NULL to suppress
1245  *             calculation of cofactor
1246  *  @param var iterator to first element of vector of sym_desc structs
1247  *  @return the GCD as a new expression
1248  *  @see gcd
1249  *  @exception gcdheu_failed() */
1250 static ex heur_gcd(const ex &a, const ex &b, ex *ca, ex *cb, sym_desc_vec::const_iterator var)
1251 {
1252 //clog << "heur_gcd(" << a << "," << b << ")\n";
1253 #if STATISTICS
1254         heur_gcd_called++;
1255 #endif
1256
1257         // GCD of two numeric values -> CLN
1258     if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric)) {
1259         numeric g = gcd(ex_to_numeric(a), ex_to_numeric(b));
1260         numeric rg;
1261         if (ca || cb)
1262             rg = g.inverse();
1263         if (ca)
1264             *ca = ex_to_numeric(a).mul(rg);
1265         if (cb)
1266             *cb = ex_to_numeric(b).mul(rg);
1267         return g;
1268     }
1269
1270     // The first symbol is our main variable
1271     const symbol *x = var->sym;
1272
1273     // Remove integer content
1274     numeric gc = gcd(a.integer_content(), b.integer_content());
1275     numeric rgc = gc.inverse();
1276     ex p = a * rgc;
1277     ex q = b * rgc;
1278     int maxdeg = max(p.degree(*x), q.degree(*x));
1279
1280     // Find evaluation point
1281     numeric mp = p.max_coefficient(), mq = q.max_coefficient();
1282     numeric xi;
1283     if (mp > mq)
1284         xi = mq * _num2() + _num2();
1285     else
1286         xi = mp * _num2() + _num2();
1287
1288     // 6 tries maximum
1289     for (int t=0; t<6; t++) {
1290         if (xi.int_length() * maxdeg > 100000) {
1291 //clog << "giving up heur_gcd, xi.int_length = " << xi.int_length() << ", maxdeg = " << maxdeg << endl;
1292             throw gcdheu_failed();
1293                 }
1294
1295         // Apply evaluation homomorphism and calculate GCD
1296         ex gamma = heur_gcd(p.subs(*x == xi), q.subs(*x == xi), NULL, NULL, var+1).expand();
1297         if (!is_ex_exactly_of_type(gamma, fail)) {
1298
1299             // Reconstruct polynomial from GCD of mapped polynomials
1300             ex g = _ex0();
1301             numeric rxi = xi.inverse();
1302             for (int i=0; !gamma.is_zero(); i++) {
1303                 ex gi = gamma.smod(xi);
1304                 g += gi * power(*x, i);
1305                 gamma = (gamma - gi) * rxi;
1306             }
1307             // Remove integer content
1308             g /= g.integer_content();
1309
1310             // If the calculated polynomial divides both a and b, this is the GCD
1311             ex dummy;
1312             if (divide_in_z(p, g, ca ? *ca : dummy, var) && divide_in_z(q, g, cb ? *cb : dummy, var)) {
1313                 g *= gc;
1314                 ex lc = g.lcoeff(*x);
1315                 if (is_ex_exactly_of_type(lc, numeric) && ex_to_numeric(lc).is_negative())
1316                     return -g;
1317                 else
1318                     return g;
1319             }
1320         }
1321
1322         // Next evaluation point
1323         xi = iquo(xi * isqrt(isqrt(xi)) * numeric(73794), numeric(27011));
1324     }
1325     return *new ex(fail());
1326 }
1327
1328
1329 /** Compute GCD (Greatest Common Divisor) of multivariate polynomials a(X)
1330  *  and b(X) in Z[X].
1331  *
1332  *  @param a  first multivariate polynomial
1333  *  @param b  second multivariate polynomial
1334  *  @param check_args  check whether a and b are polynomials with rational
1335  *         coefficients (defaults to "true")
1336  *  @return the GCD as a new expression */
1337 ex gcd(const ex &a, const ex &b, ex *ca, ex *cb, bool check_args)
1338 {
1339 //clog << "gcd(" << a << "," << b << ")\n";
1340 #if STATISTICS
1341         gcd_called++;
1342 #endif
1343
1344         // GCD of numerics -> CLN
1345     if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric)) {
1346         numeric g = gcd(ex_to_numeric(a), ex_to_numeric(b));
1347         if (ca)
1348             *ca = ex_to_numeric(a) / g;
1349         if (cb)
1350             *cb = ex_to_numeric(b) / g;
1351         return g;
1352     }
1353
1354         // Check arguments
1355     if (check_args && !a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)) {
1356         throw(std::invalid_argument("gcd: arguments must be polynomials over the rationals"));
1357     }
1358
1359         // Partially factored cases (to avoid expanding large expressions)
1360         if (is_ex_exactly_of_type(a, mul)) {
1361                 if (is_ex_exactly_of_type(b, mul) && b.nops() > a.nops())
1362                         goto factored_b;
1363 factored_a:
1364                 ex g = _ex1();
1365                 ex acc_ca = _ex1();
1366                 ex part_b = b;
1367                 for (unsigned i=0; i<a.nops(); i++) {
1368                         ex part_ca, part_cb;
1369                         g *= gcd(a.op(i), part_b, &part_ca, &part_cb, check_args);
1370                         acc_ca *= part_ca;
1371                         part_b = part_cb;
1372                 }
1373                 if (ca)
1374                         *ca = acc_ca;
1375                 if (cb)
1376                         *cb = part_b;
1377                 return g;
1378         } else if (is_ex_exactly_of_type(b, mul)) {
1379                 if (is_ex_exactly_of_type(a, mul) && a.nops() > b.nops())
1380                         goto factored_a;
1381 factored_b:
1382                 ex g = _ex1();
1383                 ex acc_cb = _ex1();
1384                 ex part_a = a;
1385                 for (unsigned i=0; i<b.nops(); i++) {
1386                         ex part_ca, part_cb;
1387                         g *= gcd(part_a, b.op(i), &part_ca, &part_cb, check_args);
1388                         acc_cb *= part_cb;
1389                         part_a = part_ca;
1390                 }
1391                 if (ca)
1392                         *ca = part_a;
1393                 if (cb)
1394                         *cb = acc_cb;
1395                 return g;
1396         }
1397
1398 #if FAST_COMPARE
1399         // Input polynomials of the form poly^n are sometimes also trivial
1400         if (is_ex_exactly_of_type(a, power)) {
1401                 ex p = a.op(0);
1402                 if (is_ex_exactly_of_type(b, power)) {
1403                         if (p.is_equal(b.op(0))) {
1404                                 // a = p^n, b = p^m, gcd = p^min(n, m)
1405                                 ex exp_a = a.op(1), exp_b = b.op(1);
1406                                 if (exp_a < exp_b) {
1407                                         if (ca)
1408                                                 *ca = _ex1();
1409                                         if (cb)
1410                                                 *cb = power(p, exp_b - exp_a);
1411                                         return power(p, exp_a);
1412                                 } else {
1413                                         if (ca)
1414                                                 *ca = power(p, exp_a - exp_b);
1415                                         if (cb)
1416                                                 *cb = _ex1();
1417                                         return power(p, exp_b);
1418                                 }
1419                         }
1420                 } else {
1421                         if (p.is_equal(b)) {
1422                                 // a = p^n, b = p, gcd = p
1423                                 if (ca)
1424                                         *ca = power(p, a.op(1) - 1);
1425                                 if (cb)
1426                                         *cb = _ex1();
1427                                 return p;
1428                         }
1429                 }
1430         } else if (is_ex_exactly_of_type(b, power)) {
1431                 ex p = b.op(0);
1432                 if (p.is_equal(a)) {
1433                         // a = p, b = p^n, gcd = p
1434                         if (ca)
1435                                 *ca = _ex1();
1436                         if (cb)
1437                                 *cb = power(p, b.op(1) - 1);
1438                         return p;
1439                 }
1440         }
1441 #endif
1442
1443     // Some trivial cases
1444         ex aex = a.expand(), bex = b.expand();
1445     if (aex.is_zero()) {
1446         if (ca)
1447             *ca = _ex0();
1448         if (cb)
1449             *cb = _ex1();
1450         return b;
1451     }
1452     if (bex.is_zero()) {
1453         if (ca)
1454             *ca = _ex1();
1455         if (cb)
1456             *cb = _ex0();
1457         return a;
1458     }
1459     if (aex.is_equal(_ex1()) || bex.is_equal(_ex1())) {
1460         if (ca)
1461             *ca = a;
1462         if (cb)
1463             *cb = b;
1464         return _ex1();
1465     }
1466 #if FAST_COMPARE
1467     if (a.is_equal(b)) {
1468         if (ca)
1469             *ca = _ex1();
1470         if (cb)
1471             *cb = _ex1();
1472         return a;
1473     }
1474 #endif
1475
1476     // Gather symbol statistics
1477     sym_desc_vec sym_stats;
1478     get_symbol_stats(a, b, sym_stats);
1479
1480     // The symbol with least degree is our main variable
1481     sym_desc_vec::const_iterator var = sym_stats.begin();
1482     const symbol *x = var->sym;
1483
1484     // Cancel trivial common factor
1485     int ldeg_a = var->ldeg_a;
1486     int ldeg_b = var->ldeg_b;
1487     int min_ldeg = min(ldeg_a, ldeg_b);
1488     if (min_ldeg > 0) {
1489         ex common = power(*x, min_ldeg);
1490 //clog << "trivial common factor " << common << endl;
1491         return gcd((aex / common).expand(), (bex / common).expand(), ca, cb, false) * common;
1492     }
1493
1494     // Try to eliminate variables
1495     if (var->deg_a == 0) {
1496 //clog << "eliminating variable " << *x << " from b" << endl;
1497         ex c = bex.content(*x);
1498         ex g = gcd(aex, c, ca, cb, false);
1499         if (cb)
1500             *cb *= bex.unit(*x) * bex.primpart(*x, c);
1501         return g;
1502     } else if (var->deg_b == 0) {
1503 //clog << "eliminating variable " << *x << " from a" << endl;
1504         ex c = aex.content(*x);
1505         ex g = gcd(c, bex, ca, cb, false);
1506         if (ca)
1507             *ca *= aex.unit(*x) * aex.primpart(*x, c);
1508         return g;
1509     }
1510
1511     ex g;
1512 #if 1
1513     // Try heuristic algorithm first, fall back to PRS if that failed
1514     try {
1515         g = heur_gcd(aex, bex, ca, cb, var);
1516     } catch (gcdheu_failed) {
1517         g = *new ex(fail());
1518     }
1519     if (is_ex_exactly_of_type(g, fail)) {
1520 //clog << "heuristics failed" << endl;
1521 #if STATISTICS
1522                 heur_gcd_failed++;
1523 #endif
1524 #endif
1525 //              g = heur_gcd(aex, bex, ca, cb, var);
1526 //              g = eu_gcd(aex, bex, x);
1527 //              g = euprem_gcd(aex, bex, x);
1528 //              g = peu_gcd(aex, bex, x);
1529 //              g = red_gcd(aex, bex, x);
1530                 g = sr_gcd(aex, bex, x);
1531                 if (g.is_equal(_ex1())) {
1532                         // Keep cofactors factored if possible
1533                         if (ca)
1534                                 *ca = a;
1535                         if (cb)
1536                                 *cb = b;
1537                 } else {
1538                 if (ca)
1539                     divide(aex, g, *ca, false);
1540                 if (cb)
1541                     divide(bex, g, *cb, false);
1542                 }
1543 #if 1
1544     } else {
1545                 if (g.is_equal(_ex1())) {
1546                         // Keep cofactors factored if possible
1547                         if (ca)
1548                                 *ca = a;
1549                         if (cb)
1550                                 *cb = b;
1551                 }
1552         }
1553 #endif
1554     return g;
1555 }
1556
1557
1558 /** Compute LCM (Least Common Multiple) of multivariate polynomials in Z[X].
1559  *
1560  *  @param a  first multivariate polynomial
1561  *  @param b  second multivariate polynomial
1562  *  @param check_args  check whether a and b are polynomials with rational
1563  *         coefficients (defaults to "true")
1564  *  @return the LCM as a new expression */
1565 ex lcm(const ex &a, const ex &b, bool check_args)
1566 {
1567     if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric))
1568         return lcm(ex_to_numeric(a), ex_to_numeric(b));
1569     if (check_args && !a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial))
1570         throw(std::invalid_argument("lcm: arguments must be polynomials over the rationals"));
1571     
1572     ex ca, cb;
1573     ex g = gcd(a, b, &ca, &cb, false);
1574     return ca * cb * g;
1575 }
1576
1577
1578 /*
1579  *  Square-free factorization
1580  */
1581
1582 // Univariate GCD of polynomials in Q[x] (used internally by sqrfree()).
1583 // a and b can be multivariate polynomials but they are treated as univariate polynomials in x.
1584 static ex univariate_gcd(const ex &a, const ex &b, const symbol &x)
1585 {
1586     if (a.is_zero())
1587         return b;
1588     if (b.is_zero())
1589         return a;
1590     if (a.is_equal(_ex1()) || b.is_equal(_ex1()))
1591         return _ex1();
1592     if (is_ex_of_type(a, numeric) && is_ex_of_type(b, numeric))
1593         return gcd(ex_to_numeric(a), ex_to_numeric(b));
1594     if (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial))
1595         throw(std::invalid_argument("univariate_gcd: arguments must be polynomials over the rationals"));
1596
1597     // Euclidean algorithm
1598     ex c, d, r;
1599     if (a.degree(x) >= b.degree(x)) {
1600         c = a;
1601         d = b;
1602     } else {
1603         c = b;
1604         d = a;
1605     }
1606     for (;;) {
1607         r = rem(c, d, x, false);
1608         if (r.is_zero())
1609             break;
1610         c = d;
1611         d = r;
1612     }
1613     return d / d.lcoeff(x);
1614 }
1615
1616
1617 /** Compute square-free factorization of multivariate polynomial a(x) using
1618  *  YunĀ“s algorithm.
1619  *
1620  * @param a  multivariate polynomial
1621  * @param x  variable to factor in
1622  * @return factored polynomial */
1623 ex sqrfree(const ex &a, const symbol &x)
1624 {
1625     int i = 1;
1626     ex res = _ex1();
1627     ex b = a.diff(x);
1628     ex c = univariate_gcd(a, b, x);
1629     ex w;
1630     if (c.is_equal(_ex1())) {
1631         w = a;
1632     } else {
1633         w = quo(a, c, x);
1634         ex y = quo(b, c, x);
1635         ex z = y - w.diff(x);
1636         while (!z.is_zero()) {
1637             ex g = univariate_gcd(w, z, x);
1638             res *= power(g, i);
1639             w = quo(w, g, x);
1640             y = quo(z, g, x);
1641             z = y - w.diff(x);
1642             i++;
1643         }
1644     }
1645     return res * power(w, i);
1646 }
1647
1648
1649 /*
1650  *  Normal form of rational functions
1651  */
1652
1653 /*
1654  *  Note: The internal normal() functions (= basic::normal() and overloaded
1655  *  functions) all return lists of the form {numerator, denominator}. This
1656  *  is to get around mul::eval()'s automatic expansion of numeric coefficients.
1657  *  E.g. (a+b)/3 is automatically converted to a/3+b/3 but we want to keep
1658  *  the information that (a+b) is the numerator and 3 is the denominator.
1659  */
1660
1661 /** Create a symbol for replacing the expression "e" (or return a previously
1662  *  assigned symbol). The symbol is appended to sym_lst and returned, the
1663  *  expression is appended to repl_lst.
1664  *  @see ex::normal */
1665 static ex replace_with_symbol(const ex &e, lst &sym_lst, lst &repl_lst)
1666 {
1667     // Expression already in repl_lst? Then return the assigned symbol
1668     for (unsigned i=0; i<repl_lst.nops(); i++)
1669         if (repl_lst.op(i).is_equal(e))
1670             return sym_lst.op(i);
1671     
1672     // Otherwise create new symbol and add to list, taking care that the
1673         // replacement expression doesn't contain symbols from the sym_lst
1674         // because subs() is not recursive
1675         symbol s;
1676         ex es(s);
1677         ex e_replaced = e.subs(sym_lst, repl_lst);
1678     sym_lst.append(es);
1679     repl_lst.append(e_replaced);
1680     return es;
1681 }
1682
1683 /** Create a symbol for replacing the expression "e" (or return a previously
1684  *  assigned symbol). An expression of the form "symbol == expression" is added
1685  *  to repl_lst and the symbol is returned.
1686  *  @see ex::to_rational */
1687 static ex replace_with_symbol(const ex &e, lst &repl_lst)
1688 {
1689     // Expression already in repl_lst? Then return the assigned symbol
1690     for (unsigned i=0; i<repl_lst.nops(); i++)
1691         if (repl_lst.op(i).op(1).is_equal(e))
1692             return repl_lst.op(i).op(0);
1693     
1694     // Otherwise create new symbol and add to list, taking care that the
1695         // replacement expression doesn't contain symbols from the sym_lst
1696         // because subs() is not recursive
1697         symbol s;
1698         ex es(s);
1699         ex e_replaced = e.subs(repl_lst);
1700     repl_lst.append(es == e_replaced);
1701     return es;
1702 }
1703
1704 /** Default implementation of ex::normal(). It replaces the object with a
1705  *  temporary symbol.
1706  *  @see ex::normal */
1707 ex basic::normal(lst &sym_lst, lst &repl_lst, int level) const
1708 {
1709     return (new lst(replace_with_symbol(*this, sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
1710 }
1711
1712
1713 /** Implementation of ex::normal() for symbols. This returns the unmodified symbol.
1714  *  @see ex::normal */
1715 ex symbol::normal(lst &sym_lst, lst &repl_lst, int level) const
1716 {
1717     return (new lst(*this, _ex1()))->setflag(status_flags::dynallocated);
1718 }
1719
1720
1721 /** Implementation of ex::normal() for a numeric. It splits complex numbers
1722  *  into re+I*im and replaces I and non-rational real numbers with a temporary
1723  *  symbol.
1724  *  @see ex::normal */
1725 ex numeric::normal(lst &sym_lst, lst &repl_lst, int level) const
1726 {
1727         numeric num = numer();
1728         ex numex = num;
1729
1730     if (num.is_real()) {
1731         if (!num.is_integer())
1732             numex = replace_with_symbol(numex, sym_lst, repl_lst);
1733     } else { // complex
1734         numeric re = num.real(), im = num.imag();
1735         ex re_ex = re.is_rational() ? re : replace_with_symbol(re, sym_lst, repl_lst);
1736         ex im_ex = im.is_rational() ? im : replace_with_symbol(im, sym_lst, repl_lst);
1737         numex = re_ex + im_ex * replace_with_symbol(I, sym_lst, repl_lst);
1738     }
1739
1740         // Denominator is always a real integer (see numeric::denom())
1741         return (new lst(numex, denom()))->setflag(status_flags::dynallocated);
1742 }
1743
1744
1745 /** Fraction cancellation.
1746  *  @param n  numerator
1747  *  @param d  denominator
1748  *  @return cancelled fraction {n, d} as a list */
1749 static ex frac_cancel(const ex &n, const ex &d)
1750 {
1751     ex num = n;
1752     ex den = d;
1753     numeric pre_factor = _num1();
1754
1755 //clog << "frac_cancel num = " << num << ", den = " << den << endl;
1756
1757     // Handle special cases where numerator or denominator is 0
1758     if (num.is_zero())
1759                 return (new lst(_ex0(), _ex1()))->setflag(status_flags::dynallocated);
1760     if (den.expand().is_zero())
1761         throw(std::overflow_error("frac_cancel: division by zero in frac_cancel"));
1762
1763     // Bring numerator and denominator to Z[X] by multiplying with
1764     // LCM of all coefficients' denominators
1765     numeric num_lcm = lcm_of_coefficients_denominators(num);
1766     numeric den_lcm = lcm_of_coefficients_denominators(den);
1767         num = multiply_lcm(num, num_lcm);
1768         den = multiply_lcm(den, den_lcm);
1769     pre_factor = den_lcm / num_lcm;
1770
1771     // Cancel GCD from numerator and denominator
1772     ex cnum, cden;
1773     if (gcd(num, den, &cnum, &cden, false) != _ex1()) {
1774                 num = cnum;
1775                 den = cden;
1776         }
1777
1778         // Make denominator unit normal (i.e. coefficient of first symbol
1779         // as defined by get_first_symbol() is made positive)
1780         const symbol *x;
1781         if (get_first_symbol(den, x)) {
1782                 GINAC_ASSERT(is_ex_exactly_of_type(den.unit(*x),numeric));
1783                 if (ex_to_numeric(den.unit(*x)).is_negative()) {
1784                         num *= _ex_1();
1785                         den *= _ex_1();
1786                 }
1787         }
1788
1789         // Return result as list
1790 //clog << " returns num = " << num << ", den = " << den << ", pre_factor = " << pre_factor << endl;
1791     return (new lst(num * pre_factor.numer(), den * pre_factor.denom()))->setflag(status_flags::dynallocated);
1792 }
1793
1794
1795 /** Implementation of ex::normal() for a sum. It expands terms and performs
1796  *  fractional addition.
1797  *  @see ex::normal */
1798 ex add::normal(lst &sym_lst, lst &repl_lst, int level) const
1799 {
1800     // Normalize and expand children, chop into summands
1801     exvector o;
1802     o.reserve(seq.size()+1);
1803     epvector::const_iterator it = seq.begin(), itend = seq.end();
1804     while (it != itend) {
1805
1806                 // Normalize and expand child
1807         ex n = recombine_pair_to_ex(*it).bp->normal(sym_lst, repl_lst, level-1).expand();
1808
1809                 // If numerator is a sum, chop into summands
1810         if (is_ex_exactly_of_type(n.op(0), add)) {
1811             epvector::const_iterator bit = ex_to_add(n.op(0)).seq.begin(), bitend = ex_to_add(n.op(0)).seq.end();
1812             while (bit != bitend) {
1813                 o.push_back((new lst(recombine_pair_to_ex(*bit), n.op(1)))->setflag(status_flags::dynallocated));
1814                 bit++;
1815             }
1816
1817                         // The overall_coeff is already normalized (== rational), we just
1818                         // split it into numerator and denominator
1819                         GINAC_ASSERT(ex_to_numeric(ex_to_add(n.op(0)).overall_coeff).is_rational());
1820                         numeric overall = ex_to_numeric(ex_to_add(n.op(0)).overall_coeff);
1821             o.push_back((new lst(overall.numer(), overall.denom() * n.op(1)))->setflag(status_flags::dynallocated));
1822         } else
1823             o.push_back(n);
1824         it++;
1825     }
1826     o.push_back(overall_coeff.bp->normal(sym_lst, repl_lst, level-1));
1827
1828         // o is now a vector of {numerator, denominator} lists
1829
1830     // Determine common denominator
1831     ex den = _ex1();
1832     exvector::const_iterator ait = o.begin(), aitend = o.end();
1833 //clog << "add::normal uses the following summands:\n";
1834     while (ait != aitend) {
1835 //clog << " num = " << ait->op(0) << ", den = " << ait->op(1) << endl;
1836         den = lcm(ait->op(1), den, false);
1837         ait++;
1838     }
1839 //clog << " common denominator = " << den << endl;
1840
1841     // Add fractions
1842     if (den.is_equal(_ex1())) {
1843
1844                 // Common denominator is 1, simply add all numerators
1845         exvector num_seq;
1846                 for (ait=o.begin(); ait!=aitend; ait++) {
1847                         num_seq.push_back(ait->op(0));
1848                 }
1849                 return (new lst((new add(num_seq))->setflag(status_flags::dynallocated), den))->setflag(status_flags::dynallocated);
1850
1851         } else {
1852
1853                 // Perform fractional addition
1854         exvector num_seq;
1855         for (ait=o.begin(); ait!=aitend; ait++) {
1856             ex q;
1857             if (!divide(den, ait->op(1), q, false)) {
1858                 // should not happen
1859                 throw(std::runtime_error("invalid expression in add::normal, division failed"));
1860             }
1861             num_seq.push_back((ait->op(0) * q).expand());
1862         }
1863         ex num = (new add(num_seq))->setflag(status_flags::dynallocated);
1864
1865         // Cancel common factors from num/den
1866         return frac_cancel(num, den);
1867     }
1868 }
1869
1870
1871 /** Implementation of ex::normal() for a product. It cancels common factors
1872  *  from fractions.
1873  *  @see ex::normal() */
1874 ex mul::normal(lst &sym_lst, lst &repl_lst, int level) const
1875 {
1876     // Normalize children, separate into numerator and denominator
1877         ex num = _ex1();
1878         ex den = _ex1(); 
1879         ex n;
1880     epvector::const_iterator it = seq.begin(), itend = seq.end();
1881     while (it != itend) {
1882                 n = recombine_pair_to_ex(*it).bp->normal(sym_lst, repl_lst, level-1);
1883                 num *= n.op(0);
1884                 den *= n.op(1);
1885         it++;
1886     }
1887         n = overall_coeff.bp->normal(sym_lst, repl_lst, level-1);
1888         num *= n.op(0);
1889         den *= n.op(1);
1890
1891         // Perform fraction cancellation
1892     return frac_cancel(num, den);
1893 }
1894
1895
1896 /** Implementation of ex::normal() for powers. It normalizes the basis,
1897  *  distributes integer exponents to numerator and denominator, and replaces
1898  *  non-integer powers by temporary symbols.
1899  *  @see ex::normal */
1900 ex power::normal(lst &sym_lst, lst &repl_lst, int level) const
1901 {
1902         // Normalize basis
1903     ex n = basis.bp->normal(sym_lst, repl_lst, level-1);
1904
1905         if (exponent.info(info_flags::integer)) {
1906
1907             if (exponent.info(info_flags::positive)) {
1908
1909                         // (a/b)^n -> {a^n, b^n}
1910                         return (new lst(power(n.op(0), exponent), power(n.op(1), exponent)))->setflag(status_flags::dynallocated);
1911
1912                 } else if (exponent.info(info_flags::negative)) {
1913
1914                         // (a/b)^-n -> {b^n, a^n}
1915                         return (new lst(power(n.op(1), -exponent), power(n.op(0), -exponent)))->setflag(status_flags::dynallocated);
1916                 }
1917
1918         } else {
1919
1920                 if (exponent.info(info_flags::positive)) {
1921
1922                         // (a/b)^x -> {sym((a/b)^x), 1}
1923                         return (new lst(replace_with_symbol(power(n.op(0) / n.op(1), exponent), sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
1924
1925                 } else if (exponent.info(info_flags::negative)) {
1926
1927                         if (n.op(1).is_equal(_ex1())) {
1928
1929                                 // a^-x -> {1, sym(a^x)}
1930                                 return (new lst(_ex1(), replace_with_symbol(power(n.op(0), -exponent), sym_lst, repl_lst)))->setflag(status_flags::dynallocated);
1931
1932                         } else {
1933
1934                                 // (a/b)^-x -> {sym((b/a)^x), 1}
1935                                 return (new lst(replace_with_symbol(power(n.op(1) / n.op(0), -exponent), sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
1936                         }
1937
1938                 } else {        // exponent not numeric
1939
1940                         // (a/b)^x -> {sym((a/b)^x, 1}
1941                         return (new lst(replace_with_symbol(power(n.op(0) / n.op(1), exponent), sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
1942                 }
1943     }
1944 }
1945
1946
1947 /** Implementation of ex::normal() for pseries. It normalizes each coefficient and
1948  *  replaces the series by a temporary symbol.
1949  *  @see ex::normal */
1950 ex pseries::normal(lst &sym_lst, lst &repl_lst, int level) const
1951 {
1952     epvector new_seq;
1953     new_seq.reserve(seq.size());
1954
1955     epvector::const_iterator it = seq.begin(), itend = seq.end();
1956     while (it != itend) {
1957         new_seq.push_back(expair(it->rest.normal(), it->coeff));
1958         it++;
1959     }
1960     ex n = pseries(relational(var,point), new_seq);
1961         return (new lst(replace_with_symbol(n, sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
1962 }
1963
1964
1965 /** Implementation of ex::normal() for relationals. It normalizes both sides.
1966  *  @see ex::normal */
1967 ex relational::normal(lst &sym_lst, lst &repl_lst, int level) const
1968 {
1969         return (new lst(relational(lh.normal(), rh.normal(), o), _ex1()))->setflag(status_flags::dynallocated);
1970 }
1971
1972
1973 /** Normalization of rational functions.
1974  *  This function converts an expression to its normal form
1975  *  "numerator/denominator", where numerator and denominator are (relatively
1976  *  prime) polynomials. Any subexpressions which are not rational functions
1977  *  (like non-rational numbers, non-integer powers or functions like sin(),
1978  *  cos() etc.) are replaced by temporary symbols which are re-substituted by
1979  *  the (normalized) subexpressions before normal() returns (this way, any
1980  *  expression can be treated as a rational function). normal() is applied
1981  *  recursively to arguments of functions etc.
1982  *
1983  *  @param level maximum depth of recursion
1984  *  @return normalized expression */
1985 ex ex::normal(int level) const
1986 {
1987     lst sym_lst, repl_lst;
1988
1989     ex e = bp->normal(sym_lst, repl_lst, level);
1990         GINAC_ASSERT(is_ex_of_type(e, lst));
1991
1992         // Re-insert replaced symbols
1993     if (sym_lst.nops() > 0)
1994         e = e.subs(sym_lst, repl_lst);
1995
1996         // Convert {numerator, denominator} form back to fraction
1997     return e.op(0) / e.op(1);
1998 }
1999
2000 /** Numerator of an expression. If the expression is not of the normal form
2001  *  "numerator/denominator", it is first converted to this form and then the
2002  *  numerator is returned.
2003  *
2004  *  @see ex::normal
2005  *  @return numerator */
2006 ex ex::numer(void) const
2007 {
2008     lst sym_lst, repl_lst;
2009
2010     ex e = bp->normal(sym_lst, repl_lst, 0);
2011         GINAC_ASSERT(is_ex_of_type(e, lst));
2012
2013         // Re-insert replaced symbols
2014     if (sym_lst.nops() > 0)
2015         return e.op(0).subs(sym_lst, repl_lst);
2016         else
2017                 return e.op(0);
2018 }
2019
2020 /** Denominator of an expression. If the expression is not of the normal form
2021  *  "numerator/denominator", it is first converted to this form and then the
2022  *  denominator is returned.
2023  *
2024  *  @see ex::normal
2025  *  @return denominator */
2026 ex ex::denom(void) const
2027 {
2028     lst sym_lst, repl_lst;
2029
2030     ex e = bp->normal(sym_lst, repl_lst, 0);
2031         GINAC_ASSERT(is_ex_of_type(e, lst));
2032
2033         // Re-insert replaced symbols
2034     if (sym_lst.nops() > 0)
2035         return e.op(1).subs(sym_lst, repl_lst);
2036         else
2037                 return e.op(1);
2038 }
2039
2040
2041 /** Default implementation of ex::to_rational(). It replaces the object with a
2042  *  temporary symbol.
2043  *  @see ex::to_rational */
2044 ex basic::to_rational(lst &repl_lst) const
2045 {
2046         return replace_with_symbol(*this, repl_lst);
2047 }
2048
2049
2050 /** Implementation of ex::to_rational() for symbols. This returns the
2051  *  unmodified symbol.
2052  *  @see ex::to_rational */
2053 ex symbol::to_rational(lst &repl_lst) const
2054 {
2055     return *this;
2056 }
2057
2058
2059 /** Implementation of ex::to_rational() for a numeric. It splits complex
2060  *  numbers into re+I*im and replaces I and non-rational real numbers with a
2061  *  temporary symbol.
2062  *  @see ex::to_rational */
2063 ex numeric::to_rational(lst &repl_lst) const
2064 {
2065     if (is_real()) {
2066         if (!is_rational())
2067             return replace_with_symbol(*this, repl_lst);
2068     } else { // complex
2069         numeric re = real();
2070         numeric im = imag();
2071         ex re_ex = re.is_rational() ? re : replace_with_symbol(re, repl_lst);
2072         ex im_ex = im.is_rational() ? im : replace_with_symbol(im, repl_lst);
2073         return re_ex + im_ex * replace_with_symbol(I, repl_lst);
2074     }
2075         return *this;
2076 }
2077
2078
2079 /** Implementation of ex::to_rational() for powers. It replaces non-integer
2080  *  powers by temporary symbols.
2081  *  @see ex::to_rational */
2082 ex power::to_rational(lst &repl_lst) const
2083 {
2084         if (exponent.info(info_flags::integer))
2085                 return power(basis.to_rational(repl_lst), exponent);
2086         else
2087                 return replace_with_symbol(*this, repl_lst);
2088 }
2089
2090
2091 /** Implementation of ex::to_rational() for expairseqs.
2092  *  @see ex::to_rational */
2093 ex expairseq::to_rational(lst &repl_lst) const
2094 {
2095     epvector s;
2096     s.reserve(seq.size());
2097     for (epvector::const_iterator it=seq.begin(); it!=seq.end(); ++it) {
2098         s.push_back(split_ex_to_pair(recombine_pair_to_ex(*it).to_rational(repl_lst)));
2099         // s.push_back(combine_ex_with_coeff_to_pair((*it).rest.to_rational(repl_lst),
2100     }
2101     ex oc = overall_coeff.to_rational(repl_lst);
2102     if (oc.info(info_flags::numeric))
2103         return thisexpairseq(s, overall_coeff);
2104     else s.push_back(combine_ex_with_coeff_to_pair(oc,_ex1()));
2105     return thisexpairseq(s, default_overall_coeff());
2106 }
2107
2108
2109 /** Rationalization of non-rational functions.
2110  *  This function converts a general expression to a rational polynomial
2111  *  by replacing all non-rational subexpressions (like non-rational numbers,
2112  *  non-integer powers or functions like sin(), cos() etc.) to temporary
2113  *  symbols. This makes it possible to use functions like gcd() and divide()
2114  *  on non-rational functions by applying to_rational() on the arguments,
2115  *  calling the desired function and re-substituting the temporary symbols
2116  *  in the result. To make the last step possible, all temporary symbols and
2117  *  their associated expressions are collected in the list specified by the
2118  *  repl_lst parameter in the form {symbol == expression}, ready to be passed
2119  *  as an argument to ex::subs().
2120  *
2121  *  @param repl_lst collects a list of all temporary symbols and their replacements
2122  *  @return rationalized expression */
2123 ex ex::to_rational(lst &repl_lst) const
2124 {
2125         return bp->to_rational(repl_lst);
2126 }
2127
2128
2129 #ifndef NO_NAMESPACE_GINAC
2130 } // namespace GiNaC
2131 #endif // ndef NO_NAMESPACE_GINAC