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