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