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