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