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