]> www.ginac.de Git - ginac.git/blob - ginac/normal.cpp
container.pl: can now generate constructors for an arbitary number
[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         // Partially factored cases (to avoid expanding large expressions)
1105         if (is_ex_exactly_of_type(a, mul)) {
1106                 if (is_ex_exactly_of_type(b, mul) && b.nops() > a.nops())
1107                         goto factored_b;
1108 factored_a:
1109                 ex g = _ex1();
1110                 ex acc_ca = _ex1();
1111                 ex part_b = b;
1112                 for (unsigned i=0; i<a.nops(); i++) {
1113                         ex part_ca, part_cb;
1114                         g *= gcd(a.op(i), part_b, &part_ca, &part_cb, check_args);
1115                         acc_ca *= part_ca;
1116                         part_b = part_cb;
1117                 }
1118                 if (ca)
1119                         *ca = acc_ca;
1120                 if (cb)
1121                         *cb = part_b;
1122                 return g;
1123         } else if (is_ex_exactly_of_type(b, mul)) {
1124                 if (is_ex_exactly_of_type(a, mul) && a.nops() > b.nops())
1125                         goto factored_a;
1126 factored_b:
1127                 ex g = _ex1();
1128                 ex acc_cb = _ex1();
1129                 ex part_a = a;
1130                 for (unsigned i=0; i<b.nops(); i++) {
1131                         ex part_ca, part_cb;
1132                         g *= gcd(part_a, b.op(i), &part_ca, &part_cb, check_args);
1133                         acc_cb *= part_cb;
1134                         part_a = part_ca;
1135                 }
1136                 if (ca)
1137                         *ca = part_a;
1138                 if (cb)
1139                         *cb = acc_cb;
1140                 return g;
1141         }
1142
1143     // Some trivial cases
1144         ex aex = a.expand(), bex = b.expand();
1145     if (aex.is_zero()) {
1146         if (ca)
1147             *ca = _ex0();
1148         if (cb)
1149             *cb = _ex1();
1150         return b;
1151     }
1152     if (bex.is_zero()) {
1153         if (ca)
1154             *ca = _ex1();
1155         if (cb)
1156             *cb = _ex0();
1157         return a;
1158     }
1159     if (aex.is_equal(_ex1()) || bex.is_equal(_ex1())) {
1160         if (ca)
1161             *ca = a;
1162         if (cb)
1163             *cb = b;
1164         return _ex1();
1165     }
1166 #if FAST_COMPARE
1167     if (a.is_equal(b)) {
1168         if (ca)
1169             *ca = _ex1();
1170         if (cb)
1171             *cb = _ex1();
1172         return a;
1173     }
1174 #endif
1175     if (is_ex_exactly_of_type(aex, numeric) && is_ex_exactly_of_type(bex, numeric)) {
1176         numeric g = gcd(ex_to_numeric(aex), ex_to_numeric(bex));
1177         if (ca)
1178             *ca = ex_to_numeric(aex) / g;
1179         if (cb)
1180             *cb = ex_to_numeric(bex) / g;
1181         return g;
1182     }
1183     if (check_args && !a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)) {
1184         throw(std::invalid_argument("gcd: arguments must be polynomials over the rationals"));
1185     }
1186
1187     // Gather symbol statistics
1188     sym_desc_vec sym_stats;
1189     get_symbol_stats(a, b, sym_stats);
1190
1191     // The symbol with least degree is our main variable
1192     sym_desc_vec::const_iterator var = sym_stats.begin();
1193     const symbol *x = var->sym;
1194
1195     // Cancel trivial common factor
1196     int ldeg_a = var->ldeg_a;
1197     int ldeg_b = var->ldeg_b;
1198     int min_ldeg = min(ldeg_a, ldeg_b);
1199     if (min_ldeg > 0) {
1200         ex common = power(*x, min_ldeg);
1201 //clog << "trivial common factor " << common << endl;
1202         return gcd((aex / common).expand(), (bex / common).expand(), ca, cb, false) * common;
1203     }
1204
1205     // Try to eliminate variables
1206     if (var->deg_a == 0) {
1207 //clog << "eliminating variable " << *x << " from b" << endl;
1208         ex c = bex.content(*x);
1209         ex g = gcd(aex, c, ca, cb, false);
1210         if (cb)
1211             *cb *= bex.unit(*x) * bex.primpart(*x, c);
1212         return g;
1213     } else if (var->deg_b == 0) {
1214 //clog << "eliminating variable " << *x << " from a" << endl;
1215         ex c = aex.content(*x);
1216         ex g = gcd(c, bex, ca, cb, false);
1217         if (ca)
1218             *ca *= aex.unit(*x) * aex.primpart(*x, c);
1219         return g;
1220     }
1221
1222     // Try heuristic algorithm first, fall back to PRS if that failed
1223     ex g;
1224     try {
1225         g = heur_gcd(aex, bex, ca, cb, var);
1226     } catch (gcdheu_failed) {
1227         g = *new ex(fail());
1228     }
1229     if (is_ex_exactly_of_type(g, fail)) {
1230 //clog << "heuristics failed" << endl;
1231         g = sr_gcd(aex, bex, x);
1232         if (ca)
1233             divide(aex, g, *ca, false);
1234         if (cb)
1235             divide(bex, g, *cb, false);
1236     }
1237     return g;
1238 }
1239
1240
1241 /** Compute LCM (Least Common Multiple) of multivariate polynomials in Z[X].
1242  *
1243  *  @param a  first multivariate polynomial
1244  *  @param b  second multivariate polynomial
1245  *  @param check_args  check whether a and b are polynomials with rational
1246  *         coefficients (defaults to "true")
1247  *  @return the LCM as a new expression */
1248 ex lcm(const ex &a, const ex &b, bool check_args)
1249 {
1250     if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric))
1251         return lcm(ex_to_numeric(a), ex_to_numeric(b));
1252     if (check_args && !a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial))
1253         throw(std::invalid_argument("lcm: arguments must be polynomials over the rationals"));
1254     
1255     ex ca, cb;
1256     ex g = gcd(a, b, &ca, &cb, false);
1257     return ca * cb * g;
1258 }
1259
1260
1261 /*
1262  *  Square-free factorization
1263  */
1264
1265 // Univariate GCD of polynomials in Q[x] (used internally by sqrfree()).
1266 // a and b can be multivariate polynomials but they are treated as univariate polynomials in x.
1267 static ex univariate_gcd(const ex &a, const ex &b, const symbol &x)
1268 {
1269     if (a.is_zero())
1270         return b;
1271     if (b.is_zero())
1272         return a;
1273     if (a.is_equal(_ex1()) || b.is_equal(_ex1()))
1274         return _ex1();
1275     if (is_ex_of_type(a, numeric) && is_ex_of_type(b, numeric))
1276         return gcd(ex_to_numeric(a), ex_to_numeric(b));
1277     if (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial))
1278         throw(std::invalid_argument("univariate_gcd: arguments must be polynomials over the rationals"));
1279
1280     // Euclidean algorithm
1281     ex c, d, r;
1282     if (a.degree(x) >= b.degree(x)) {
1283         c = a;
1284         d = b;
1285     } else {
1286         c = b;
1287         d = a;
1288     }
1289     for (;;) {
1290         r = rem(c, d, x, false);
1291         if (r.is_zero())
1292             break;
1293         c = d;
1294         d = r;
1295     }
1296     return d / d.lcoeff(x);
1297 }
1298
1299
1300 /** Compute square-free factorization of multivariate polynomial a(x) using
1301  *  YunĀ“s algorithm.
1302  *
1303  * @param a  multivariate polynomial
1304  * @param x  variable to factor in
1305  * @return factored polynomial */
1306 ex sqrfree(const ex &a, const symbol &x)
1307 {
1308     int i = 1;
1309     ex res = _ex1();
1310     ex b = a.diff(x);
1311     ex c = univariate_gcd(a, b, x);
1312     ex w;
1313     if (c.is_equal(_ex1())) {
1314         w = a;
1315     } else {
1316         w = quo(a, c, x);
1317         ex y = quo(b, c, x);
1318         ex z = y - w.diff(x);
1319         while (!z.is_zero()) {
1320             ex g = univariate_gcd(w, z, x);
1321             res *= power(g, i);
1322             w = quo(w, g, x);
1323             y = quo(z, g, x);
1324             z = y - w.diff(x);
1325             i++;
1326         }
1327     }
1328     return res * power(w, i);
1329 }
1330
1331
1332 /*
1333  *  Normal form of rational functions
1334  */
1335
1336 /*
1337  *  Note: The internal normal() functions (= basic::normal() and overloaded
1338  *  functions) all return lists of the form {numerator, denominator}. This
1339  *  is to get around mul::eval()'s automatic expansion of numeric coefficients.
1340  *  E.g. (a+b)/3 is automatically converted to a/3+b/3 but we want to keep
1341  *  the information that (a+b) is the numerator and 3 is the denominator.
1342  */
1343
1344 /** Create a symbol for replacing the expression "e" (or return a previously
1345  *  assigned symbol). The symbol is appended to sym_list and returned, the
1346  *  expression is appended to repl_list.
1347  *  @see ex::normal */
1348 static ex replace_with_symbol(const ex &e, lst &sym_lst, lst &repl_lst)
1349 {
1350     // Expression already in repl_lst? Then return the assigned symbol
1351     for (unsigned i=0; i<repl_lst.nops(); i++)
1352         if (repl_lst.op(i).is_equal(e))
1353             return sym_lst.op(i);
1354
1355     // Otherwise create new symbol and add to list, taking care that the
1356         // replacement expression doesn't contain symbols from the sym_lst
1357         // because subs() is not recursive
1358         symbol s;
1359         ex es(s);
1360         ex e_replaced = e.subs(sym_lst, repl_lst);
1361     sym_lst.append(es);
1362     repl_lst.append(e_replaced);
1363     return es;
1364 }
1365
1366
1367 /** Default implementation of ex::normal(). It replaces the object with a
1368  *  temporary symbol.
1369  *  @see ex::normal */
1370 ex basic::normal(lst &sym_lst, lst &repl_lst, int level) const
1371 {
1372     return (new lst(replace_with_symbol(*this, sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
1373 }
1374
1375
1376 /** Implementation of ex::normal() for symbols. This returns the unmodified symbol.
1377  *  @see ex::normal */
1378 ex symbol::normal(lst &sym_lst, lst &repl_lst, int level) const
1379 {
1380     return (new lst(*this, _ex1()))->setflag(status_flags::dynallocated);
1381 }
1382
1383
1384 /** Implementation of ex::normal() for a numeric. It splits complex numbers
1385  *  into re+I*im and replaces I and non-rational real numbers with a temporary
1386  *  symbol.
1387  *  @see ex::normal */
1388 ex numeric::normal(lst &sym_lst, lst &repl_lst, int level) const
1389 {
1390         numeric num = numer();
1391         ex numex = num;
1392
1393     if (num.is_real()) {
1394         if (!num.is_integer())
1395             numex = replace_with_symbol(numex, sym_lst, repl_lst);
1396     } else { // complex
1397         numeric re = num.real(), im = num.imag();
1398         ex re_ex = re.is_rational() ? re : replace_with_symbol(re, sym_lst, repl_lst);
1399         ex im_ex = im.is_rational() ? im : replace_with_symbol(im, sym_lst, repl_lst);
1400         numex = re_ex + im_ex * replace_with_symbol(I, sym_lst, repl_lst);
1401     }
1402
1403         // Denominator is always a real integer (see numeric::denom())
1404         return (new lst(numex, denom()))->setflag(status_flags::dynallocated);
1405 }
1406
1407
1408 /** Fraction cancellation.
1409  *  @param n  numerator
1410  *  @param d  denominator
1411  *  @return cancelled fraction {n, d} as a list */
1412 static ex frac_cancel(const ex &n, const ex &d)
1413 {
1414     ex num = n;
1415     ex den = d;
1416     numeric pre_factor = _num1();
1417
1418 //clog << "frac_cancel num = " << num << ", den = " << den << endl;
1419
1420     // Handle special cases where numerator or denominator is 0
1421     if (num.is_zero())
1422                 return (new lst(_ex0(), _ex1()))->setflag(status_flags::dynallocated);
1423     if (den.expand().is_zero())
1424         throw(std::overflow_error("frac_cancel: division by zero in frac_cancel"));
1425
1426     // Bring numerator and denominator to Z[X] by multiplying with
1427     // LCM of all coefficients' denominators
1428     numeric num_lcm = lcm_of_coefficients_denominators(num);
1429     numeric den_lcm = lcm_of_coefficients_denominators(den);
1430         num = multiply_lcm(num, num_lcm);
1431         den = multiply_lcm(den, den_lcm);
1432     pre_factor = den_lcm / num_lcm;
1433
1434     // Cancel GCD from numerator and denominator
1435     ex cnum, cden;
1436     if (gcd(num, den, &cnum, &cden, false) != _ex1()) {
1437                 num = cnum;
1438                 den = cden;
1439         }
1440
1441         // Make denominator unit normal (i.e. coefficient of first symbol
1442         // as defined by get_first_symbol() is made positive)
1443         const symbol *x;
1444         if (get_first_symbol(den, x)) {
1445                 GINAC_ASSERT(is_ex_exactly_of_type(den.unit(*x),numeric));
1446                 if (ex_to_numeric(den.unit(*x)).is_negative()) {
1447                         num *= _ex_1();
1448                         den *= _ex_1();
1449                 }
1450         }
1451
1452         // Return result as list
1453 //clog << " returns num = " << num << ", den = " << den << ", pre_factor = " << pre_factor << endl;
1454     return (new lst(num * pre_factor.numer(), den * pre_factor.denom()))->setflag(status_flags::dynallocated);
1455 }
1456
1457
1458 /** Implementation of ex::normal() for a sum. It expands terms and performs
1459  *  fractional addition.
1460  *  @see ex::normal */
1461 ex add::normal(lst &sym_lst, lst &repl_lst, int level) const
1462 {
1463     // Normalize and expand children, chop into summands
1464     exvector o;
1465     o.reserve(seq.size()+1);
1466     epvector::const_iterator it = seq.begin(), itend = seq.end();
1467     while (it != itend) {
1468
1469                 // Normalize and expand child
1470         ex n = recombine_pair_to_ex(*it).bp->normal(sym_lst, repl_lst, level-1).expand();
1471
1472                 // If numerator is a sum, chop into summands
1473         if (is_ex_exactly_of_type(n.op(0), add)) {
1474             epvector::const_iterator bit = ex_to_add(n.op(0)).seq.begin(), bitend = ex_to_add(n.op(0)).seq.end();
1475             while (bit != bitend) {
1476                 o.push_back((new lst(recombine_pair_to_ex(*bit), n.op(1)))->setflag(status_flags::dynallocated));
1477                 bit++;
1478             }
1479
1480                         // The overall_coeff is already normalized (== rational), we just
1481                         // split it into numerator and denominator
1482                         GINAC_ASSERT(ex_to_numeric(ex_to_add(n.op(0)).overall_coeff).is_rational());
1483                         numeric overall = ex_to_numeric(ex_to_add(n.op(0)).overall_coeff);
1484             o.push_back((new lst(overall.numer(), overall.denom() * n.op(1)))->setflag(status_flags::dynallocated));
1485         } else
1486             o.push_back(n);
1487         it++;
1488     }
1489     o.push_back(overall_coeff.bp->normal(sym_lst, repl_lst, level-1));
1490
1491         // o is now a vector of {numerator, denominator} lists
1492
1493     // Determine common denominator
1494     ex den = _ex1();
1495     exvector::const_iterator ait = o.begin(), aitend = o.end();
1496 //clog << "add::normal uses the following summands:\n";
1497     while (ait != aitend) {
1498 //clog << " num = " << ait->op(0) << ", den = " << ait->op(1) << endl;
1499         den = lcm(ait->op(1), den, false);
1500         ait++;
1501     }
1502 //clog << " common denominator = " << den << endl;
1503
1504     // Add fractions
1505     if (den.is_equal(_ex1())) {
1506
1507                 // Common denominator is 1, simply add all numerators
1508         exvector num_seq;
1509                 for (ait=o.begin(); ait!=aitend; ait++) {
1510                         num_seq.push_back(ait->op(0));
1511                 }
1512                 return (new lst((new add(num_seq))->setflag(status_flags::dynallocated), den))->setflag(status_flags::dynallocated);
1513
1514         } else {
1515
1516                 // Perform fractional addition
1517         exvector num_seq;
1518         for (ait=o.begin(); ait!=aitend; ait++) {
1519             ex q;
1520             if (!divide(den, ait->op(1), q, false)) {
1521                 // should not happen
1522                 throw(std::runtime_error("invalid expression in add::normal, division failed"));
1523             }
1524             num_seq.push_back((ait->op(0) * q).expand());
1525         }
1526         ex num = (new add(num_seq))->setflag(status_flags::dynallocated);
1527
1528         // Cancel common factors from num/den
1529         return frac_cancel(num, den);
1530     }
1531 }
1532
1533
1534 /** Implementation of ex::normal() for a product. It cancels common factors
1535  *  from fractions.
1536  *  @see ex::normal() */
1537 ex mul::normal(lst &sym_lst, lst &repl_lst, int level) const
1538 {
1539     // Normalize children, separate into numerator and denominator
1540         ex num = _ex1();
1541         ex den = _ex1(); 
1542         ex n;
1543     epvector::const_iterator it = seq.begin(), itend = seq.end();
1544     while (it != itend) {
1545                 n = recombine_pair_to_ex(*it).bp->normal(sym_lst, repl_lst, level-1);
1546                 num *= n.op(0);
1547                 den *= n.op(1);
1548         it++;
1549     }
1550         n = overall_coeff.bp->normal(sym_lst, repl_lst, level-1);
1551         num *= n.op(0);
1552         den *= n.op(1);
1553
1554         // Perform fraction cancellation
1555     return frac_cancel(num, den);
1556 }
1557
1558
1559 /** Implementation of ex::normal() for powers. It normalizes the basis,
1560  *  distributes integer exponents to numerator and denominator, and replaces
1561  *  non-integer powers by temporary symbols.
1562  *  @see ex::normal */
1563 ex power::normal(lst &sym_lst, lst &repl_lst, int level) const
1564 {
1565         // Normalize basis
1566     ex n = basis.bp->normal(sym_lst, repl_lst, level-1);
1567
1568         if (exponent.info(info_flags::integer)) {
1569
1570             if (exponent.info(info_flags::positive)) {
1571
1572                         // (a/b)^n -> {a^n, b^n}
1573                         return (new lst(power(n.op(0), exponent), power(n.op(1), exponent)))->setflag(status_flags::dynallocated);
1574
1575                 } else if (exponent.info(info_flags::negint)) {
1576
1577                         // (a/b)^-n -> {b^n, a^n}
1578                         return (new lst(power(n.op(1), -exponent), power(n.op(0), -exponent)))->setflag(status_flags::dynallocated);
1579                 }
1580
1581         } else {
1582                 if (exponent.info(info_flags::positive)) {
1583
1584                         // (a/b)^z -> {sym((a/b)^z), 1}
1585                         return (new lst(replace_with_symbol(power(n.op(0) / n.op(1), exponent), sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
1586
1587                 } else {
1588
1589                         if (n.op(1).is_equal(_ex1())) {
1590
1591                                 // a^-x -> {1, sym(a^x)}
1592                                 return (new lst(_ex1(), replace_with_symbol(power(n.op(0), -exponent), sym_lst, repl_lst)))->setflag(status_flags::dynallocated);
1593
1594                         } else {
1595
1596                                 // (a/b)^-x -> {(b/a)^x, 1}
1597                                 return (new lst(replace_with_symbol(power(n.op(1) / n.op(0), -exponent), sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
1598                         }
1599                 }
1600     }
1601 }
1602
1603
1604 /** Implementation of ex::normal() for pseries. It normalizes each coefficient and
1605  *  replaces the series by a temporary symbol.
1606  *  @see ex::normal */
1607 ex pseries::normal(lst &sym_lst, lst &repl_lst, int level) const
1608 {
1609     epvector new_seq;
1610     new_seq.reserve(seq.size());
1611
1612     epvector::const_iterator it = seq.begin(), itend = seq.end();
1613     while (it != itend) {
1614         new_seq.push_back(expair(it->rest.normal(), it->coeff));
1615         it++;
1616     }
1617     ex n = pseries(var, point, new_seq);
1618         return (new lst(replace_with_symbol(n, sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
1619 }
1620
1621
1622 /** Normalization of rational functions.
1623  *  This function converts an expression to its normal form
1624  *  "numerator/denominator", where numerator and denominator are (relatively
1625  *  prime) polynomials. Any subexpressions which are not rational functions
1626  *  (like non-rational numbers, non-integer powers or functions like Sin(),
1627  *  Cos() etc.) are replaced by temporary symbols which are re-substituted by
1628  *  the (normalized) subexpressions before normal() returns (this way, any
1629  *  expression can be treated as a rational function). normal() is applied
1630  *  recursively to arguments of functions etc.
1631  *
1632  *  @param level maximum depth of recursion
1633  *  @return normalized expression */
1634 ex ex::normal(int level) const
1635 {
1636     lst sym_lst, repl_lst;
1637
1638     ex e = bp->normal(sym_lst, repl_lst, level);
1639         GINAC_ASSERT(is_ex_of_type(e, lst));
1640
1641         // Re-insert replaced symbols
1642     if (sym_lst.nops() > 0)
1643         e = e.subs(sym_lst, repl_lst);
1644
1645         // Convert {numerator, denominator} form back to fraction
1646     return e.op(0) / e.op(1);
1647 }
1648
1649 /** Numerator of an expression. If the expression is not of the normal form
1650  *  "numerator/denominator", it is first converted to this form and then the
1651  *  numerator is returned.
1652  *
1653  *  @see ex::normal
1654  *  @return numerator */
1655 ex ex::numer(void) const
1656 {
1657     lst sym_lst, repl_lst;
1658
1659     ex e = bp->normal(sym_lst, repl_lst, 0);
1660         GINAC_ASSERT(is_ex_of_type(e, lst));
1661
1662         // Re-insert replaced symbols
1663     if (sym_lst.nops() > 0)
1664         return e.op(0).subs(sym_lst, repl_lst);
1665         else
1666                 return e.op(0);
1667 }
1668
1669 /** Denominator of an expression. If the expression is not of the normal form
1670  *  "numerator/denominator", it is first converted to this form and then the
1671  *  denominator is returned.
1672  *
1673  *  @see ex::normal
1674  *  @return denominator */
1675 ex ex::denom(void) const
1676 {
1677     lst sym_lst, repl_lst;
1678
1679     ex e = bp->normal(sym_lst, repl_lst, 0);
1680         GINAC_ASSERT(is_ex_of_type(e, lst));
1681
1682         // Re-insert replaced symbols
1683     if (sym_lst.nops() > 0)
1684         return e.op(1).subs(sym_lst, repl_lst);
1685         else
1686                 return e.op(1);
1687 }
1688
1689 #ifndef NO_NAMESPACE_GINAC
1690 } // namespace GiNaC
1691 #endif // ndef NO_NAMESPACE_GINAC