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