]> www.ginac.de Git - ginac.git/blob - ginac/normal.cpp
- is_zero() is now called on expanded expressions in gcd()
[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         ex aex = a.expand(), bex = b.expand();
1054     if (aex.is_zero()) {
1055         if (ca)
1056             *ca = exZERO();
1057         if (cb)
1058             *cb = exONE();
1059         return b;
1060     }
1061     if (bex.is_zero()) {
1062         if (ca)
1063             *ca = exONE();
1064         if (cb)
1065             *cb = exZERO();
1066         return a;
1067     }
1068     if (aex.is_equal(exONE()) || bex.is_equal(exONE())) {
1069         if (ca)
1070             *ca = a;
1071         if (cb)
1072             *cb = b;
1073         return exONE();
1074     }
1075 #if FAST_COMPARE
1076     if (a.is_equal(b)) {
1077         if (ca)
1078             *ca = exONE();
1079         if (cb)
1080             *cb = exONE();
1081         return a;
1082     }
1083 #endif
1084     if (is_ex_exactly_of_type(aex, numeric) && is_ex_exactly_of_type(bex, numeric)) {
1085         numeric g = gcd(ex_to_numeric(aex), ex_to_numeric(bex));
1086         if (ca)
1087             *ca = ex_to_numeric(aex) / g;
1088         if (cb)
1089             *cb = ex_to_numeric(bex) / g;
1090         return g;
1091     }
1092     if (check_args && !a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)) {
1093         throw(std::invalid_argument("gcd: arguments must be polynomials over the rationals"));
1094     }
1095
1096     // Gather symbol statistics
1097     sym_desc_vec sym_stats;
1098     get_symbol_stats(a, b, sym_stats);
1099
1100     // The symbol with least degree is our main variable
1101     sym_desc_vec::const_iterator var = sym_stats.begin();
1102     const symbol *x = var->sym;
1103
1104     // Cancel trivial common factor
1105     int ldeg_a = var->ldeg_a;
1106     int ldeg_b = var->ldeg_b;
1107     int min_ldeg = min(ldeg_a, ldeg_b);
1108     if (min_ldeg > 0) {
1109         ex common = power(*x, min_ldeg);
1110 //clog << "trivial common factor " << common << endl;
1111         return gcd((aex / common).expand(), (bex / common).expand(), ca, cb, false) * common;
1112     }
1113
1114     // Try to eliminate variables
1115     if (var->deg_a == 0) {
1116 //clog << "eliminating variable " << *x << " from b" << endl;
1117         ex c = bex.content(*x);
1118         ex g = gcd(aex, c, ca, cb, false);
1119         if (cb)
1120             *cb *= bex.unit(*x) * bex.primpart(*x, c);
1121         return g;
1122     } else if (var->deg_b == 0) {
1123 //clog << "eliminating variable " << *x << " from a" << endl;
1124         ex c = aex.content(*x);
1125         ex g = gcd(c, bex, ca, cb, false);
1126         if (ca)
1127             *ca *= aex.unit(*x) * aex.primpart(*x, c);
1128         return g;
1129     }
1130
1131     // Try heuristic algorithm first, fall back to PRS if that failed
1132     ex g;
1133     try {
1134         g = heur_gcd(aex, bex, ca, cb, var);
1135     } catch (gcdheu_failed) {
1136         g = *new ex(fail());
1137     }
1138     if (is_ex_exactly_of_type(g, fail)) {
1139 //clog << "heuristics failed\n";
1140         g = sr_gcd(aex, bex, x);
1141         if (ca)
1142             divide(aex, g, *ca, false);
1143         if (cb)
1144             divide(bex, g, *cb, false);
1145     }
1146     return g;
1147 }
1148
1149
1150 /** Compute LCM (Least Common Multiple) of multivariate polynomials in Z[X].
1151  *
1152  *  @param a  first multivariate polynomial
1153  *  @param b  second multivariate polynomial
1154  *  @param check_args  check whether a and b are polynomials with rational
1155  *         coefficients (defaults to "true")
1156  *  @return the LCM as a new expression */
1157 ex lcm(const ex &a, const ex &b, bool check_args)
1158 {
1159     if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric))
1160         return gcd(ex_to_numeric(a), ex_to_numeric(b));
1161     if (check_args && !a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial))
1162         throw(std::invalid_argument("lcm: arguments must be polynomials over the rationals"));
1163     
1164     ex ca, cb;
1165     ex g = gcd(a, b, &ca, &cb, false);
1166     return ca * cb * g;
1167 }
1168
1169
1170 /*
1171  *  Square-free factorization
1172  */
1173
1174 // Univariate GCD of polynomials in Q[x] (used internally by sqrfree()).
1175 // a and b can be multivariate polynomials but they are treated as univariate polynomials in x.
1176 static ex univariate_gcd(const ex &a, const ex &b, const symbol &x)
1177 {
1178     if (a.is_zero())
1179         return b;
1180     if (b.is_zero())
1181         return a;
1182     if (a.is_equal(exONE()) || b.is_equal(exONE()))
1183         return exONE();
1184     if (is_ex_of_type(a, numeric) && is_ex_of_type(b, numeric))
1185         return gcd(ex_to_numeric(a), ex_to_numeric(b));
1186     if (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial))
1187         throw(std::invalid_argument("univariate_gcd: arguments must be polynomials over the rationals"));
1188
1189     // Euclidean algorithm
1190     ex c, d, r;
1191     if (a.degree(x) >= b.degree(x)) {
1192         c = a;
1193         d = b;
1194     } else {
1195         c = b;
1196         d = a;
1197     }
1198     for (;;) {
1199         r = rem(c, d, x, false);
1200         if (r.is_zero())
1201             break;
1202         c = d;
1203         d = r;
1204     }
1205     return d / d.lcoeff(x);
1206 }
1207
1208
1209 /** Compute square-free factorization of multivariate polynomial a(x) using
1210  *  YunĀ“s algorithm.
1211  *
1212  * @param a  multivariate polynomial
1213  * @param x  variable to factor in
1214  * @return factored polynomial */
1215 ex sqrfree(const ex &a, const symbol &x)
1216 {
1217     int i = 1;
1218     ex res = exONE();
1219     ex b = a.diff(x);
1220     ex c = univariate_gcd(a, b, x);
1221     ex w;
1222     if (c.is_equal(exONE())) {
1223         w = a;
1224     } else {
1225         w = quo(a, c, x);
1226         ex y = quo(b, c, x);
1227         ex z = y - w.diff(x);
1228         while (!z.is_zero()) {
1229             ex g = univariate_gcd(w, z, x);
1230             res *= power(g, i);
1231             w = quo(w, g, x);
1232             y = quo(z, g, x);
1233             z = y - w.diff(x);
1234             i++;
1235         }
1236     }
1237     return res * power(w, i);
1238 }
1239
1240
1241 /*
1242  *  Normal form of rational functions
1243  */
1244
1245 // Create a symbol for replacing the expression "e" (or return a previously
1246 // assigned symbol). The symbol is appended to sym_list and returned, the
1247 // expression is appended to repl_list.
1248 static ex replace_with_symbol(const ex &e, lst &sym_lst, lst &repl_lst)
1249 {
1250     // Expression already in repl_lst? Then return the assigned symbol
1251     for (int i=0; i<repl_lst.nops(); i++)
1252         if (repl_lst.op(i).is_equal(e))
1253             return sym_lst.op(i);
1254
1255     // Otherwise create new symbol and add to list, taking care that the
1256         // replacement expression doesn't contain symbols from the sym_lst
1257         // because subs() is not recursive
1258         symbol s;
1259         ex es(s);
1260         ex e_replaced = e.subs(sym_lst, repl_lst);
1261     sym_lst.append(es);
1262     repl_lst.append(e_replaced);
1263     return es;
1264 }
1265
1266
1267 /** Default implementation of ex::normal(). It replaces the object with a
1268  *  temporary symbol.
1269  *  @see ex::normal */
1270 ex basic::normal(lst &sym_lst, lst &repl_lst, int level) const
1271 {
1272     return replace_with_symbol(*this, sym_lst, repl_lst);
1273 }
1274
1275
1276 /** Implementation of ex::normal() for symbols. This returns the unmodifies symbol.
1277  *  @see ex::normal */
1278 ex symbol::normal(lst &sym_lst, lst &repl_lst, int level) const
1279 {
1280     return *this;
1281 }
1282
1283
1284 /** Implementation of ex::normal() for a numeric. It splits complex numbers
1285  *  into re+I*im and replaces I and non-rational real numbers with a temporary
1286  *  symbol.
1287  *  @see ex::normal */
1288 ex numeric::normal(lst &sym_lst, lst &repl_lst, int level) const
1289 {
1290     if (is_real())
1291         if (is_rational())
1292             return *this;
1293                 else
1294                     return replace_with_symbol(*this, sym_lst, repl_lst);
1295     else { // complex
1296         numeric re = real(), im = imag();
1297                 ex re_ex = re.is_rational() ? re : replace_with_symbol(re, sym_lst, repl_lst);
1298                 ex im_ex = im.is_rational() ? im : replace_with_symbol(im, sym_lst, repl_lst);
1299                 return re_ex + im_ex * replace_with_symbol(I, sym_lst, repl_lst);
1300         }
1301 }
1302
1303
1304 /*
1305  *  Helper function for fraction cancellation (returns cancelled fraction n/d)
1306  */
1307
1308 static ex frac_cancel(const ex &n, const ex &d)
1309 {
1310     ex num = n;
1311     ex den = d;
1312     ex pre_factor = exONE();
1313
1314     // Handle special cases where numerator or denominator is 0
1315     if (num.is_zero())
1316         return exZERO();
1317     if (den.expand().is_zero())
1318         throw(std::overflow_error("frac_cancel: division by zero in frac_cancel"));
1319
1320     // More special cases
1321     if (is_ex_exactly_of_type(den, numeric))
1322         return num / den;
1323     if (num.is_zero())
1324         return exZERO();
1325
1326     // Bring numerator and denominator to Z[X] by multiplying with
1327     // LCM of all coefficients' denominators
1328     ex num_lcm = lcm_of_coefficients_denominators(num);
1329     ex den_lcm = lcm_of_coefficients_denominators(den);
1330     num *= num_lcm;
1331     den *= den_lcm;
1332     pre_factor = den_lcm / num_lcm;
1333
1334     // Cancel GCD from numerator and denominator
1335     ex cnum, cden;
1336     if (gcd(num, den, &cnum, &cden, false) != exONE()) {
1337                 num = cnum;
1338                 den = cden;
1339         }
1340
1341         // Make denominator unit normal (i.e. coefficient of first symbol
1342         // as defined by get_first_symbol() is made positive)
1343         const symbol *x;
1344         if (get_first_symbol(den, x)) {
1345                 if (den.unit(*x).compare(exZERO()) < 0) {
1346                         num *= exMINUSONE();
1347                         den *= exMINUSONE();
1348                 }
1349         }
1350     return pre_factor * num / den;
1351 }
1352
1353
1354 /** Implementation of ex::normal() for a sum. It expands terms and performs
1355  *  fractional addition.
1356  *  @see ex::normal */
1357 ex add::normal(lst &sym_lst, lst &repl_lst, int level) const
1358 {
1359     // Normalize and expand children
1360     exvector o;
1361     o.reserve(seq.size()+1);
1362     epvector::const_iterator it = seq.begin(), itend = seq.end();
1363     while (it != itend) {
1364         ex n = recombine_pair_to_ex(*it).bp->normal(sym_lst, repl_lst, level-1).expand();
1365         if (is_ex_exactly_of_type(n, add)) {
1366             epvector::const_iterator bit = (static_cast<add *>(n.bp))->seq.begin(), bitend = (static_cast<add *>(n.bp))->seq.end();
1367             while (bit != bitend) {
1368                 o.push_back(recombine_pair_to_ex(*bit));
1369                 bit++;
1370             }
1371             o.push_back((static_cast<add *>(n.bp))->overall_coeff);
1372         } else
1373             o.push_back(n);
1374         it++;
1375     }
1376     o.push_back(overall_coeff.bp->normal(sym_lst, repl_lst, level-1));
1377
1378     // Determine common denominator
1379     ex den = exONE();
1380     exvector::const_iterator ait = o.begin(), aitend = o.end();
1381     while (ait != aitend) {
1382         den = lcm((*ait).denom(false), den, false);
1383         ait++;
1384     }
1385
1386     // Add fractions
1387     if (den.is_equal(exONE()))
1388         return (new add(o))->setflag(status_flags::dynallocated);
1389     else {
1390         exvector num_seq;
1391         for (ait=o.begin(); ait!=aitend; ait++) {
1392             ex q;
1393             if (!divide(den, (*ait).denom(false), q, false)) {
1394                 // should not happen
1395                 throw(std::runtime_error("invalid expression in add::normal, division failed"));
1396             }
1397             num_seq.push_back((*ait).numer(false) * q);
1398         }
1399         ex num = add(num_seq);
1400
1401         // Cancel common factors from num/den
1402         return frac_cancel(num, den);
1403     }
1404 }
1405
1406
1407 /** Implementation of ex::normal() for a product. It cancels common factors
1408  *  from fractions.
1409  *  @see ex::normal() */
1410 ex mul::normal(lst &sym_lst, lst &repl_lst, int level) const
1411 {
1412     // Normalize children
1413     exvector o;
1414     o.reserve(seq.size()+1);
1415     epvector::const_iterator it = seq.begin(), itend = seq.end();
1416     while (it != itend) {
1417         o.push_back(recombine_pair_to_ex(*it).bp->normal(sym_lst, repl_lst, level-1));
1418         it++;
1419     }
1420     o.push_back(overall_coeff.bp->normal(sym_lst, repl_lst, level-1));
1421     ex n = (new mul(o))->setflag(status_flags::dynallocated);
1422     return frac_cancel(n.numer(false), n.denom(false));
1423 }
1424
1425
1426 /** Implementation of ex::normal() for powers. It normalizes the basis,
1427  *  distributes integer exponents to numerator and denominator, and replaces
1428  *  non-integer powers by temporary symbols.
1429  *  @see ex::normal */
1430 ex power::normal(lst &sym_lst, lst &repl_lst, int level) const
1431 {
1432     if (exponent.info(info_flags::integer)) {
1433         // Integer powers are distributed
1434         ex n = basis.bp->normal(sym_lst, repl_lst, level-1);
1435         ex num = n.numer(false);
1436         ex den = n.denom(false);
1437         return power(num, exponent) / power(den, exponent);
1438     } else {
1439         // Non-integer powers are replaced by temporary symbol (after normalizing basis)
1440         ex n = power(basis.bp->normal(sym_lst, repl_lst, level-1), exponent);
1441         return replace_with_symbol(n, sym_lst, repl_lst);
1442     }
1443 }
1444
1445
1446 /** Implementation of ex::normal() for series. It normalizes each coefficient and
1447  *  replaces the series by a temporary symbol.
1448  *  @see ex::normal */
1449 ex series::normal(lst &sym_lst, lst &repl_lst, int level) const
1450 {
1451     epvector new_seq;
1452     new_seq.reserve(seq.size());
1453
1454     epvector::const_iterator it = seq.begin(), itend = seq.end();
1455     while (it != itend) {
1456         new_seq.push_back(expair(it->rest.normal(), it->coeff));
1457         it++;
1458     }
1459
1460     ex n = series(var, point, new_seq);
1461     return replace_with_symbol(n, sym_lst, repl_lst);
1462 }
1463
1464
1465 /** Normalization of rational functions.
1466  *  This function converts an expression to its normal form
1467  *  "numerator/denominator", where numerator and denominator are (relatively
1468  *  prime) polynomials. Any subexpressions which are not rational functions
1469  *  (like non-rational numbers, non-integer powers or functions like Sin(),
1470  *  Cos() etc.) are replaced by temporary symbols which are re-substituted by
1471  *  the (normalized) subexpressions before normal() returns (this way, any
1472  *  expression can be treated as a rational function). normal() is applied
1473  *  recursively to arguments of functions etc.
1474  *
1475  *  @param level maximum depth of recursion
1476  *  @return normalized expression */
1477 ex ex::normal(int level) const
1478 {
1479     lst sym_lst, repl_lst;
1480     ex e = bp->normal(sym_lst, repl_lst, level);
1481     if (sym_lst.nops() > 0)
1482         return e.subs(sym_lst, repl_lst);
1483     else
1484         return e;
1485 }
1486
1487 } // namespace GiNaC