]> www.ginac.de Git - ginac.git/blob - ginac/normal.cpp
- speedup by declaring x_pt and so on const
[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 /*
10  *  GiNaC Copyright (C) 1999 Johannes Gutenberg University Mainz, Germany
11  *
12  *  This program is free software; you can redistribute it and/or modify
13  *  it under the terms of the GNU General Public License as published by
14  *  the Free Software Foundation; either version 2 of the License, or
15  *  (at your option) any later version.
16  *
17  *  This program is distributed in the hope that it will be useful,
18  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
19  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  *  GNU General Public License for more details.
21  *
22  *  You should have received a copy of the GNU General Public License
23  *  along with this program; if not, write to the Free Software
24  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
25  */
26
27 #include <stdexcept>
28 #include <algorithm>
29 #include <map>
30
31 #include "normal.h"
32 #include "basic.h"
33 #include "ex.h"
34 #include "add.h"
35 #include "constant.h"
36 #include "expairseq.h"
37 #include "fail.h"
38 #include "indexed.h"
39 #include "inifcns.h"
40 #include "lst.h"
41 #include "mul.h"
42 #include "ncmul.h"
43 #include "numeric.h"
44 #include "power.h"
45 #include "relational.h"
46 #include "series.h"
47 #include "symbol.h"
48 #include "utils.h"
49
50 #ifndef NO_GINAC_NAMESPACE
51 namespace GiNaC {
52 #endif // ndef NO_GINAC_NAMESPACE
53
54 // If comparing expressions (ex::compare()) is fast, you can set this to 1.
55 // Some routines like quo(), rem() and gcd() will then return a quick answer
56 // when they are called with two identical arguments.
57 #define FAST_COMPARE 1
58
59 // Set this if you want divide_in_z() to use remembering
60 #define USE_REMEMBER 1
61
62
63 /** Return pointer to first symbol found in expression.  Due to GiNaCĀ“s
64  *  internal ordering of terms, it may not be obvious which symbol this
65  *  function returns for a given expression.
66  *
67  *  @param e  expression to search
68  *  @param x  pointer to first symbol found (returned)
69  *  @return "false" if no symbol was found, "true" otherwise */
70
71 static bool get_first_symbol(const ex &e, const symbol *&x)
72 {
73     if (is_ex_exactly_of_type(e, symbol)) {
74         x = static_cast<symbol *>(e.bp);
75         return true;
76     } else if (is_ex_exactly_of_type(e, add) || is_ex_exactly_of_type(e, mul)) {
77         for (int i=0; i<e.nops(); i++)
78             if (get_first_symbol(e.op(i), x))
79                 return true;
80     } else if (is_ex_exactly_of_type(e, power)) {
81         if (get_first_symbol(e.op(0), x))
82             return true;
83     }
84     return false;
85 }
86
87
88 /*
89  *  Statistical information about symbols in polynomials
90  */
91
92 /** This structure holds information about the highest and lowest degrees
93  *  in which a symbol appears in two multivariate polynomials "a" and "b".
94  *  A vector of these structures with information about all symbols in
95  *  two polynomials can be created with the function get_symbol_stats().
96  *
97  *  @see get_symbol_stats */
98 struct sym_desc {
99     /** Pointer to symbol */
100     const symbol *sym;
101
102     /** Highest degree of symbol in polynomial "a" */
103     int deg_a;
104
105     /** Highest degree of symbol in polynomial "b" */
106     int deg_b;
107
108     /** Lowest degree of symbol in polynomial "a" */
109     int ldeg_a;
110
111     /** Lowest degree of symbol in polynomial "b" */
112     int ldeg_b;
113
114     /** Minimum of ldeg_a and ldeg_b (Used for sorting) */
115     int min_deg;
116
117     /** Commparison operator for sorting */
118     bool operator<(const sym_desc &x) const {return min_deg < x.min_deg;}
119 };
120
121 // Vector of sym_desc structures
122 typedef vector<sym_desc> sym_desc_vec;
123
124 // Add symbol the sym_desc_vec (used internally by get_symbol_stats())
125 static void add_symbol(const symbol *s, sym_desc_vec &v)
126 {
127     sym_desc_vec::iterator it = v.begin(), itend = v.end();
128     while (it != itend) {
129         if (it->sym->compare(*s) == 0)  // If it's already in there, don't add it a second time
130             return;
131         it++;
132     }
133     sym_desc d;
134     d.sym = s;
135     v.push_back(d);
136 }
137
138 // Collect all symbols of an expression (used internally by get_symbol_stats())
139 static void collect_symbols(const ex &e, sym_desc_vec &v)
140 {
141     if (is_ex_exactly_of_type(e, symbol)) {
142         add_symbol(static_cast<symbol *>(e.bp), v);
143     } else if (is_ex_exactly_of_type(e, add) || is_ex_exactly_of_type(e, mul)) {
144         for (int i=0; i<e.nops(); i++)
145             collect_symbols(e.op(i), v);
146     } else if (is_ex_exactly_of_type(e, power)) {
147         collect_symbols(e.op(0), v);
148     }
149 }
150
151 /** Collect statistical information about symbols in polynomials.
152  *  This function fills in a vector of "sym_desc" structs which contain
153  *  information about the highest and lowest degrees of all symbols that
154  *  appear in two polynomials. The vector is then sorted by minimum
155  *  degree (lowest to highest). The information gathered by this
156  *  function is used by the GCD routines to identify trivial factors
157  *  and to determine which variable to choose as the main variable
158  *  for GCD computation.
159  *
160  *  @param a  first multivariate polynomial
161  *  @param b  second multivariate polynomial
162  *  @param v  vector of sym_desc structs (filled in) */
163
164 static void get_symbol_stats(const ex &a, const ex &b, sym_desc_vec &v)
165 {
166     collect_symbols(a.eval(), v);   // eval() to expand assigned symbols
167     collect_symbols(b.eval(), v);
168     sym_desc_vec::iterator it = v.begin(), itend = v.end();
169     while (it != itend) {
170         int deg_a = a.degree(*(it->sym));
171         int deg_b = b.degree(*(it->sym));
172         it->deg_a = deg_a;
173         it->deg_b = deg_b;
174         it->min_deg = min(deg_a, deg_b);
175         it->ldeg_a = a.ldegree(*(it->sym));
176         it->ldeg_b = b.ldegree(*(it->sym));
177         it++;
178     }
179     sort(v.begin(), v.end());
180 }
181
182
183 /*
184  *  Computation of LCM of denominators of coefficients of a polynomial
185  */
186
187 // Compute LCM of denominators of coefficients by going through the
188 // expression recursively (used internally by lcm_of_coefficients_denominators())
189 static numeric lcmcoeff(const ex &e, const numeric &l)
190 {
191     if (e.info(info_flags::rational))
192         return lcm(ex_to_numeric(e).denom(), l);
193     else if (is_ex_exactly_of_type(e, add) || is_ex_exactly_of_type(e, mul)) {
194         numeric c = _num1();
195         for (int i=0; i<e.nops(); i++) {
196             c = lcmcoeff(e.op(i), c);
197         }
198         return lcm(c, l);
199     } else if (is_ex_exactly_of_type(e, power))
200         return lcmcoeff(e.op(0), l);
201     return l;
202 }
203
204 /** Compute LCM of denominators of coefficients of a polynomial.
205  *  Given a polynomial with rational coefficients, this function computes
206  *  the LCM of the denominators of all coefficients. This can be used
207  *  To bring a polynomial from Q[X] to Z[X].
208  *
209  *  @param e  multivariate polynomial
210  *  @return LCM of denominators of coefficients */
211
212 static numeric lcm_of_coefficients_denominators(const ex &e)
213 {
214     return lcmcoeff(e.expand(), _num1());
215 }
216
217
218 /** Compute the integer content (= GCD of all numeric coefficients) of an
219  *  expanded polynomial.
220  *
221  *  @param e  expanded polynomial
222  *  @return integer content */
223
224 numeric ex::integer_content(void) const
225 {
226     GINAC_ASSERT(bp!=0);
227     return bp->integer_content();
228 }
229
230 numeric basic::integer_content(void) const
231 {
232     return _num1();
233 }
234
235 numeric numeric::integer_content(void) const
236 {
237     return abs(*this);
238 }
239
240 numeric add::integer_content(void) const
241 {
242     epvector::const_iterator it = seq.begin();
243     epvector::const_iterator itend = seq.end();
244     numeric c = _num0();
245     while (it != itend) {
246         GINAC_ASSERT(!is_ex_exactly_of_type(it->rest,numeric));
247         GINAC_ASSERT(is_ex_exactly_of_type(it->coeff,numeric));
248         c = gcd(ex_to_numeric(it->coeff), c);
249         it++;
250     }
251     GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
252     c = gcd(ex_to_numeric(overall_coeff),c);
253     return c;
254 }
255
256 numeric mul::integer_content(void) const
257 {
258 #ifdef DO_GINAC_ASSERT
259     epvector::const_iterator it = seq.begin();
260     epvector::const_iterator itend = seq.end();
261     while (it != itend) {
262         GINAC_ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*it),numeric));
263         ++it;
264     }
265 #endif // def DO_GINAC_ASSERT
266     GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
267     return abs(ex_to_numeric(overall_coeff));
268 }
269
270
271 /*
272  *  Polynomial quotients and remainders
273  */
274
275 /** Quotient q(x) of polynomials a(x) and b(x) in Q[x].
276  *  It satisfies a(x)=b(x)*q(x)+r(x).
277  *
278  *  @param a  first polynomial in x (dividend)
279  *  @param b  second polynomial in x (divisor)
280  *  @param x  a and b are polynomials in x
281  *  @param check_args  check whether a and b are polynomials with rational
282  *         coefficients (defaults to "true")
283  *  @return quotient of a and b in Q[x] */
284
285 ex quo(const ex &a, const ex &b, const symbol &x, bool check_args)
286 {
287     if (b.is_zero())
288         throw(std::overflow_error("quo: division by zero"));
289     if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric))
290         return a / b;
291 #if FAST_COMPARE
292     if (a.is_equal(b))
293         return _ex1();
294 #endif
295     if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
296         throw(std::invalid_argument("quo: arguments must be polynomials over the rationals"));
297
298     // Polynomial long division
299     ex q = _ex0();
300     ex r = a.expand();
301     if (r.is_zero())
302         return r;
303     int bdeg = b.degree(x);
304     int rdeg = r.degree(x);
305     ex blcoeff = b.expand().coeff(x, bdeg);
306     bool blcoeff_is_numeric = is_ex_exactly_of_type(blcoeff, numeric);
307     while (rdeg >= bdeg) {
308         ex term, rcoeff = r.coeff(x, rdeg);
309         if (blcoeff_is_numeric)
310             term = rcoeff / blcoeff;
311         else {
312             if (!divide(rcoeff, blcoeff, term, false))
313                 return *new ex(fail());
314         }
315         term *= power(x, rdeg - bdeg);
316         q += term;
317         r -= (term * b).expand();
318         if (r.is_zero())
319             break;
320         rdeg = r.degree(x);
321     }
322     return q;
323 }
324
325
326 /** Remainder r(x) of polynomials a(x) and b(x) in Q[x].
327  *  It satisfies a(x)=b(x)*q(x)+r(x).
328  *
329  *  @param a  first polynomial in x (dividend)
330  *  @param b  second polynomial in x (divisor)
331  *  @param x  a and b are polynomials in x
332  *  @param check_args  check whether a and b are polynomials with rational
333  *         coefficients (defaults to "true")
334  *  @return remainder of a(x) and b(x) in Q[x] */
335
336 ex rem(const ex &a, const ex &b, const symbol &x, bool check_args)
337 {
338     if (b.is_zero())
339         throw(std::overflow_error("rem: division by zero"));
340     if (is_ex_exactly_of_type(a, numeric)) {
341         if  (is_ex_exactly_of_type(b, numeric))
342             return _ex0();
343         else
344             return b;
345     }
346 #if FAST_COMPARE
347     if (a.is_equal(b))
348         return _ex0();
349 #endif
350     if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
351         throw(std::invalid_argument("rem: arguments must be polynomials over the rationals"));
352
353     // Polynomial long division
354     ex r = a.expand();
355     if (r.is_zero())
356         return r;
357     int bdeg = b.degree(x);
358     int rdeg = r.degree(x);
359     ex blcoeff = b.expand().coeff(x, bdeg);
360     bool blcoeff_is_numeric = is_ex_exactly_of_type(blcoeff, numeric);
361     while (rdeg >= bdeg) {
362         ex term, rcoeff = r.coeff(x, rdeg);
363         if (blcoeff_is_numeric)
364             term = rcoeff / blcoeff;
365         else {
366             if (!divide(rcoeff, blcoeff, term, false))
367                 return *new ex(fail());
368         }
369         term *= power(x, rdeg - bdeg);
370         r -= (term * b).expand();
371         if (r.is_zero())
372             break;
373         rdeg = r.degree(x);
374     }
375     return r;
376 }
377
378
379 /** Pseudo-remainder of polynomials a(x) and b(x) in Z[x].
380  *
381  *  @param a  first polynomial in x (dividend)
382  *  @param b  second polynomial in x (divisor)
383  *  @param x  a and b are polynomials in x
384  *  @param check_args  check whether a and b are polynomials with rational
385  *         coefficients (defaults to "true")
386  *  @return pseudo-remainder of a(x) and b(x) in Z[x] */
387
388 ex prem(const ex &a, const ex &b, const symbol &x, bool check_args)
389 {
390     if (b.is_zero())
391         throw(std::overflow_error("prem: division by zero"));
392     if (is_ex_exactly_of_type(a, numeric)) {
393         if (is_ex_exactly_of_type(b, numeric))
394             return _ex0();
395         else
396             return b;
397     }
398     if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
399         throw(std::invalid_argument("prem: arguments must be polynomials over the rationals"));
400
401     // Polynomial long division
402     ex r = a.expand();
403     ex eb = b.expand();
404     int rdeg = r.degree(x);
405     int bdeg = eb.degree(x);
406     ex blcoeff;
407     if (bdeg <= rdeg) {
408         blcoeff = eb.coeff(x, bdeg);
409         if (bdeg == 0)
410             eb = _ex0();
411         else
412             eb -= blcoeff * power(x, bdeg);
413     } else
414         blcoeff = _ex1();
415
416     int delta = rdeg - bdeg + 1, i = 0;
417     while (rdeg >= bdeg && !r.is_zero()) {
418         ex rlcoeff = r.coeff(x, rdeg);
419         ex term = (power(x, rdeg - bdeg) * eb * rlcoeff).expand();
420         if (rdeg == 0)
421             r = _ex0();
422         else
423             r -= rlcoeff * power(x, rdeg);
424         r = (blcoeff * r).expand() - term;
425         rdeg = r.degree(x);
426         i++;
427     }
428     return power(blcoeff, delta - i) * r;
429 }
430
431
432 /** Exact polynomial division of a(X) by b(X) in Q[X].
433  *  
434  *  @param a  first multivariate polynomial (dividend)
435  *  @param b  second multivariate polynomial (divisor)
436  *  @param q  quotient (returned)
437  *  @param check_args  check whether a and b are polynomials with rational
438  *         coefficients (defaults to "true")
439  *  @return "true" when exact division succeeds (quotient returned in q),
440  *          "false" otherwise */
441
442 bool divide(const ex &a, const ex &b, ex &q, bool check_args)
443 {
444     q = _ex0();
445     if (b.is_zero())
446         throw(std::overflow_error("divide: division by zero"));
447     if (is_ex_exactly_of_type(b, numeric)) {
448         q = a / b;
449         return true;
450     } else if (is_ex_exactly_of_type(a, numeric))
451         return false;
452 #if FAST_COMPARE
453     if (a.is_equal(b)) {
454         q = _ex1();
455         return true;
456     }
457 #endif
458     if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
459         throw(std::invalid_argument("divide: arguments must be polynomials over the rationals"));
460
461     // Find first symbol
462     const symbol *x;
463     if (!get_first_symbol(a, x) && !get_first_symbol(b, x))
464         throw(std::invalid_argument("invalid expression in divide()"));
465
466     // Polynomial long division (recursive)
467     ex r = a.expand();
468     if (r.is_zero())
469         return true;
470     int bdeg = b.degree(*x);
471     int rdeg = r.degree(*x);
472     ex blcoeff = b.expand().coeff(*x, bdeg);
473     bool blcoeff_is_numeric = is_ex_exactly_of_type(blcoeff, numeric);
474     while (rdeg >= bdeg) {
475         ex term, rcoeff = r.coeff(*x, rdeg);
476         if (blcoeff_is_numeric)
477             term = rcoeff / blcoeff;
478         else
479             if (!divide(rcoeff, blcoeff, term, false))
480                 return false;
481         term *= power(*x, rdeg - bdeg);
482         q += term;
483         r -= (term * b).expand();
484         if (r.is_zero())
485             return true;
486         rdeg = r.degree(*x);
487     }
488     return false;
489 }
490
491
492 #if USE_REMEMBER
493 /*
494  *  Remembering
495  */
496
497 typedef pair<ex, ex> ex2;
498 typedef pair<ex, bool> exbool;
499
500 struct ex2_less {
501     bool operator() (const ex2 p, const ex2 q) const 
502     {
503         return p.first.compare(q.first) < 0 || (!(q.first.compare(p.first) < 0) && p.second.compare(q.second) < 0);        
504     }
505 };
506
507 typedef map<ex2, exbool, ex2_less> ex2_exbool_remember;
508 #endif
509
510
511 /** Exact polynomial division of a(X) by b(X) in Z[X].
512  *  This functions works like divide() but the input and output polynomials are
513  *  in Z[X] instead of Q[X] (i.e. they have integer coefficients). Unlike
514  *  divide(), it doesnĀ“t check whether the input polynomials really are integer
515  *  polynomials, so be careful of what you pass in. Also, you have to run
516  *  get_symbol_stats() over the input polynomials before calling this function
517  *  and pass an iterator to the first element of the sym_desc vector. This
518  *  function is used internally by the heur_gcd().
519  *  
520  *  @param a  first multivariate polynomial (dividend)
521  *  @param b  second multivariate polynomial (divisor)
522  *  @param q  quotient (returned)
523  *  @param var  iterator to first element of vector of sym_desc structs
524  *  @return "true" when exact division succeeds (the quotient is returned in
525  *          q), "false" otherwise.
526  *  @see get_symbol_stats, heur_gcd */
527 static bool divide_in_z(const ex &a, const ex &b, ex &q, sym_desc_vec::const_iterator var)
528 {
529     q = _ex0();
530     if (b.is_zero())
531         throw(std::overflow_error("divide_in_z: division by zero"));
532     if (b.is_equal(_ex1())) {
533         q = a;
534         return true;
535     }
536     if (is_ex_exactly_of_type(a, numeric)) {
537         if (is_ex_exactly_of_type(b, numeric)) {
538             q = a / b;
539             return q.info(info_flags::integer);
540         } else
541             return false;
542     }
543 #if FAST_COMPARE
544     if (a.is_equal(b)) {
545         q = _ex1();
546         return true;
547     }
548 #endif
549
550 #if USE_REMEMBER
551     // Remembering
552     static ex2_exbool_remember dr_remember;
553     ex2_exbool_remember::const_iterator remembered = dr_remember.find(ex2(a, b));
554     if (remembered != dr_remember.end()) {
555         q = remembered->second.first;
556         return remembered->second.second;
557     }
558 #endif
559
560     // Main symbol
561     const symbol *x = var->sym;
562
563     // Compare degrees
564     int adeg = a.degree(*x), bdeg = b.degree(*x);
565     if (bdeg > adeg)
566         return false;
567
568 #if 1
569
570     // Polynomial long division (recursive)
571     ex r = a.expand();
572     if (r.is_zero())
573         return true;
574     int rdeg = adeg;
575     ex eb = b.expand();
576     ex blcoeff = eb.coeff(*x, bdeg);
577     while (rdeg >= bdeg) {
578         ex term, rcoeff = r.coeff(*x, rdeg);
579         if (!divide_in_z(rcoeff, blcoeff, term, var+1))
580             break;
581         term = (term * power(*x, rdeg - bdeg)).expand();
582         q += term;
583         r -= (term * eb).expand();
584         if (r.is_zero()) {
585 #if USE_REMEMBER
586             dr_remember[ex2(a, b)] = exbool(q, true);
587 #endif
588             return true;
589         }
590         rdeg = r.degree(*x);
591     }
592 #if USE_REMEMBER
593     dr_remember[ex2(a, b)] = exbool(q, false);
594 #endif
595     return false;
596
597 #else
598
599     // Trial division using polynomial interpolation
600     int i, k;
601
602     // Compute values at evaluation points 0..adeg
603     vector<numeric> alpha; alpha.reserve(adeg + 1);
604     exvector u; u.reserve(adeg + 1);
605     numeric point = _num0();
606     ex c;
607     for (i=0; i<=adeg; i++) {
608         ex bs = b.subs(*x == point);
609         while (bs.is_zero()) {
610             point += _num1();
611             bs = b.subs(*x == point);
612         }
613         if (!divide_in_z(a.subs(*x == point), bs, c, var+1))
614             return false;
615         alpha.push_back(point);
616         u.push_back(c);
617         point += _num1();
618     }
619
620     // Compute inverses
621     vector<numeric> rcp; rcp.reserve(adeg + 1);
622     rcp.push_back(0);
623     for (k=1; k<=adeg; k++) {
624         numeric product = alpha[k] - alpha[0];
625         for (i=1; i<k; i++)
626             product *= alpha[k] - alpha[i];
627         rcp.push_back(product.inverse());
628     }
629
630     // Compute Newton coefficients
631     exvector v; v.reserve(adeg + 1);
632     v.push_back(u[0]);
633     for (k=1; k<=adeg; k++) {
634         ex temp = v[k - 1];
635         for (i=k-2; i>=0; i--)
636             temp = temp * (alpha[k] - alpha[i]) + v[i];
637         v.push_back((u[k] - temp) * rcp[k]);
638     }
639
640     // Convert from Newton form to standard form
641     c = v[adeg];
642     for (k=adeg-1; k>=0; k--)
643         c = c * (*x - alpha[k]) + v[k];
644
645     if (c.degree(*x) == (adeg - bdeg)) {
646         q = c.expand();
647         return true;
648     } else
649         return false;
650 #endif
651 }
652
653
654 /*
655  *  Separation of unit part, content part and primitive part of polynomials
656  */
657
658 /** Compute unit part (= sign of leading coefficient) of a multivariate
659  *  polynomial in Z[x]. The product of unit part, content part, and primitive
660  *  part is the polynomial itself.
661  *
662  *  @param x  variable in which to compute the unit part
663  *  @return unit part
664  *  @see ex::content, ex::primpart */
665 ex ex::unit(const symbol &x) const
666 {
667     ex c = expand().lcoeff(x);
668     if (is_ex_exactly_of_type(c, numeric))
669         return c < _ex0() ? _ex_1() : _ex1();
670     else {
671         const symbol *y;
672         if (get_first_symbol(c, y))
673             return c.unit(*y);
674         else
675             throw(std::invalid_argument("invalid expression in unit()"));
676     }
677 }
678
679
680 /** Compute content part (= unit normal GCD of all coefficients) of a
681  *  multivariate polynomial in Z[x].  The product of unit part, content part,
682  *  and primitive part is the polynomial itself.
683  *
684  *  @param x  variable in which to compute the content part
685  *  @return content part
686  *  @see ex::unit, ex::primpart */
687 ex ex::content(const symbol &x) const
688 {
689     if (is_zero())
690         return _ex0();
691     if (is_ex_exactly_of_type(*this, numeric))
692         return info(info_flags::negative) ? -*this : *this;
693     ex e = expand();
694     if (e.is_zero())
695         return _ex0();
696
697     // First, try the integer content
698     ex c = e.integer_content();
699     ex r = e / c;
700     ex lcoeff = r.lcoeff(x);
701     if (lcoeff.info(info_flags::integer))
702         return c;
703
704     // GCD of all coefficients
705     int deg = e.degree(x);
706     int ldeg = e.ldegree(x);
707     if (deg == ldeg)
708         return e.lcoeff(x) / e.unit(x);
709     c = _ex0();
710     for (int i=ldeg; i<=deg; i++)
711         c = gcd(e.coeff(x, i), c, NULL, NULL, false);
712     return c;
713 }
714
715
716 /** Compute primitive part of a multivariate polynomial in Z[x].
717  *  The product of unit part, content part, and primitive part is the
718  *  polynomial itself.
719  *
720  *  @param x  variable in which to compute the primitive part
721  *  @return primitive part
722  *  @see ex::unit, ex::content */
723 ex ex::primpart(const symbol &x) const
724 {
725     if (is_zero())
726         return _ex0();
727     if (is_ex_exactly_of_type(*this, numeric))
728         return _ex1();
729
730     ex c = content(x);
731     if (c.is_zero())
732         return _ex0();
733     ex u = unit(x);
734     if (is_ex_exactly_of_type(c, numeric))
735         return *this / (c * u);
736     else
737         return quo(*this, c * u, x, false);
738 }
739
740
741 /** Compute primitive part of a multivariate polynomial in Z[x] when the
742  *  content part is already known. This function is faster in computing the
743  *  primitive part than the previous function.
744  *
745  *  @param x  variable in which to compute the primitive part
746  *  @param c  previously computed content part
747  *  @return primitive part */
748
749 ex ex::primpart(const symbol &x, const ex &c) const
750 {
751     if (is_zero())
752         return _ex0();
753     if (c.is_zero())
754         return _ex0();
755     if (is_ex_exactly_of_type(*this, numeric))
756         return _ex1();
757
758     ex u = unit(x);
759     if (is_ex_exactly_of_type(c, numeric))
760         return *this / (c * u);
761     else
762         return quo(*this, c * u, x, false);
763 }
764
765
766 /*
767  *  GCD of multivariate polynomials
768  */
769
770 /** Compute GCD of multivariate polynomials using the subresultant PRS
771  *  algorithm. This function is used internally gy gcd().
772  *
773  *  @param a  first multivariate polynomial
774  *  @param b  second multivariate polynomial
775  *  @param x  pointer to symbol (main variable) in which to compute the GCD in
776  *  @return the GCD as a new expression
777  *  @see gcd */
778
779 static ex sr_gcd(const ex &a, const ex &b, const symbol *x)
780 {
781     // Sort c and d so that c has higher degree
782     ex c, d;
783     int adeg = a.degree(*x), bdeg = b.degree(*x);
784     int cdeg, ddeg;
785     if (adeg >= bdeg) {
786         c = a;
787         d = b;
788         cdeg = adeg;
789         ddeg = bdeg;
790     } else {
791         c = b;
792         d = a;
793         cdeg = bdeg;
794         ddeg = adeg;
795     }
796
797     // Remove content from c and d, to be attached to GCD later
798     ex cont_c = c.content(*x);
799     ex cont_d = d.content(*x);
800     ex gamma = gcd(cont_c, cont_d, NULL, NULL, false);
801     if (ddeg == 0)
802         return gamma;
803     c = c.primpart(*x, cont_c);
804     d = d.primpart(*x, cont_d);
805
806     // First element of subresultant sequence
807     ex r = _ex0(), ri = _ex1(), psi = _ex1();
808     int delta = cdeg - ddeg;
809
810     for (;;) {
811         // Calculate polynomial pseudo-remainder
812         r = prem(c, d, *x, false);
813         if (r.is_zero())
814             return gamma * d.primpart(*x);
815         c = d;
816         cdeg = ddeg;
817         if (!divide(r, ri * power(psi, delta), d, false))
818             throw(std::runtime_error("invalid expression in sr_gcd(), division failed"));
819         ddeg = d.degree(*x);
820         if (ddeg == 0) {
821             if (is_ex_exactly_of_type(r, numeric))
822                 return gamma;
823             else
824                 return gamma * r.primpart(*x);
825         }
826
827         // Next element of subresultant sequence
828         ri = c.expand().lcoeff(*x);
829         if (delta == 1)
830             psi = ri;
831         else if (delta)
832             divide(power(ri, delta), power(psi, delta-1), psi, false);
833         delta = cdeg - ddeg;
834     }
835 }
836
837
838 /** Return maximum (absolute value) coefficient of a polynomial.
839  *  This function is used internally by heur_gcd().
840  *
841  *  @param e  expanded multivariate polynomial
842  *  @return maximum coefficient
843  *  @see heur_gcd */
844
845 numeric ex::max_coefficient(void) const
846 {
847     GINAC_ASSERT(bp!=0);
848     return bp->max_coefficient();
849 }
850
851 numeric basic::max_coefficient(void) const
852 {
853     return _num1();
854 }
855
856 numeric numeric::max_coefficient(void) const
857 {
858     return abs(*this);
859 }
860
861 numeric add::max_coefficient(void) const
862 {
863     epvector::const_iterator it = seq.begin();
864     epvector::const_iterator itend = seq.end();
865     GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
866     numeric cur_max = abs(ex_to_numeric(overall_coeff));
867     while (it != itend) {
868         numeric a;
869         GINAC_ASSERT(!is_ex_exactly_of_type(it->rest,numeric));
870         a = abs(ex_to_numeric(it->coeff));
871         if (a > cur_max)
872             cur_max = a;
873         it++;
874     }
875     return cur_max;
876 }
877
878 numeric mul::max_coefficient(void) const
879 {
880 #ifdef DO_GINAC_ASSERT
881     epvector::const_iterator it = seq.begin();
882     epvector::const_iterator itend = seq.end();
883     while (it != itend) {
884         GINAC_ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*it),numeric));
885         it++;
886     }
887 #endif // def DO_GINAC_ASSERT
888     GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
889     return abs(ex_to_numeric(overall_coeff));
890 }
891
892
893 /** Apply symmetric modular homomorphism to a multivariate polynomial.
894  *  This function is used internally by heur_gcd().
895  *
896  *  @param e  expanded multivariate polynomial
897  *  @param xi  modulus
898  *  @return mapped polynomial
899  *  @see heur_gcd */
900
901 ex ex::smod(const numeric &xi) const
902 {
903     GINAC_ASSERT(bp!=0);
904     return bp->smod(xi);
905 }
906
907 ex basic::smod(const numeric &xi) const
908 {
909     return *this;
910 }
911
912 ex numeric::smod(const numeric &xi) const
913 {
914 #ifndef NO_GINAC_NAMESPACE
915     return GiNaC::smod(*this, xi);
916 #else // ndef NO_GINAC_NAMESPACE
917     return ::smod(*this, xi);
918 #endif // ndef NO_GINAC_NAMESPACE
919 }
920
921 ex add::smod(const numeric &xi) const
922 {
923     epvector newseq;
924     newseq.reserve(seq.size()+1);
925     epvector::const_iterator it = seq.begin();
926     epvector::const_iterator itend = seq.end();
927     while (it != itend) {
928         GINAC_ASSERT(!is_ex_exactly_of_type(it->rest,numeric));
929 #ifndef NO_GINAC_NAMESPACE
930         numeric coeff = GiNaC::smod(ex_to_numeric(it->coeff), xi);
931 #else // ndef NO_GINAC_NAMESPACE
932         numeric coeff = ::smod(ex_to_numeric(it->coeff), xi);
933 #endif // ndef NO_GINAC_NAMESPACE
934         if (!coeff.is_zero())
935             newseq.push_back(expair(it->rest, coeff));
936         it++;
937     }
938     GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
939 #ifndef NO_GINAC_NAMESPACE
940     numeric coeff = GiNaC::smod(ex_to_numeric(overall_coeff), xi);
941 #else // ndef NO_GINAC_NAMESPACE
942     numeric coeff = ::smod(ex_to_numeric(overall_coeff), xi);
943 #endif // ndef NO_GINAC_NAMESPACE
944     return (new add(newseq,coeff))->setflag(status_flags::dynallocated);
945 }
946
947 ex mul::smod(const numeric &xi) const
948 {
949 #ifdef DO_GINAC_ASSERT
950     epvector::const_iterator it = seq.begin();
951     epvector::const_iterator itend = seq.end();
952     while (it != itend) {
953         GINAC_ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*it),numeric));
954         it++;
955     }
956 #endif // def DO_GINAC_ASSERT
957     mul * mulcopyp=new mul(*this);
958     GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
959 #ifndef NO_GINAC_NAMESPACE
960     mulcopyp->overall_coeff = GiNaC::smod(ex_to_numeric(overall_coeff),xi);
961 #else // ndef NO_GINAC_NAMESPACE
962     mulcopyp->overall_coeff = ::smod(ex_to_numeric(overall_coeff),xi);
963 #endif // ndef NO_GINAC_NAMESPACE
964     mulcopyp->clearflag(status_flags::evaluated);
965     mulcopyp->clearflag(status_flags::hash_calculated);
966     return mulcopyp->setflag(status_flags::dynallocated);
967 }
968
969
970 /** Exception thrown by heur_gcd() to signal failure. */
971 class gcdheu_failed {};
972
973 /** Compute GCD of multivariate polynomials using the heuristic GCD algorithm.
974  *  get_symbol_stats() must have been called previously with the input
975  *  polynomials and an iterator to the first element of the sym_desc vector
976  *  passed in. This function is used internally by gcd().
977  *
978  *  @param a  first multivariate polynomial (expanded)
979  *  @param b  second multivariate polynomial (expanded)
980  *  @param ca  cofactor of polynomial a (returned), NULL to suppress
981  *             calculation of cofactor
982  *  @param cb  cofactor of polynomial b (returned), NULL to suppress
983  *             calculation of cofactor
984  *  @param var iterator to first element of vector of sym_desc structs
985  *  @return the GCD as a new expression
986  *  @see gcd
987  *  @exception gcdheu_failed() */
988
989 static ex heur_gcd(const ex &a, const ex &b, ex *ca, ex *cb, sym_desc_vec::const_iterator var)
990 {
991     if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric)) {
992         numeric g = gcd(ex_to_numeric(a), ex_to_numeric(b));
993         numeric rg;
994         if (ca || cb)
995             rg = g.inverse();
996         if (ca)
997             *ca = ex_to_numeric(a).mul(rg);
998         if (cb)
999             *cb = ex_to_numeric(b).mul(rg);
1000         return g;
1001     }
1002
1003     // The first symbol is our main variable
1004     const symbol *x = var->sym;
1005
1006     // Remove integer content
1007     numeric gc = gcd(a.integer_content(), b.integer_content());
1008     numeric rgc = gc.inverse();
1009     ex p = a * rgc;
1010     ex q = b * rgc;
1011     int maxdeg = max(p.degree(*x), q.degree(*x));
1012
1013     // Find evaluation point
1014     numeric mp = p.max_coefficient(), mq = q.max_coefficient();
1015     numeric xi;
1016     if (mp > mq)
1017         xi = mq * _num2() + _num2();
1018     else
1019         xi = mp * _num2() + _num2();
1020
1021     // 6 tries maximum
1022     for (int t=0; t<6; t++) {
1023         if (xi.int_length() * maxdeg > 50000)
1024             throw gcdheu_failed();
1025
1026         // Apply evaluation homomorphism and calculate GCD
1027         ex gamma = heur_gcd(p.subs(*x == xi), q.subs(*x == xi), NULL, NULL, var+1).expand();
1028         if (!is_ex_exactly_of_type(gamma, fail)) {
1029
1030             // Reconstruct polynomial from GCD of mapped polynomials
1031             ex g = _ex0();
1032             numeric rxi = xi.inverse();
1033             for (int i=0; !gamma.is_zero(); i++) {
1034                 ex gi = gamma.smod(xi);
1035                 g += gi * power(*x, i);
1036                 gamma = (gamma - gi) * rxi;
1037             }
1038             // Remove integer content
1039             g /= g.integer_content();
1040
1041             // If the calculated polynomial divides both a and b, this is the GCD
1042             ex dummy;
1043             if (divide_in_z(p, g, ca ? *ca : dummy, var) && divide_in_z(q, g, cb ? *cb : dummy, var)) {
1044                 g *= gc;
1045                 ex lc = g.lcoeff(*x);
1046                 if (is_ex_exactly_of_type(lc, numeric) && lc.compare(_ex0()) < 0)
1047                     return -g;
1048                 else
1049                     return g;
1050             }
1051         }
1052
1053         // Next evaluation point
1054         xi = iquo(xi * isqrt(isqrt(xi)) * numeric(73794), numeric(27011));
1055     }
1056     return *new ex(fail());
1057 }
1058
1059
1060 /** Compute GCD (Greatest Common Divisor) of multivariate polynomials a(X)
1061  *  and b(X) in Z[X].
1062  *
1063  *  @param a  first multivariate polynomial
1064  *  @param b  second multivariate polynomial
1065  *  @param check_args  check whether a and b are polynomials with rational
1066  *         coefficients (defaults to "true")
1067  *  @return the GCD as a new expression */
1068
1069 ex gcd(const ex &a, const ex &b, ex *ca, ex *cb, bool check_args)
1070 {
1071     // Some trivial cases
1072         ex aex = a.expand(), bex = b.expand();
1073     if (aex.is_zero()) {
1074         if (ca)
1075             *ca = _ex0();
1076         if (cb)
1077             *cb = _ex1();
1078         return b;
1079     }
1080     if (bex.is_zero()) {
1081         if (ca)
1082             *ca = _ex1();
1083         if (cb)
1084             *cb = _ex0();
1085         return a;
1086     }
1087     if (aex.is_equal(_ex1()) || bex.is_equal(_ex1())) {
1088         if (ca)
1089             *ca = a;
1090         if (cb)
1091             *cb = b;
1092         return _ex1();
1093     }
1094 #if FAST_COMPARE
1095     if (a.is_equal(b)) {
1096         if (ca)
1097             *ca = _ex1();
1098         if (cb)
1099             *cb = _ex1();
1100         return a;
1101     }
1102 #endif
1103     if (is_ex_exactly_of_type(aex, numeric) && is_ex_exactly_of_type(bex, numeric)) {
1104         numeric g = gcd(ex_to_numeric(aex), ex_to_numeric(bex));
1105         if (ca)
1106             *ca = ex_to_numeric(aex) / g;
1107         if (cb)
1108             *cb = ex_to_numeric(bex) / g;
1109         return g;
1110     }
1111     if (check_args && !a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)) {
1112         throw(std::invalid_argument("gcd: arguments must be polynomials over the rationals"));
1113     }
1114
1115     // Gather symbol statistics
1116     sym_desc_vec sym_stats;
1117     get_symbol_stats(a, b, sym_stats);
1118
1119     // The symbol with least degree is our main variable
1120     sym_desc_vec::const_iterator var = sym_stats.begin();
1121     const symbol *x = var->sym;
1122
1123     // Cancel trivial common factor
1124     int ldeg_a = var->ldeg_a;
1125     int ldeg_b = var->ldeg_b;
1126     int min_ldeg = min(ldeg_a, ldeg_b);
1127     if (min_ldeg > 0) {
1128         ex common = power(*x, min_ldeg);
1129 //clog << "trivial common factor " << common << endl;
1130         return gcd((aex / common).expand(), (bex / common).expand(), ca, cb, false) * common;
1131     }
1132
1133     // Try to eliminate variables
1134     if (var->deg_a == 0) {
1135 //clog << "eliminating variable " << *x << " from b" << endl;
1136         ex c = bex.content(*x);
1137         ex g = gcd(aex, c, ca, cb, false);
1138         if (cb)
1139             *cb *= bex.unit(*x) * bex.primpart(*x, c);
1140         return g;
1141     } else if (var->deg_b == 0) {
1142 //clog << "eliminating variable " << *x << " from a" << endl;
1143         ex c = aex.content(*x);
1144         ex g = gcd(c, bex, ca, cb, false);
1145         if (ca)
1146             *ca *= aex.unit(*x) * aex.primpart(*x, c);
1147         return g;
1148     }
1149
1150     // Try heuristic algorithm first, fall back to PRS if that failed
1151     ex g;
1152     try {
1153         g = heur_gcd(aex, bex, ca, cb, var);
1154     } catch (gcdheu_failed) {
1155         g = *new ex(fail());
1156     }
1157     if (is_ex_exactly_of_type(g, fail)) {
1158 // clog << "heuristics failed" << endl;
1159         g = sr_gcd(aex, bex, x);
1160         if (ca)
1161             divide(aex, g, *ca, false);
1162         if (cb)
1163             divide(bex, g, *cb, false);
1164     }
1165     return g;
1166 }
1167
1168
1169 /** Compute LCM (Least Common Multiple) of multivariate polynomials in Z[X].
1170  *
1171  *  @param a  first multivariate polynomial
1172  *  @param b  second multivariate polynomial
1173  *  @param check_args  check whether a and b are polynomials with rational
1174  *         coefficients (defaults to "true")
1175  *  @return the LCM as a new expression */
1176 ex lcm(const ex &a, const ex &b, bool check_args)
1177 {
1178     if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric))
1179         return gcd(ex_to_numeric(a), ex_to_numeric(b));
1180     if (check_args && !a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial))
1181         throw(std::invalid_argument("lcm: arguments must be polynomials over the rationals"));
1182     
1183     ex ca, cb;
1184     ex g = gcd(a, b, &ca, &cb, false);
1185     return ca * cb * g;
1186 }
1187
1188
1189 /*
1190  *  Square-free factorization
1191  */
1192
1193 // Univariate GCD of polynomials in Q[x] (used internally by sqrfree()).
1194 // a and b can be multivariate polynomials but they are treated as univariate polynomials in x.
1195 static ex univariate_gcd(const ex &a, const ex &b, const symbol &x)
1196 {
1197     if (a.is_zero())
1198         return b;
1199     if (b.is_zero())
1200         return a;
1201     if (a.is_equal(_ex1()) || b.is_equal(_ex1()))
1202         return _ex1();
1203     if (is_ex_of_type(a, numeric) && is_ex_of_type(b, numeric))
1204         return gcd(ex_to_numeric(a), ex_to_numeric(b));
1205     if (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial))
1206         throw(std::invalid_argument("univariate_gcd: arguments must be polynomials over the rationals"));
1207
1208     // Euclidean algorithm
1209     ex c, d, r;
1210     if (a.degree(x) >= b.degree(x)) {
1211         c = a;
1212         d = b;
1213     } else {
1214         c = b;
1215         d = a;
1216     }
1217     for (;;) {
1218         r = rem(c, d, x, false);
1219         if (r.is_zero())
1220             break;
1221         c = d;
1222         d = r;
1223     }
1224     return d / d.lcoeff(x);
1225 }
1226
1227
1228 /** Compute square-free factorization of multivariate polynomial a(x) using
1229  *  YunĀ“s algorithm.
1230  *
1231  * @param a  multivariate polynomial
1232  * @param x  variable to factor in
1233  * @return factored polynomial */
1234 ex sqrfree(const ex &a, const symbol &x)
1235 {
1236     int i = 1;
1237     ex res = _ex1();
1238     ex b = a.diff(x);
1239     ex c = univariate_gcd(a, b, x);
1240     ex w;
1241     if (c.is_equal(_ex1())) {
1242         w = a;
1243     } else {
1244         w = quo(a, c, x);
1245         ex y = quo(b, c, x);
1246         ex z = y - w.diff(x);
1247         while (!z.is_zero()) {
1248             ex g = univariate_gcd(w, z, x);
1249             res *= power(g, i);
1250             w = quo(w, g, x);
1251             y = quo(z, g, x);
1252             z = y - w.diff(x);
1253             i++;
1254         }
1255     }
1256     return res * power(w, i);
1257 }
1258
1259
1260 /*
1261  *  Normal form of rational functions
1262  */
1263
1264 // Create a symbol for replacing the expression "e" (or return a previously
1265 // assigned symbol). The symbol is appended to sym_list and returned, the
1266 // expression is appended to repl_list.
1267 static ex replace_with_symbol(const ex &e, lst &sym_lst, lst &repl_lst)
1268 {
1269     // Expression already in repl_lst? Then return the assigned symbol
1270     for (int i=0; i<repl_lst.nops(); i++)
1271         if (repl_lst.op(i).is_equal(e))
1272             return sym_lst.op(i);
1273
1274     // Otherwise create new symbol and add to list, taking care that the
1275         // replacement expression doesn't contain symbols from the sym_lst
1276         // because subs() is not recursive
1277         symbol s;
1278         ex es(s);
1279         ex e_replaced = e.subs(sym_lst, repl_lst);
1280     sym_lst.append(es);
1281     repl_lst.append(e_replaced);
1282     return es;
1283 }
1284
1285
1286 /** Default implementation of ex::normal(). It replaces the object with a
1287  *  temporary symbol.
1288  *  @see ex::normal */
1289 ex basic::normal(lst &sym_lst, lst &repl_lst, int level) const
1290 {
1291     return replace_with_symbol(*this, sym_lst, repl_lst);
1292 }
1293
1294
1295 /** Implementation of ex::normal() for symbols. This returns the unmodifies symbol.
1296  *  @see ex::normal */
1297 ex symbol::normal(lst &sym_lst, lst &repl_lst, int level) const
1298 {
1299     return *this;
1300 }
1301
1302
1303 /** Implementation of ex::normal() for a numeric. It splits complex numbers
1304  *  into re+I*im and replaces I and non-rational real numbers with a temporary
1305  *  symbol.
1306  *  @see ex::normal */
1307 ex numeric::normal(lst &sym_lst, lst &repl_lst, int level) const
1308 {
1309     if (is_real())
1310         if (is_rational())
1311             return *this;
1312         else
1313             return replace_with_symbol(*this, sym_lst, repl_lst);
1314     else { // complex
1315         numeric re = real(), im = imag();
1316         ex re_ex = re.is_rational() ? re : replace_with_symbol(re, sym_lst, repl_lst);
1317         ex im_ex = im.is_rational() ? im : replace_with_symbol(im, sym_lst, repl_lst);
1318         return re_ex + im_ex * replace_with_symbol(I, sym_lst, repl_lst);
1319     }
1320 }
1321
1322
1323 /*
1324  *  Helper function for fraction cancellation (returns cancelled fraction n/d)
1325  */
1326 static ex frac_cancel(const ex &n, const ex &d)
1327 {
1328     ex num = n;
1329     ex den = d;
1330     ex pre_factor = _ex1();
1331
1332     // Handle special cases where numerator or denominator is 0
1333     if (num.is_zero())
1334         return _ex0();
1335     if (den.expand().is_zero())
1336         throw(std::overflow_error("frac_cancel: division by zero in frac_cancel"));
1337
1338     // More special cases
1339     if (is_ex_exactly_of_type(den, numeric))
1340         return num / den;
1341     if (num.is_zero())
1342         return _ex0();
1343
1344     // Bring numerator and denominator to Z[X] by multiplying with
1345     // LCM of all coefficients' denominators
1346     ex num_lcm = lcm_of_coefficients_denominators(num);
1347     ex den_lcm = lcm_of_coefficients_denominators(den);
1348     num *= num_lcm;
1349     den *= den_lcm;
1350     pre_factor = den_lcm / num_lcm;
1351
1352     // Cancel GCD from numerator and denominator
1353     ex cnum, cden;
1354     if (gcd(num, den, &cnum, &cden, false) != _ex1()) {
1355                 num = cnum;
1356                 den = cden;
1357         }
1358
1359         // Make denominator unit normal (i.e. coefficient of first symbol
1360         // as defined by get_first_symbol() is made positive)
1361         const symbol *x;
1362         if (get_first_symbol(den, x)) {
1363                 if (den.unit(*x).compare(_ex0()) < 0) {
1364                         num *= _ex_1();
1365                         den *= _ex_1();
1366                 }
1367         }
1368     return pre_factor * num / den;
1369 }
1370
1371
1372 /** Implementation of ex::normal() for a sum. It expands terms and performs
1373  *  fractional addition.
1374  *  @see ex::normal */
1375 ex add::normal(lst &sym_lst, lst &repl_lst, int level) const
1376 {
1377     // Normalize and expand children
1378     exvector o;
1379     o.reserve(seq.size()+1);
1380     epvector::const_iterator it = seq.begin(), itend = seq.end();
1381     while (it != itend) {
1382         ex n = recombine_pair_to_ex(*it).bp->normal(sym_lst, repl_lst, level-1).expand();
1383         if (is_ex_exactly_of_type(n, add)) {
1384             epvector::const_iterator bit = (static_cast<add *>(n.bp))->seq.begin(), bitend = (static_cast<add *>(n.bp))->seq.end();
1385             while (bit != bitend) {
1386                 o.push_back(recombine_pair_to_ex(*bit));
1387                 bit++;
1388             }
1389             o.push_back((static_cast<add *>(n.bp))->overall_coeff);
1390         } else
1391             o.push_back(n);
1392         it++;
1393     }
1394     o.push_back(overall_coeff.bp->normal(sym_lst, repl_lst, level-1));
1395
1396     // Determine common denominator
1397     ex den = _ex1();
1398     exvector::const_iterator ait = o.begin(), aitend = o.end();
1399     while (ait != aitend) {
1400         den = lcm((*ait).denom(false), den, false);
1401         ait++;
1402     }
1403
1404     // Add fractions
1405     if (den.is_equal(_ex1()))
1406         return (new add(o))->setflag(status_flags::dynallocated);
1407     else {
1408         exvector num_seq;
1409         for (ait=o.begin(); ait!=aitend; ait++) {
1410             ex q;
1411             if (!divide(den, (*ait).denom(false), q, false)) {
1412                 // should not happen
1413                 throw(std::runtime_error("invalid expression in add::normal, division failed"));
1414             }
1415             num_seq.push_back((*ait).numer(false) * q);
1416         }
1417         ex num = add(num_seq);
1418
1419         // Cancel common factors from num/den
1420         return frac_cancel(num, den);
1421     }
1422 }
1423
1424
1425 /** Implementation of ex::normal() for a product. It cancels common factors
1426  *  from fractions.
1427  *  @see ex::normal() */
1428 ex mul::normal(lst &sym_lst, lst &repl_lst, int level) const
1429 {
1430     // Normalize children
1431     exvector o;
1432     o.reserve(seq.size()+1);
1433     epvector::const_iterator it = seq.begin(), itend = seq.end();
1434     while (it != itend) {
1435         o.push_back(recombine_pair_to_ex(*it).bp->normal(sym_lst, repl_lst, level-1));
1436         it++;
1437     }
1438     o.push_back(overall_coeff.bp->normal(sym_lst, repl_lst, level-1));
1439     ex n = (new mul(o))->setflag(status_flags::dynallocated);
1440     return frac_cancel(n.numer(false), n.denom(false));
1441 }
1442
1443
1444 /** Implementation of ex::normal() for powers. It normalizes the basis,
1445  *  distributes integer exponents to numerator and denominator, and replaces
1446  *  non-integer powers by temporary symbols.
1447  *  @see ex::normal */
1448 ex power::normal(lst &sym_lst, lst &repl_lst, int level) const
1449 {
1450     if (exponent.info(info_flags::integer)) {
1451         // Integer powers are distributed
1452         ex n = basis.bp->normal(sym_lst, repl_lst, level-1);
1453         ex num = n.numer(false);
1454         ex den = n.denom(false);
1455         return power(num, exponent) / power(den, exponent);
1456     } else {
1457         // Non-integer powers are replaced by temporary symbol (after normalizing basis)
1458         ex n = power(basis.bp->normal(sym_lst, repl_lst, level-1), exponent);
1459         return replace_with_symbol(n, sym_lst, repl_lst);
1460     }
1461 }
1462
1463
1464 /** Implementation of ex::normal() for series. It normalizes each coefficient and
1465  *  replaces the series by a temporary symbol.
1466  *  @see ex::normal */
1467 ex series::normal(lst &sym_lst, lst &repl_lst, int level) const
1468 {
1469     epvector new_seq;
1470     new_seq.reserve(seq.size());
1471
1472     epvector::const_iterator it = seq.begin(), itend = seq.end();
1473     while (it != itend) {
1474         new_seq.push_back(expair(it->rest.normal(), it->coeff));
1475         it++;
1476     }
1477
1478     ex n = series(var, point, new_seq);
1479     return replace_with_symbol(n, sym_lst, repl_lst);
1480 }
1481
1482
1483 /** Normalization of rational functions.
1484  *  This function converts an expression to its normal form
1485  *  "numerator/denominator", where numerator and denominator are (relatively
1486  *  prime) polynomials. Any subexpressions which are not rational functions
1487  *  (like non-rational numbers, non-integer powers or functions like Sin(),
1488  *  Cos() etc.) are replaced by temporary symbols which are re-substituted by
1489  *  the (normalized) subexpressions before normal() returns (this way, any
1490  *  expression can be treated as a rational function). normal() is applied
1491  *  recursively to arguments of functions etc.
1492  *
1493  *  @param level maximum depth of recursion
1494  *  @return normalized expression */
1495 ex ex::normal(int level) const
1496 {
1497     lst sym_lst, repl_lst;
1498     ex e = bp->normal(sym_lst, repl_lst, level);
1499     if (sym_lst.nops() > 0)
1500         return e.subs(sym_lst, repl_lst);
1501     else
1502         return e;
1503 }
1504
1505 #ifndef NO_GINAC_NAMESPACE
1506 } // namespace GiNaC
1507 #endif // ndef NO_GINAC_NAMESPACE