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