]> www.ginac.de Git - ginac.git/blob - ginac/normal.cpp
* Removed H(m,s,x)
[ginac.git] / ginac / normal.cpp
1 /** @file normal.cpp
2  *
3  *  This file implements several functions that work on univariate and
4  *  multivariate polynomials and rational functions.
5  *  These functions include polynomial quotient and remainder, GCD and LCM
6  *  computation, square-free factorization and rational function normalization. */
7
8 /*
9  *  GiNaC Copyright (C) 1999-2003 Johannes Gutenberg University Mainz, Germany
10  *
11  *  This program is free software; you can redistribute it and/or modify
12  *  it under the terms of the GNU General Public License as published by
13  *  the Free Software Foundation; either version 2 of the License, or
14  *  (at your option) any later version.
15  *
16  *  This program is distributed in the hope that it will be useful,
17  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
18  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  *  GNU General Public License for more details.
20  *
21  *  You should have received a copy of the GNU General Public License
22  *  along with this program; if not, write to the Free Software
23  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
24  */
25
26 #include <algorithm>
27 #include <map>
28
29 #include "normal.h"
30 #include "basic.h"
31 #include "ex.h"
32 #include "add.h"
33 #include "constant.h"
34 #include "expairseq.h"
35 #include "fail.h"
36 #include "inifcns.h"
37 #include "lst.h"
38 #include "mul.h"
39 #include "numeric.h"
40 #include "power.h"
41 #include "relational.h"
42 #include "operators.h"
43 #include "matrix.h"
44 #include "pseries.h"
45 #include "symbol.h"
46 #include "utils.h"
47
48 namespace GiNaC {
49
50 // If comparing expressions (ex::compare()) is fast, you can set this to 1.
51 // Some routines like quo(), rem() and gcd() will then return a quick answer
52 // when they are called with two identical arguments.
53 #define FAST_COMPARE 1
54
55 // Set this if you want divide_in_z() to use remembering
56 #define USE_REMEMBER 0
57
58 // Set this if you want divide_in_z() to use trial division followed by
59 // polynomial interpolation (always slower except for completely dense
60 // polynomials)
61 #define USE_TRIAL_DIVISION 0
62
63 // Set this to enable some statistical output for the GCD routines
64 #define STATISTICS 0
65
66
67 #if STATISTICS
68 // Statistics variables
69 static int gcd_called = 0;
70 static int sr_gcd_called = 0;
71 static int heur_gcd_called = 0;
72 static int heur_gcd_failed = 0;
73
74 // Print statistics at end of program
75 static struct _stat_print {
76         _stat_print() {}
77         ~_stat_print() {
78                 std::cout << "gcd() called " << gcd_called << " times\n";
79                 std::cout << "sr_gcd() called " << sr_gcd_called << " times\n";
80                 std::cout << "heur_gcd() called " << heur_gcd_called << " times\n";
81                 std::cout << "heur_gcd() failed " << heur_gcd_failed << " times\n";
82         }
83 } stat_print;
84 #endif
85
86
87 /** Return pointer to first symbol found in expression.  Due to GiNaCĀ“s
88  *  internal ordering of terms, it may not be obvious which symbol this
89  *  function returns for a given expression.
90  *
91  *  @param e  expression to search
92  *  @param x  first symbol found (returned)
93  *  @return "false" if no symbol was found, "true" otherwise */
94 static bool get_first_symbol(const ex &e, ex &x)
95 {
96         if (is_a<symbol>(e)) {
97                 x = e;
98                 return true;
99         } else if (is_exactly_a<add>(e) || is_exactly_a<mul>(e)) {
100                 for (size_t i=0; i<e.nops(); i++)
101                         if (get_first_symbol(e.op(i), x))
102                                 return true;
103         } else if (is_exactly_a<power>(e)) {
104                 if (get_first_symbol(e.op(0), x))
105                         return true;
106         }
107         return false;
108 }
109
110
111 /*
112  *  Statistical information about symbols in polynomials
113  */
114
115 /** This structure holds information about the highest and lowest degrees
116  *  in which a symbol appears in two multivariate polynomials "a" and "b".
117  *  A vector of these structures with information about all symbols in
118  *  two polynomials can be created with the function get_symbol_stats().
119  *
120  *  @see get_symbol_stats */
121 struct sym_desc {
122         /** Reference to symbol */
123         ex sym;
124
125         /** Highest degree of symbol in polynomial "a" */
126         int deg_a;
127
128         /** Highest degree of symbol in polynomial "b" */
129         int deg_b;
130
131         /** Lowest degree of symbol in polynomial "a" */
132         int ldeg_a;
133
134         /** Lowest degree of symbol in polynomial "b" */
135         int ldeg_b;
136
137         /** Maximum of deg_a and deg_b (Used for sorting) */
138         int max_deg;
139
140         /** Maximum number of terms of leading coefficient of symbol in both polynomials */
141         size_t max_lcnops;
142
143         /** Commparison operator for sorting */
144         bool operator<(const sym_desc &x) const
145         {
146                 if (max_deg == x.max_deg)
147                         return max_lcnops < x.max_lcnops;
148                 else
149                         return max_deg < x.max_deg;
150         }
151 };
152
153 // Vector of sym_desc structures
154 typedef std::vector<sym_desc> sym_desc_vec;
155
156 // Add symbol the sym_desc_vec (used internally by get_symbol_stats())
157 static void add_symbol(const ex &s, sym_desc_vec &v)
158 {
159         sym_desc_vec::const_iterator it = v.begin(), itend = v.end();
160         while (it != itend) {
161                 if (it->sym.is_equal(s))  // If it's already in there, don't add it a second time
162                         return;
163                 ++it;
164         }
165         sym_desc d;
166         d.sym = s;
167         v.push_back(d);
168 }
169
170 // Collect all symbols of an expression (used internally by get_symbol_stats())
171 static void collect_symbols(const ex &e, sym_desc_vec &v)
172 {
173         if (is_a<symbol>(e)) {
174                 add_symbol(e, v);
175         } else if (is_exactly_a<add>(e) || is_exactly_a<mul>(e)) {
176                 for (size_t i=0; i<e.nops(); i++)
177                         collect_symbols(e.op(i), v);
178         } else if (is_exactly_a<power>(e)) {
179                 collect_symbols(e.op(0), v);
180         }
181 }
182
183 /** Collect statistical information about symbols in polynomials.
184  *  This function fills in a vector of "sym_desc" structs which contain
185  *  information about the highest and lowest degrees of all symbols that
186  *  appear in two polynomials. The vector is then sorted by minimum
187  *  degree (lowest to highest). The information gathered by this
188  *  function is used by the GCD routines to identify trivial factors
189  *  and to determine which variable to choose as the main variable
190  *  for GCD computation.
191  *
192  *  @param a  first multivariate polynomial
193  *  @param b  second multivariate polynomial
194  *  @param v  vector of sym_desc structs (filled in) */
195 static void get_symbol_stats(const ex &a, const ex &b, sym_desc_vec &v)
196 {
197         collect_symbols(a.eval(), v);   // eval() to expand assigned symbols
198         collect_symbols(b.eval(), v);
199         sym_desc_vec::iterator it = v.begin(), itend = v.end();
200         while (it != itend) {
201                 int deg_a = a.degree(it->sym);
202                 int deg_b = b.degree(it->sym);
203                 it->deg_a = deg_a;
204                 it->deg_b = deg_b;
205                 it->max_deg = std::max(deg_a, deg_b);
206                 it->max_lcnops = std::max(a.lcoeff(it->sym).nops(), b.lcoeff(it->sym).nops());
207                 it->ldeg_a = a.ldegree(it->sym);
208                 it->ldeg_b = b.ldegree(it->sym);
209                 ++it;
210         }
211         std::sort(v.begin(), v.end());
212
213 #if 0
214         std::clog << "Symbols:\n";
215         it = v.begin(); itend = v.end();
216         while (it != itend) {
217                 std::clog << " " << it->sym << ": deg_a=" << it->deg_a << ", deg_b=" << it->deg_b << ", ldeg_a=" << it->ldeg_a << ", ldeg_b=" << it->ldeg_b << ", max_deg=" << it->max_deg << ", max_lcnops=" << it->max_lcnops << endl;
218                 std::clog << "  lcoeff_a=" << a.lcoeff(it->sym) << ", lcoeff_b=" << b.lcoeff(it->sym) << endl;
219                 ++it;
220         }
221 #endif
222 }
223
224
225 /*
226  *  Computation of LCM of denominators of coefficients of a polynomial
227  */
228
229 // Compute LCM of denominators of coefficients by going through the
230 // expression recursively (used internally by lcm_of_coefficients_denominators())
231 static numeric lcmcoeff(const ex &e, const numeric &l)
232 {
233         if (e.info(info_flags::rational))
234                 return lcm(ex_to<numeric>(e).denom(), l);
235         else if (is_exactly_a<add>(e)) {
236                 numeric c = _num1;
237                 for (size_t i=0; i<e.nops(); i++)
238                         c = lcmcoeff(e.op(i), c);
239                 return lcm(c, l);
240         } else if (is_exactly_a<mul>(e)) {
241                 numeric c = _num1;
242                 for (size_t i=0; i<e.nops(); i++)
243                         c *= lcmcoeff(e.op(i), _num1);
244                 return lcm(c, l);
245         } else if (is_exactly_a<power>(e)) {
246                 if (is_a<symbol>(e.op(0)))
247                         return l;
248                 else
249                         return pow(lcmcoeff(e.op(0), l), ex_to<numeric>(e.op(1)));
250         }
251         return l;
252 }
253
254 /** Compute LCM of denominators of coefficients of a polynomial.
255  *  Given a polynomial with rational coefficients, this function computes
256  *  the LCM of the denominators of all coefficients. This can be used
257  *  to bring a polynomial from Q[X] to Z[X].
258  *
259  *  @param e  multivariate polynomial (need not be expanded)
260  *  @return LCM of denominators of coefficients */
261 static numeric lcm_of_coefficients_denominators(const ex &e)
262 {
263         return lcmcoeff(e, _num1);
264 }
265
266 /** Bring polynomial from Q[X] to Z[X] by multiplying in the previously
267  *  determined LCM of the coefficient's denominators.
268  *
269  *  @param e  multivariate polynomial (need not be expanded)
270  *  @param lcm  LCM to multiply in */
271 static ex multiply_lcm(const ex &e, const numeric &lcm)
272 {
273         if (is_exactly_a<mul>(e)) {
274                 size_t num = e.nops();
275                 exvector v; v.reserve(num + 1);
276                 numeric lcm_accum = _num1;
277                 for (size_t i=0; i<num; i++) {
278                         numeric op_lcm = lcmcoeff(e.op(i), _num1);
279                         v.push_back(multiply_lcm(e.op(i), op_lcm));
280                         lcm_accum *= op_lcm;
281                 }
282                 v.push_back(lcm / lcm_accum);
283                 return (new mul(v))->setflag(status_flags::dynallocated);
284         } else if (is_exactly_a<add>(e)) {
285                 size_t num = e.nops();
286                 exvector v; v.reserve(num);
287                 for (size_t i=0; i<num; i++)
288                         v.push_back(multiply_lcm(e.op(i), lcm));
289                 return (new add(v))->setflag(status_flags::dynallocated);
290         } else if (is_exactly_a<power>(e)) {
291                 if (is_a<symbol>(e.op(0)))
292                         return e * lcm;
293                 else
294                         return pow(multiply_lcm(e.op(0), lcm.power(ex_to<numeric>(e.op(1)).inverse())), e.op(1));
295         } else
296                 return e * lcm;
297 }
298
299
300 /** Compute the integer content (= GCD of all numeric coefficients) of an
301  *  expanded polynomial.
302  *
303  *  @return integer content */
304 numeric ex::integer_content() const
305 {
306         return bp->integer_content();
307 }
308
309 numeric basic::integer_content() const
310 {
311         return _num1;
312 }
313
314 numeric numeric::integer_content() const
315 {
316         return abs(*this);
317 }
318
319 numeric add::integer_content() const
320 {
321         epvector::const_iterator it = seq.begin();
322         epvector::const_iterator itend = seq.end();
323         numeric c = _num0;
324         while (it != itend) {
325                 GINAC_ASSERT(!is_exactly_a<numeric>(it->rest));
326                 GINAC_ASSERT(is_exactly_a<numeric>(it->coeff));
327                 c = gcd(ex_to<numeric>(it->coeff), c);
328                 it++;
329         }
330         GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
331         c = gcd(ex_to<numeric>(overall_coeff),c);
332         return c;
333 }
334
335 numeric mul::integer_content() const
336 {
337 #ifdef DO_GINAC_ASSERT
338         epvector::const_iterator it = seq.begin();
339         epvector::const_iterator itend = seq.end();
340         while (it != itend) {
341                 GINAC_ASSERT(!is_exactly_a<numeric>(recombine_pair_to_ex(*it)));
342                 ++it;
343         }
344 #endif // def DO_GINAC_ASSERT
345         GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
346         return abs(ex_to<numeric>(overall_coeff));
347 }
348
349
350 /*
351  *  Polynomial quotients and remainders
352  */
353
354 /** Quotient q(x) of polynomials a(x) and b(x) in Q[x].
355  *  It satisfies a(x)=b(x)*q(x)+r(x).
356  *
357  *  @param a  first polynomial in x (dividend)
358  *  @param b  second polynomial in x (divisor)
359  *  @param x  a and b are polynomials in x
360  *  @param check_args  check whether a and b are polynomials with rational
361  *         coefficients (defaults to "true")
362  *  @return quotient of a and b in Q[x] */
363 ex quo(const ex &a, const ex &b, const ex &x, bool check_args)
364 {
365         if (b.is_zero())
366                 throw(std::overflow_error("quo: division by zero"));
367         if (is_exactly_a<numeric>(a) && is_exactly_a<numeric>(b))
368                 return a / b;
369 #if FAST_COMPARE
370         if (a.is_equal(b))
371                 return _ex1;
372 #endif
373         if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
374                 throw(std::invalid_argument("quo: arguments must be polynomials over the rationals"));
375
376         // Polynomial long division
377         ex r = a.expand();
378         if (r.is_zero())
379                 return r;
380         int bdeg = b.degree(x);
381         int rdeg = r.degree(x);
382         ex blcoeff = b.expand().coeff(x, bdeg);
383         bool blcoeff_is_numeric = is_exactly_a<numeric>(blcoeff);
384         exvector v; v.reserve(std::max(rdeg - bdeg + 1, 0));
385         while (rdeg >= bdeg) {
386                 ex term, rcoeff = r.coeff(x, rdeg);
387                 if (blcoeff_is_numeric)
388                         term = rcoeff / blcoeff;
389                 else {
390                         if (!divide(rcoeff, blcoeff, term, false))
391                                 return (new fail())->setflag(status_flags::dynallocated);
392                 }
393                 term *= power(x, rdeg - bdeg);
394                 v.push_back(term);
395                 r -= (term * b).expand();
396                 if (r.is_zero())
397                         break;
398                 rdeg = r.degree(x);
399         }
400         return (new add(v))->setflag(status_flags::dynallocated);
401 }
402
403
404 /** Remainder r(x) of polynomials a(x) and b(x) in Q[x].
405  *  It satisfies a(x)=b(x)*q(x)+r(x).
406  *
407  *  @param a  first polynomial in x (dividend)
408  *  @param b  second polynomial in x (divisor)
409  *  @param x  a and b are polynomials in x
410  *  @param check_args  check whether a and b are polynomials with rational
411  *         coefficients (defaults to "true")
412  *  @return remainder of a(x) and b(x) in Q[x] */
413 ex rem(const ex &a, const ex &b, const ex &x, bool check_args)
414 {
415         if (b.is_zero())
416                 throw(std::overflow_error("rem: division by zero"));
417         if (is_exactly_a<numeric>(a)) {
418                 if  (is_exactly_a<numeric>(b))
419                         return _ex0;
420                 else
421                         return a;
422         }
423 #if FAST_COMPARE
424         if (a.is_equal(b))
425                 return _ex0;
426 #endif
427         if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
428                 throw(std::invalid_argument("rem: arguments must be polynomials over the rationals"));
429
430         // Polynomial long division
431         ex r = a.expand();
432         if (r.is_zero())
433                 return r;
434         int bdeg = b.degree(x);
435         int rdeg = r.degree(x);
436         ex blcoeff = b.expand().coeff(x, bdeg);
437         bool blcoeff_is_numeric = is_exactly_a<numeric>(blcoeff);
438         while (rdeg >= bdeg) {
439                 ex term, rcoeff = r.coeff(x, rdeg);
440                 if (blcoeff_is_numeric)
441                         term = rcoeff / blcoeff;
442                 else {
443                         if (!divide(rcoeff, blcoeff, term, false))
444                                 return (new fail())->setflag(status_flags::dynallocated);
445                 }
446                 term *= power(x, rdeg - bdeg);
447                 r -= (term * b).expand();
448                 if (r.is_zero())
449                         break;
450                 rdeg = r.degree(x);
451         }
452         return r;
453 }
454
455
456 /** Decompose rational function a(x)=N(x)/D(x) into P(x)+n(x)/D(x)
457  *  with degree(n, x) < degree(D, x).
458  *
459  *  @param a rational function in x
460  *  @param x a is a function of x
461  *  @return decomposed function. */
462 ex decomp_rational(const ex &a, const ex &x)
463 {
464         ex nd = numer_denom(a);
465         ex numer = nd.op(0), denom = nd.op(1);
466         ex q = quo(numer, denom, x);
467         if (is_exactly_a<fail>(q))
468                 return a;
469         else
470                 return q + rem(numer, denom, x) / denom;
471 }
472
473
474 /** Pseudo-remainder of polynomials a(x) and b(x) in Q[x].
475  *
476  *  @param a  first polynomial in x (dividend)
477  *  @param b  second polynomial in x (divisor)
478  *  @param x  a and b are polynomials in x
479  *  @param check_args  check whether a and b are polynomials with rational
480  *         coefficients (defaults to "true")
481  *  @return pseudo-remainder of a(x) and b(x) in Q[x] */
482 ex prem(const ex &a, const ex &b, const ex &x, bool check_args)
483 {
484         if (b.is_zero())
485                 throw(std::overflow_error("prem: division by zero"));
486         if (is_exactly_a<numeric>(a)) {
487                 if (is_exactly_a<numeric>(b))
488                         return _ex0;
489                 else
490                         return b;
491         }
492         if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
493                 throw(std::invalid_argument("prem: arguments must be polynomials over the rationals"));
494
495         // Polynomial long division
496         ex r = a.expand();
497         ex eb = b.expand();
498         int rdeg = r.degree(x);
499         int bdeg = eb.degree(x);
500         ex blcoeff;
501         if (bdeg <= rdeg) {
502                 blcoeff = eb.coeff(x, bdeg);
503                 if (bdeg == 0)
504                         eb = _ex0;
505                 else
506                         eb -= blcoeff * power(x, bdeg);
507         } else
508                 blcoeff = _ex1;
509
510         int delta = rdeg - bdeg + 1, i = 0;
511         while (rdeg >= bdeg && !r.is_zero()) {
512                 ex rlcoeff = r.coeff(x, rdeg);
513                 ex term = (power(x, rdeg - bdeg) * eb * rlcoeff).expand();
514                 if (rdeg == 0)
515                         r = _ex0;
516                 else
517                         r -= rlcoeff * power(x, rdeg);
518                 r = (blcoeff * r).expand() - term;
519                 rdeg = r.degree(x);
520                 i++;
521         }
522         return power(blcoeff, delta - i) * r;
523 }
524
525
526 /** Sparse pseudo-remainder of polynomials a(x) and b(x) in Q[x].
527  *
528  *  @param a  first polynomial in x (dividend)
529  *  @param b  second polynomial in x (divisor)
530  *  @param x  a and b are polynomials in x
531  *  @param check_args  check whether a and b are polynomials with rational
532  *         coefficients (defaults to "true")
533  *  @return sparse pseudo-remainder of a(x) and b(x) in Q[x] */
534 ex sprem(const ex &a, const ex &b, const ex &x, bool check_args)
535 {
536         if (b.is_zero())
537                 throw(std::overflow_error("prem: division by zero"));
538         if (is_exactly_a<numeric>(a)) {
539                 if (is_exactly_a<numeric>(b))
540                         return _ex0;
541                 else
542                         return b;
543         }
544         if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
545                 throw(std::invalid_argument("prem: arguments must be polynomials over the rationals"));
546
547         // Polynomial long division
548         ex r = a.expand();
549         ex eb = b.expand();
550         int rdeg = r.degree(x);
551         int bdeg = eb.degree(x);
552         ex blcoeff;
553         if (bdeg <= rdeg) {
554                 blcoeff = eb.coeff(x, bdeg);
555                 if (bdeg == 0)
556                         eb = _ex0;
557                 else
558                         eb -= blcoeff * power(x, bdeg);
559         } else
560                 blcoeff = _ex1;
561
562         while (rdeg >= bdeg && !r.is_zero()) {
563                 ex rlcoeff = r.coeff(x, rdeg);
564                 ex term = (power(x, rdeg - bdeg) * eb * rlcoeff).expand();
565                 if (rdeg == 0)
566                         r = _ex0;
567                 else
568                         r -= rlcoeff * power(x, rdeg);
569                 r = (blcoeff * r).expand() - term;
570                 rdeg = r.degree(x);
571         }
572         return r;
573 }
574
575
576 /** Exact polynomial division of a(X) by b(X) in Q[X].
577  *  
578  *  @param a  first multivariate polynomial (dividend)
579  *  @param b  second multivariate polynomial (divisor)
580  *  @param q  quotient (returned)
581  *  @param check_args  check whether a and b are polynomials with rational
582  *         coefficients (defaults to "true")
583  *  @return "true" when exact division succeeds (quotient returned in q),
584  *          "false" otherwise (q left untouched) */
585 bool divide(const ex &a, const ex &b, ex &q, bool check_args)
586 {
587         if (b.is_zero())
588                 throw(std::overflow_error("divide: division by zero"));
589         if (a.is_zero()) {
590                 q = _ex0;
591                 return true;
592         }
593         if (is_exactly_a<numeric>(b)) {
594                 q = a / b;
595                 return true;
596         } else if (is_exactly_a<numeric>(a))
597                 return false;
598 #if FAST_COMPARE
599         if (a.is_equal(b)) {
600                 q = _ex1;
601                 return true;
602         }
603 #endif
604         if (check_args && (!a.info(info_flags::rational_polynomial) ||
605                            !b.info(info_flags::rational_polynomial)))
606                 throw(std::invalid_argument("divide: arguments must be polynomials over the rationals"));
607
608         // Find first symbol
609         ex x;
610         if (!get_first_symbol(a, x) && !get_first_symbol(b, x))
611                 throw(std::invalid_argument("invalid expression in divide()"));
612
613         // Polynomial long division (recursive)
614         ex r = a.expand();
615         if (r.is_zero()) {
616                 q = _ex0;
617                 return true;
618         }
619         int bdeg = b.degree(x);
620         int rdeg = r.degree(x);
621         ex blcoeff = b.expand().coeff(x, bdeg);
622         bool blcoeff_is_numeric = is_exactly_a<numeric>(blcoeff);
623         exvector v; v.reserve(std::max(rdeg - bdeg + 1, 0));
624         while (rdeg >= bdeg) {
625                 ex term, rcoeff = r.coeff(x, rdeg);
626                 if (blcoeff_is_numeric)
627                         term = rcoeff / blcoeff;
628                 else
629                         if (!divide(rcoeff, blcoeff, term, false))
630                                 return false;
631                 term *= power(x, rdeg - bdeg);
632                 v.push_back(term);
633                 r -= (term * b).expand();
634                 if (r.is_zero()) {
635                         q = (new add(v))->setflag(status_flags::dynallocated);
636                         return true;
637                 }
638                 rdeg = r.degree(x);
639         }
640         return false;
641 }
642
643
644 #if USE_REMEMBER
645 /*
646  *  Remembering
647  */
648
649 typedef std::pair<ex, ex> ex2;
650 typedef std::pair<ex, bool> exbool;
651
652 struct ex2_less {
653         bool operator() (const ex2 &p, const ex2 &q) const 
654         {
655                 int cmp = p.first.compare(q.first);
656                 return ((cmp<0) || (!(cmp>0) && p.second.compare(q.second)<0));
657         }
658 };
659
660 typedef std::map<ex2, exbool, ex2_less> ex2_exbool_remember;
661 #endif
662
663
664 /** Exact polynomial division of a(X) by b(X) in Z[X].
665  *  This functions works like divide() but the input and output polynomials are
666  *  in Z[X] instead of Q[X] (i.e. they have integer coefficients). Unlike
667  *  divide(), it doesn't check whether the input polynomials really are integer
668  *  polynomials, so be careful of what you pass in. Also, you have to run
669  *  get_symbol_stats() over the input polynomials before calling this function
670  *  and pass an iterator to the first element of the sym_desc vector. This
671  *  function is used internally by the heur_gcd().
672  *  
673  *  @param a  first multivariate polynomial (dividend)
674  *  @param b  second multivariate polynomial (divisor)
675  *  @param q  quotient (returned)
676  *  @param var  iterator to first element of vector of sym_desc structs
677  *  @return "true" when exact division succeeds (the quotient is returned in
678  *          q), "false" otherwise.
679  *  @see get_symbol_stats, heur_gcd */
680 static bool divide_in_z(const ex &a, const ex &b, ex &q, sym_desc_vec::const_iterator var)
681 {
682         q = _ex0;
683         if (b.is_zero())
684                 throw(std::overflow_error("divide_in_z: division by zero"));
685         if (b.is_equal(_ex1)) {
686                 q = a;
687                 return true;
688         }
689         if (is_exactly_a<numeric>(a)) {
690                 if (is_exactly_a<numeric>(b)) {
691                         q = a / b;
692                         return q.info(info_flags::integer);
693                 } else
694                         return false;
695         }
696 #if FAST_COMPARE
697         if (a.is_equal(b)) {
698                 q = _ex1;
699                 return true;
700         }
701 #endif
702
703 #if USE_REMEMBER
704         // Remembering
705         static ex2_exbool_remember dr_remember;
706         ex2_exbool_remember::const_iterator remembered = dr_remember.find(ex2(a, b));
707         if (remembered != dr_remember.end()) {
708                 q = remembered->second.first;
709                 return remembered->second.second;
710         }
711 #endif
712
713         // Main symbol
714         const ex &x = var->sym;
715
716         // Compare degrees
717         int adeg = a.degree(x), bdeg = b.degree(x);
718         if (bdeg > adeg)
719                 return false;
720
721 #if USE_TRIAL_DIVISION
722
723         // Trial division with polynomial interpolation
724         int i, k;
725
726         // Compute values at evaluation points 0..adeg
727         vector<numeric> alpha; alpha.reserve(adeg + 1);
728         exvector u; u.reserve(adeg + 1);
729         numeric point = _num0;
730         ex c;
731         for (i=0; i<=adeg; i++) {
732                 ex bs = b.subs(x == point, subs_options::no_pattern);
733                 while (bs.is_zero()) {
734                         point += _num1;
735                         bs = b.subs(x == point, subs_options::no_pattern);
736                 }
737                 if (!divide_in_z(a.subs(x == point, subs_options::no_pattern), bs, c, var+1))
738                         return false;
739                 alpha.push_back(point);
740                 u.push_back(c);
741                 point += _num1;
742         }
743
744         // Compute inverses
745         vector<numeric> rcp; rcp.reserve(adeg + 1);
746         rcp.push_back(_num0);
747         for (k=1; k<=adeg; k++) {
748                 numeric product = alpha[k] - alpha[0];
749                 for (i=1; i<k; i++)
750                         product *= alpha[k] - alpha[i];
751                 rcp.push_back(product.inverse());
752         }
753
754         // Compute Newton coefficients
755         exvector v; v.reserve(adeg + 1);
756         v.push_back(u[0]);
757         for (k=1; k<=adeg; k++) {
758                 ex temp = v[k - 1];
759                 for (i=k-2; i>=0; i--)
760                         temp = temp * (alpha[k] - alpha[i]) + v[i];
761                 v.push_back((u[k] - temp) * rcp[k]);
762         }
763
764         // Convert from Newton form to standard form
765         c = v[adeg];
766         for (k=adeg-1; k>=0; k--)
767                 c = c * (x - alpha[k]) + v[k];
768
769         if (c.degree(x) == (adeg - bdeg)) {
770                 q = c.expand();
771                 return true;
772         } else
773                 return false;
774
775 #else
776
777         // Polynomial long division (recursive)
778         ex r = a.expand();
779         if (r.is_zero())
780                 return true;
781         int rdeg = adeg;
782         ex eb = b.expand();
783         ex blcoeff = eb.coeff(x, bdeg);
784         exvector v; v.reserve(std::max(rdeg - bdeg + 1, 0));
785         while (rdeg >= bdeg) {
786                 ex term, rcoeff = r.coeff(x, rdeg);
787                 if (!divide_in_z(rcoeff, blcoeff, term, var+1))
788                         break;
789                 term = (term * power(x, rdeg - bdeg)).expand();
790                 v.push_back(term);
791                 r -= (term * eb).expand();
792                 if (r.is_zero()) {
793                         q = (new add(v))->setflag(status_flags::dynallocated);
794 #if USE_REMEMBER
795                         dr_remember[ex2(a, b)] = exbool(q, true);
796 #endif
797                         return true;
798                 }
799                 rdeg = r.degree(x);
800         }
801 #if USE_REMEMBER
802         dr_remember[ex2(a, b)] = exbool(q, false);
803 #endif
804         return false;
805
806 #endif
807 }
808
809
810 /*
811  *  Separation of unit part, content part and primitive part of polynomials
812  */
813
814 /** Compute unit part (= sign of leading coefficient) of a multivariate
815  *  polynomial in Z[x]. The product of unit part, content part, and primitive
816  *  part is the polynomial itself.
817  *
818  *  @param x  variable in which to compute the unit part
819  *  @return unit part
820  *  @see ex::content, ex::primpart */
821 ex ex::unit(const ex &x) const
822 {
823         ex c = expand().lcoeff(x);
824         if (is_exactly_a<numeric>(c))
825                 return c < _ex0 ? _ex_1 : _ex1;
826         else {
827                 ex y;
828                 if (get_first_symbol(c, y))
829                         return c.unit(y);
830                 else
831                         throw(std::invalid_argument("invalid expression in unit()"));
832         }
833 }
834
835
836 /** Compute content part (= unit normal GCD of all coefficients) of a
837  *  multivariate polynomial in Z[x].  The product of unit part, content part,
838  *  and primitive part is the polynomial itself.
839  *
840  *  @param x  variable in which to compute the content part
841  *  @return content part
842  *  @see ex::unit, ex::primpart */
843 ex ex::content(const ex &x) const
844 {
845         if (is_zero())
846                 return _ex0;
847         if (is_exactly_a<numeric>(*this))
848                 return info(info_flags::negative) ? -*this : *this;
849         ex e = expand();
850         if (e.is_zero())
851                 return _ex0;
852
853         // First, try the integer content
854         ex c = e.integer_content();
855         ex r = e / c;
856         ex lcoeff = r.lcoeff(x);
857         if (lcoeff.info(info_flags::integer))
858                 return c;
859
860         // GCD of all coefficients
861         int deg = e.degree(x);
862         int ldeg = e.ldegree(x);
863         if (deg == ldeg)
864                 return e.lcoeff(x) / e.unit(x);
865         c = _ex0;
866         for (int i=ldeg; i<=deg; i++)
867                 c = gcd(e.coeff(x, i), c, NULL, NULL, false);
868         return c;
869 }
870
871
872 /** Compute primitive part of a multivariate polynomial in Z[x].
873  *  The product of unit part, content part, and primitive part is the
874  *  polynomial itself.
875  *
876  *  @param x  variable in which to compute the primitive part
877  *  @return primitive part
878  *  @see ex::unit, ex::content */
879 ex ex::primpart(const ex &x) const
880 {
881         if (is_zero())
882                 return _ex0;
883         if (is_exactly_a<numeric>(*this))
884                 return _ex1;
885
886         ex c = content(x);
887         if (c.is_zero())
888                 return _ex0;
889         ex u = unit(x);
890         if (is_exactly_a<numeric>(c))
891                 return *this / (c * u);
892         else
893                 return quo(*this, c * u, x, false);
894 }
895
896
897 /** Compute primitive part of a multivariate polynomial in Z[x] when the
898  *  content part is already known. This function is faster in computing the
899  *  primitive part than the previous function.
900  *
901  *  @param x  variable in which to compute the primitive part
902  *  @param c  previously computed content part
903  *  @return primitive part */
904 ex ex::primpart(const ex &x, const ex &c) const
905 {
906         if (is_zero())
907                 return _ex0;
908         if (c.is_zero())
909                 return _ex0;
910         if (is_exactly_a<numeric>(*this))
911                 return _ex1;
912
913         ex u = unit(x);
914         if (is_exactly_a<numeric>(c))
915                 return *this / (c * u);
916         else
917                 return quo(*this, c * u, x, false);
918 }
919
920
921 /*
922  *  GCD of multivariate polynomials
923  */
924
925 /** Compute GCD of multivariate polynomials using the subresultant PRS
926  *  algorithm. This function is used internally by gcd().
927  *
928  *  @param a   first multivariate polynomial
929  *  @param b   second multivariate polynomial
930  *  @param var iterator to first element of vector of sym_desc structs
931  *  @return the GCD as a new expression
932  *  @see gcd */
933
934 static ex sr_gcd(const ex &a, const ex &b, sym_desc_vec::const_iterator var)
935 {
936 #if STATISTICS
937         sr_gcd_called++;
938 #endif
939
940         // The first symbol is our main variable
941         const ex &x = var->sym;
942
943         // Sort c and d so that c has higher degree
944         ex c, d;
945         int adeg = a.degree(x), bdeg = b.degree(x);
946         int cdeg, ddeg;
947         if (adeg >= bdeg) {
948                 c = a;
949                 d = b;
950                 cdeg = adeg;
951                 ddeg = bdeg;
952         } else {
953                 c = b;
954                 d = a;
955                 cdeg = bdeg;
956                 ddeg = adeg;
957         }
958
959         // Remove content from c and d, to be attached to GCD later
960         ex cont_c = c.content(x);
961         ex cont_d = d.content(x);
962         ex gamma = gcd(cont_c, cont_d, NULL, NULL, false);
963         if (ddeg == 0)
964                 return gamma;
965         c = c.primpart(x, cont_c);
966         d = d.primpart(x, cont_d);
967
968         // First element of subresultant sequence
969         ex r = _ex0, ri = _ex1, psi = _ex1;
970         int delta = cdeg - ddeg;
971
972         for (;;) {
973
974                 // Calculate polynomial pseudo-remainder
975                 r = prem(c, d, x, false);
976                 if (r.is_zero())
977                         return gamma * d.primpart(x);
978
979                 c = d;
980                 cdeg = ddeg;
981                 if (!divide_in_z(r, ri * pow(psi, delta), d, var))
982                         throw(std::runtime_error("invalid expression in sr_gcd(), division failed"));
983                 ddeg = d.degree(x);
984                 if (ddeg == 0) {
985                         if (is_exactly_a<numeric>(r))
986                                 return gamma;
987                         else
988                                 return gamma * r.primpart(x);
989                 }
990
991                 // Next element of subresultant sequence
992                 ri = c.expand().lcoeff(x);
993                 if (delta == 1)
994                         psi = ri;
995                 else if (delta)
996                         divide_in_z(pow(ri, delta), pow(psi, delta-1), psi, var+1);
997                 delta = cdeg - ddeg;
998         }
999 }
1000
1001
1002 /** Return maximum (absolute value) coefficient of a polynomial.
1003  *  This function is used internally by heur_gcd().
1004  *
1005  *  @return maximum coefficient
1006  *  @see heur_gcd */
1007 numeric ex::max_coefficient() const
1008 {
1009         return bp->max_coefficient();
1010 }
1011
1012 /** Implementation ex::max_coefficient().
1013  *  @see heur_gcd */
1014 numeric basic::max_coefficient() const
1015 {
1016         return _num1;
1017 }
1018
1019 numeric numeric::max_coefficient() const
1020 {
1021         return abs(*this);
1022 }
1023
1024 numeric add::max_coefficient() const
1025 {
1026         epvector::const_iterator it = seq.begin();
1027         epvector::const_iterator itend = seq.end();
1028         GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
1029         numeric cur_max = abs(ex_to<numeric>(overall_coeff));
1030         while (it != itend) {
1031                 numeric a;
1032                 GINAC_ASSERT(!is_exactly_a<numeric>(it->rest));
1033                 a = abs(ex_to<numeric>(it->coeff));
1034                 if (a > cur_max)
1035                         cur_max = a;
1036                 it++;
1037         }
1038         return cur_max;
1039 }
1040
1041 numeric mul::max_coefficient() const
1042 {
1043 #ifdef DO_GINAC_ASSERT
1044         epvector::const_iterator it = seq.begin();
1045         epvector::const_iterator itend = seq.end();
1046         while (it != itend) {
1047                 GINAC_ASSERT(!is_exactly_a<numeric>(recombine_pair_to_ex(*it)));
1048                 it++;
1049         }
1050 #endif // def DO_GINAC_ASSERT
1051         GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
1052         return abs(ex_to<numeric>(overall_coeff));
1053 }
1054
1055
1056 /** Apply symmetric modular homomorphism to an expanded multivariate
1057  *  polynomial.  This function is usually used internally by heur_gcd().
1058  *
1059  *  @param xi  modulus
1060  *  @return mapped polynomial
1061  *  @see heur_gcd */
1062 ex basic::smod(const numeric &xi) const
1063 {
1064         return *this;
1065 }
1066
1067 ex numeric::smod(const numeric &xi) const
1068 {
1069         return GiNaC::smod(*this, xi);
1070 }
1071
1072 ex add::smod(const numeric &xi) const
1073 {
1074         epvector newseq;
1075         newseq.reserve(seq.size()+1);
1076         epvector::const_iterator it = seq.begin();
1077         epvector::const_iterator itend = seq.end();
1078         while (it != itend) {
1079                 GINAC_ASSERT(!is_exactly_a<numeric>(it->rest));
1080                 numeric coeff = GiNaC::smod(ex_to<numeric>(it->coeff), xi);
1081                 if (!coeff.is_zero())
1082                         newseq.push_back(expair(it->rest, coeff));
1083                 it++;
1084         }
1085         GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
1086         numeric coeff = GiNaC::smod(ex_to<numeric>(overall_coeff), xi);
1087         return (new add(newseq,coeff))->setflag(status_flags::dynallocated);
1088 }
1089
1090 ex mul::smod(const numeric &xi) const
1091 {
1092 #ifdef DO_GINAC_ASSERT
1093         epvector::const_iterator it = seq.begin();
1094         epvector::const_iterator itend = seq.end();
1095         while (it != itend) {
1096                 GINAC_ASSERT(!is_exactly_a<numeric>(recombine_pair_to_ex(*it)));
1097                 it++;
1098         }
1099 #endif // def DO_GINAC_ASSERT
1100         mul * mulcopyp = new mul(*this);
1101         GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
1102         mulcopyp->overall_coeff = GiNaC::smod(ex_to<numeric>(overall_coeff),xi);
1103         mulcopyp->clearflag(status_flags::evaluated);
1104         mulcopyp->clearflag(status_flags::hash_calculated);
1105         return mulcopyp->setflag(status_flags::dynallocated);
1106 }
1107
1108
1109 /** xi-adic polynomial interpolation */
1110 static ex interpolate(const ex &gamma, const numeric &xi, const ex &x, int degree_hint = 1)
1111 {
1112         exvector g; g.reserve(degree_hint);
1113         ex e = gamma;
1114         numeric rxi = xi.inverse();
1115         for (int i=0; !e.is_zero(); i++) {
1116                 ex gi = e.smod(xi);
1117                 g.push_back(gi * power(x, i));
1118                 e = (e - gi) * rxi;
1119         }
1120         return (new add(g))->setflag(status_flags::dynallocated);
1121 }
1122
1123 /** Exception thrown by heur_gcd() to signal failure. */
1124 class gcdheu_failed {};
1125
1126 /** Compute GCD of multivariate polynomials using the heuristic GCD algorithm.
1127  *  get_symbol_stats() must have been called previously with the input
1128  *  polynomials and an iterator to the first element of the sym_desc vector
1129  *  passed in. This function is used internally by gcd().
1130  *
1131  *  @param a  first multivariate polynomial (expanded)
1132  *  @param b  second multivariate polynomial (expanded)
1133  *  @param ca  cofactor of polynomial a (returned), NULL to suppress
1134  *             calculation of cofactor
1135  *  @param cb  cofactor of polynomial b (returned), NULL to suppress
1136  *             calculation of cofactor
1137  *  @param var iterator to first element of vector of sym_desc structs
1138  *  @return the GCD as a new expression
1139  *  @see gcd
1140  *  @exception gcdheu_failed() */
1141 static ex heur_gcd(const ex &a, const ex &b, ex *ca, ex *cb, sym_desc_vec::const_iterator var)
1142 {
1143 #if STATISTICS
1144         heur_gcd_called++;
1145 #endif
1146
1147         // Algorithm only works for non-vanishing input polynomials
1148         if (a.is_zero() || b.is_zero())
1149                 return (new fail())->setflag(status_flags::dynallocated);
1150
1151         // GCD of two numeric values -> CLN
1152         if (is_exactly_a<numeric>(a) && is_exactly_a<numeric>(b)) {
1153                 numeric g = gcd(ex_to<numeric>(a), ex_to<numeric>(b));
1154                 if (ca)
1155                         *ca = ex_to<numeric>(a) / g;
1156                 if (cb)
1157                         *cb = ex_to<numeric>(b) / g;
1158                 return g;
1159         }
1160
1161         // The first symbol is our main variable
1162         const ex &x = var->sym;
1163
1164         // Remove integer content
1165         numeric gc = gcd(a.integer_content(), b.integer_content());
1166         numeric rgc = gc.inverse();
1167         ex p = a * rgc;
1168         ex q = b * rgc;
1169         int maxdeg =  std::max(p.degree(x), q.degree(x));
1170         
1171         // Find evaluation point
1172         numeric mp = p.max_coefficient();
1173         numeric mq = q.max_coefficient();
1174         numeric xi;
1175         if (mp > mq)
1176                 xi = mq * _num2 + _num2;
1177         else
1178                 xi = mp * _num2 + _num2;
1179
1180         // 6 tries maximum
1181         for (int t=0; t<6; t++) {
1182                 if (xi.int_length() * maxdeg > 100000) {
1183                         throw gcdheu_failed();
1184                 }
1185
1186                 // Apply evaluation homomorphism and calculate GCD
1187                 ex cp, cq;
1188                 ex gamma = heur_gcd(p.subs(x == xi, subs_options::no_pattern), q.subs(x == xi, subs_options::no_pattern), &cp, &cq, var+1).expand();
1189                 if (!is_exactly_a<fail>(gamma)) {
1190
1191                         // Reconstruct polynomial from GCD of mapped polynomials
1192                         ex g = interpolate(gamma, xi, x, maxdeg);
1193
1194                         // Remove integer content
1195                         g /= g.integer_content();
1196
1197                         // If the calculated polynomial divides both p and q, this is the GCD
1198                         ex dummy;
1199                         if (divide_in_z(p, g, ca ? *ca : dummy, var) && divide_in_z(q, g, cb ? *cb : dummy, var)) {
1200                                 g *= gc;
1201                                 ex lc = g.lcoeff(x);
1202                                 if (is_exactly_a<numeric>(lc) && ex_to<numeric>(lc).is_negative())
1203                                         return -g;
1204                                 else
1205                                         return g;
1206                         }
1207                 }
1208
1209                 // Next evaluation point
1210                 xi = iquo(xi * isqrt(isqrt(xi)) * numeric(73794), numeric(27011));
1211         }
1212         return (new fail())->setflag(status_flags::dynallocated);
1213 }
1214
1215
1216 /** Compute GCD (Greatest Common Divisor) of multivariate polynomials a(X)
1217  *  and b(X) in Z[X].
1218  *
1219  *  @param a  first multivariate polynomial
1220  *  @param b  second multivariate polynomial
1221  *  @param ca pointer to expression that will receive the cofactor of a, or NULL
1222  *  @param cb pointer to expression that will receive the cofactor of b, or NULL
1223  *  @param check_args  check whether a and b are polynomials with rational
1224  *         coefficients (defaults to "true")
1225  *  @return the GCD as a new expression */
1226 ex gcd(const ex &a, const ex &b, ex *ca, ex *cb, bool check_args)
1227 {
1228 #if STATISTICS
1229         gcd_called++;
1230 #endif
1231
1232         // GCD of numerics -> CLN
1233         if (is_exactly_a<numeric>(a) && is_exactly_a<numeric>(b)) {
1234                 numeric g = gcd(ex_to<numeric>(a), ex_to<numeric>(b));
1235                 if (ca || cb) {
1236                         if (g.is_zero()) {
1237                                 if (ca)
1238                                         *ca = _ex0;
1239                                 if (cb)
1240                                         *cb = _ex0;
1241                         } else {
1242                                 if (ca)
1243                                         *ca = ex_to<numeric>(a) / g;
1244                                 if (cb)
1245                                         *cb = ex_to<numeric>(b) / g;
1246                         }
1247                 }
1248                 return g;
1249         }
1250
1251         // Check arguments
1252         if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial))) {
1253                 throw(std::invalid_argument("gcd: arguments must be polynomials over the rationals"));
1254         }
1255
1256         // Partially factored cases (to avoid expanding large expressions)
1257         if (is_exactly_a<mul>(a)) {
1258                 if (is_exactly_a<mul>(b) && b.nops() > a.nops())
1259                         goto factored_b;
1260 factored_a:
1261                 size_t num = a.nops();
1262                 exvector g; g.reserve(num);
1263                 exvector acc_ca; acc_ca.reserve(num);
1264                 ex part_b = b;
1265                 for (size_t i=0; i<num; i++) {
1266                         ex part_ca, part_cb;
1267                         g.push_back(gcd(a.op(i), part_b, &part_ca, &part_cb, check_args));
1268                         acc_ca.push_back(part_ca);
1269                         part_b = part_cb;
1270                 }
1271                 if (ca)
1272                         *ca = (new mul(acc_ca))->setflag(status_flags::dynallocated);
1273                 if (cb)
1274                         *cb = part_b;
1275                 return (new mul(g))->setflag(status_flags::dynallocated);
1276         } else if (is_exactly_a<mul>(b)) {
1277                 if (is_exactly_a<mul>(a) && a.nops() > b.nops())
1278                         goto factored_a;
1279 factored_b:
1280                 size_t num = b.nops();
1281                 exvector g; g.reserve(num);
1282                 exvector acc_cb; acc_cb.reserve(num);
1283                 ex part_a = a;
1284                 for (size_t i=0; i<num; i++) {
1285                         ex part_ca, part_cb;
1286                         g.push_back(gcd(part_a, b.op(i), &part_ca, &part_cb, check_args));
1287                         acc_cb.push_back(part_cb);
1288                         part_a = part_ca;
1289                 }
1290                 if (ca)
1291                         *ca = part_a;
1292                 if (cb)
1293                         *cb = (new mul(acc_cb))->setflag(status_flags::dynallocated);
1294                 return (new mul(g))->setflag(status_flags::dynallocated);
1295         }
1296
1297 #if FAST_COMPARE
1298         // Input polynomials of the form poly^n are sometimes also trivial
1299         if (is_exactly_a<power>(a)) {
1300                 ex p = a.op(0);
1301                 if (is_exactly_a<power>(b)) {
1302                         if (p.is_equal(b.op(0))) {
1303                                 // a = p^n, b = p^m, gcd = p^min(n, m)
1304                                 ex exp_a = a.op(1), exp_b = b.op(1);
1305                                 if (exp_a < exp_b) {
1306                                         if (ca)
1307                                                 *ca = _ex1;
1308                                         if (cb)
1309                                                 *cb = power(p, exp_b - exp_a);
1310                                         return power(p, exp_a);
1311                                 } else {
1312                                         if (ca)
1313                                                 *ca = power(p, exp_a - exp_b);
1314                                         if (cb)
1315                                                 *cb = _ex1;
1316                                         return power(p, exp_b);
1317                                 }
1318                         }
1319                 } else {
1320                         if (p.is_equal(b)) {
1321                                 // a = p^n, b = p, gcd = p
1322                                 if (ca)
1323                                         *ca = power(p, a.op(1) - 1);
1324                                 if (cb)
1325                                         *cb = _ex1;
1326                                 return p;
1327                         }
1328                 }
1329         } else if (is_exactly_a<power>(b)) {
1330                 ex p = b.op(0);
1331                 if (p.is_equal(a)) {
1332                         // a = p, b = p^n, gcd = p
1333                         if (ca)
1334                                 *ca = _ex1;
1335                         if (cb)
1336                                 *cb = power(p, b.op(1) - 1);
1337                         return p;
1338                 }
1339         }
1340 #endif
1341
1342         // Some trivial cases
1343         ex aex = a.expand(), bex = b.expand();
1344         if (aex.is_zero()) {
1345                 if (ca)
1346                         *ca = _ex0;
1347                 if (cb)
1348                         *cb = _ex1;
1349                 return b;
1350         }
1351         if (bex.is_zero()) {
1352                 if (ca)
1353                         *ca = _ex1;
1354                 if (cb)
1355                         *cb = _ex0;
1356                 return a;
1357         }
1358         if (aex.is_equal(_ex1) || bex.is_equal(_ex1)) {
1359                 if (ca)
1360                         *ca = a;
1361                 if (cb)
1362                         *cb = b;
1363                 return _ex1;
1364         }
1365 #if FAST_COMPARE
1366         if (a.is_equal(b)) {
1367                 if (ca)
1368                         *ca = _ex1;
1369                 if (cb)
1370                         *cb = _ex1;
1371                 return a;
1372         }
1373 #endif
1374
1375         // Gather symbol statistics
1376         sym_desc_vec sym_stats;
1377         get_symbol_stats(a, b, sym_stats);
1378
1379         // The symbol with least degree is our main variable
1380         sym_desc_vec::const_iterator var = sym_stats.begin();
1381         const ex &x = var->sym;
1382
1383         // Cancel trivial common factor
1384         int ldeg_a = var->ldeg_a;
1385         int ldeg_b = var->ldeg_b;
1386         int min_ldeg = std::min(ldeg_a,ldeg_b);
1387         if (min_ldeg > 0) {
1388                 ex common = power(x, min_ldeg);
1389                 return gcd((aex / common).expand(), (bex / common).expand(), ca, cb, false) * common;
1390         }
1391
1392         // Try to eliminate variables
1393         if (var->deg_a == 0) {
1394                 ex c = bex.content(x);
1395                 ex g = gcd(aex, c, ca, cb, false);
1396                 if (cb)
1397                         *cb *= bex.unit(x) * bex.primpart(x, c);
1398                 return g;
1399         } else if (var->deg_b == 0) {
1400                 ex c = aex.content(x);
1401                 ex g = gcd(c, bex, ca, cb, false);
1402                 if (ca)
1403                         *ca *= aex.unit(x) * aex.primpart(x, c);
1404                 return g;
1405         }
1406
1407         // Try heuristic algorithm first, fall back to PRS if that failed
1408         ex g;
1409         try {
1410                 g = heur_gcd(aex, bex, ca, cb, var);
1411         } catch (gcdheu_failed) {
1412                 g = fail();
1413         }
1414         if (is_exactly_a<fail>(g)) {
1415 #if STATISTICS
1416                 heur_gcd_failed++;
1417 #endif
1418                 g = sr_gcd(aex, bex, var);
1419                 if (g.is_equal(_ex1)) {
1420                         // Keep cofactors factored if possible
1421                         if (ca)
1422                                 *ca = a;
1423                         if (cb)
1424                                 *cb = b;
1425                 } else {
1426                         if (ca)
1427                                 divide(aex, g, *ca, false);
1428                         if (cb)
1429                                 divide(bex, g, *cb, false);
1430                 }
1431         } else {
1432                 if (g.is_equal(_ex1)) {
1433                         // Keep cofactors factored if possible
1434                         if (ca)
1435                                 *ca = a;
1436                         if (cb)
1437                                 *cb = b;
1438                 }
1439         }
1440
1441         return g;
1442 }
1443
1444
1445 /** Compute LCM (Least Common Multiple) of multivariate polynomials in Z[X].
1446  *
1447  *  @param a  first multivariate polynomial
1448  *  @param b  second multivariate polynomial
1449  *  @param check_args  check whether a and b are polynomials with rational
1450  *         coefficients (defaults to "true")
1451  *  @return the LCM as a new expression */
1452 ex lcm(const ex &a, const ex &b, bool check_args)
1453 {
1454         if (is_exactly_a<numeric>(a) && is_exactly_a<numeric>(b))
1455                 return lcm(ex_to<numeric>(a), ex_to<numeric>(b));
1456         if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
1457                 throw(std::invalid_argument("lcm: arguments must be polynomials over the rationals"));
1458         
1459         ex ca, cb;
1460         ex g = gcd(a, b, &ca, &cb, false);
1461         return ca * cb * g;
1462 }
1463
1464
1465 /*
1466  *  Square-free factorization
1467  */
1468
1469 /** Compute square-free factorization of multivariate polynomial a(x) using
1470  *  YunĀ“s algorithm.  Used internally by sqrfree().
1471  *
1472  *  @param a  multivariate polynomial over Z[X], treated here as univariate
1473  *            polynomial in x.
1474  *  @param x  variable to factor in
1475  *  @return   vector of factors sorted in ascending degree */
1476 static exvector sqrfree_yun(const ex &a, const symbol &x)
1477 {
1478         exvector res;
1479         ex w = a;
1480         ex z = w.diff(x);
1481         ex g = gcd(w, z);
1482         if (g.is_equal(_ex1)) {
1483                 res.push_back(a);
1484                 return res;
1485         }
1486         ex y;
1487         do {
1488                 w = quo(w, g, x);
1489                 y = quo(z, g, x);
1490                 z = y - w.diff(x);
1491                 g = gcd(w, z);
1492                 res.push_back(g);
1493         } while (!z.is_zero());
1494         return res;
1495 }
1496
1497
1498 /** Compute a square-free factorization of a multivariate polynomial in Q[X].
1499  *
1500  *  @param a  multivariate polynomial over Q[X]
1501  *  @param l  lst of variables to factor in, may be left empty for autodetection
1502  *  @return   a square-free factorization of \p a.
1503  *
1504  * \note
1505  * A polynomial \f$p(X) \in C[X]\f$ is said <EM>square-free</EM>
1506  * if, whenever any two polynomials \f$q(X)\f$ and \f$r(X)\f$
1507  * are such that
1508  * \f[
1509  *     p(X) = q(X)^2 r(X),
1510  * \f]
1511  * we have \f$q(X) \in C\f$.
1512  * This means that \f$p(X)\f$ has no repeated factors, apart
1513  * eventually from constants.
1514  * Given a polynomial \f$p(X) \in C[X]\f$, we say that the
1515  * decomposition
1516  * \f[
1517  *   p(X) = b \cdot p_1(X)^{a_1} \cdot p_2(X)^{a_2} \cdots p_r(X)^{a_r}
1518  * \f]
1519  * is a <EM>square-free factorization</EM> of \f$p(X)\f$ if the
1520  * following conditions hold:
1521  * -#  \f$b \in C\f$ and \f$b \neq 0\f$;
1522  * -#  \f$a_i\f$ is a positive integer for \f$i = 1, \ldots, r\f$;
1523  * -#  the degree of the polynomial \f$p_i\f$ is strictly positive
1524  *     for \f$i = 1, \ldots, r\f$;
1525  * -#  the polynomial \f$\Pi_{i=1}^r p_i(X)\f$ is square-free.
1526  *
1527  * Square-free factorizations need not be unique.  For example, if
1528  * \f$a_i\f$ is even, we could change the polynomial \f$p_i(X)\f$
1529  * into \f$-p_i(X)\f$.
1530  * Observe also that the factors \f$p_i(X)\f$ need not be irreducible
1531  * polynomials.
1532  */
1533 ex sqrfree(const ex &a, const lst &l)
1534 {
1535         if (is_exactly_a<numeric>(a) ||     // algorithm does not trap a==0
1536             is_a<symbol>(a))        // shortcut
1537                 return a;
1538
1539         // If no lst of variables to factorize in was specified we have to
1540         // invent one now.  Maybe one can optimize here by reversing the order
1541         // or so, I don't know.
1542         lst args;
1543         if (l.nops()==0) {
1544                 sym_desc_vec sdv;
1545                 get_symbol_stats(a, _ex0, sdv);
1546                 sym_desc_vec::const_iterator it = sdv.begin(), itend = sdv.end();
1547                 while (it != itend) {
1548                         args.append(it->sym);
1549                         ++it;
1550                 }
1551         } else {
1552                 args = l;
1553         }
1554
1555         // Find the symbol to factor in at this stage
1556         if (!is_a<symbol>(args.op(0)))
1557                 throw (std::runtime_error("sqrfree(): invalid factorization variable"));
1558         const symbol &x = ex_to<symbol>(args.op(0));
1559
1560         // convert the argument from something in Q[X] to something in Z[X]
1561         const numeric lcm = lcm_of_coefficients_denominators(a);
1562         const ex tmp = multiply_lcm(a,lcm);
1563
1564         // find the factors
1565         exvector factors = sqrfree_yun(tmp, x);
1566
1567         // construct the next list of symbols with the first element popped
1568         lst newargs = args;
1569         newargs.remove_first();
1570
1571         // recurse down the factors in remaining variables
1572         if (newargs.nops()>0) {
1573                 exvector::iterator i = factors.begin();
1574                 while (i != factors.end()) {
1575                         *i = sqrfree(*i, newargs);
1576                         ++i;
1577                 }
1578         }
1579
1580         // Done with recursion, now construct the final result
1581         ex result = _ex1;
1582         exvector::const_iterator it = factors.begin(), itend = factors.end();
1583         for (int p = 1; it!=itend; ++it, ++p)
1584                 result *= power(*it, p);
1585
1586         // Yun's algorithm does not account for constant factors.  (For univariate
1587         // polynomials it works only in the monic case.)  We can correct this by
1588         // inserting what has been lost back into the result.  For completeness
1589         // we'll also have to recurse down that factor in the remaining variables.
1590         if (newargs.nops()>0)
1591                 result *= sqrfree(quo(tmp, result, x), newargs);
1592         else
1593                 result *= quo(tmp, result, x);
1594
1595         // Put in the reational overall factor again and return
1596         return result * lcm.inverse();
1597 }
1598
1599
1600 /** Compute square-free partial fraction decomposition of rational function
1601  *  a(x).
1602  *
1603  *  @param a rational function over Z[x], treated as univariate polynomial
1604  *           in x
1605  *  @param x variable to factor in
1606  *  @return decomposed rational function */
1607 ex sqrfree_parfrac(const ex & a, const symbol & x)
1608 {
1609         // Find numerator and denominator
1610         ex nd = numer_denom(a);
1611         ex numer = nd.op(0), denom = nd.op(1);
1612 //clog << "numer = " << numer << ", denom = " << denom << endl;
1613
1614         // Convert N(x)/D(x) -> Q(x) + R(x)/D(x), so degree(R) < degree(D)
1615         ex red_poly = quo(numer, denom, x), red_numer = rem(numer, denom, x).expand();
1616 //clog << "red_poly = " << red_poly << ", red_numer = " << red_numer << endl;
1617
1618         // Factorize denominator and compute cofactors
1619         exvector yun = sqrfree_yun(denom, x);
1620 //clog << "yun factors: " << exprseq(yun) << endl;
1621         size_t num_yun = yun.size();
1622         exvector factor; factor.reserve(num_yun);
1623         exvector cofac; cofac.reserve(num_yun);
1624         for (size_t i=0; i<num_yun; i++) {
1625                 if (!yun[i].is_equal(_ex1)) {
1626                         for (size_t j=0; j<=i; j++) {
1627                                 factor.push_back(pow(yun[i], j+1));
1628                                 ex prod = _ex1;
1629                                 for (size_t k=0; k<num_yun; k++) {
1630                                         if (k == i)
1631                                                 prod *= pow(yun[k], i-j);
1632                                         else
1633                                                 prod *= pow(yun[k], k+1);
1634                                 }
1635                                 cofac.push_back(prod.expand());
1636                         }
1637                 }
1638         }
1639         size_t num_factors = factor.size();
1640 //clog << "factors  : " << exprseq(factor) << endl;
1641 //clog << "cofactors: " << exprseq(cofac) << endl;
1642
1643         // Construct coefficient matrix for decomposition
1644         int max_denom_deg = denom.degree(x);
1645         matrix sys(max_denom_deg + 1, num_factors);
1646         matrix rhs(max_denom_deg + 1, 1);
1647         for (int i=0; i<=max_denom_deg; i++) {
1648                 for (size_t j=0; j<num_factors; j++)
1649                         sys(i, j) = cofac[j].coeff(x, i);
1650                 rhs(i, 0) = red_numer.coeff(x, i);
1651         }
1652 //clog << "coeffs: " << sys << endl;
1653 //clog << "rhs   : " << rhs << endl;
1654
1655         // Solve resulting linear system
1656         matrix vars(num_factors, 1);
1657         for (size_t i=0; i<num_factors; i++)
1658                 vars(i, 0) = symbol();
1659         matrix sol = sys.solve(vars, rhs);
1660
1661         // Sum up decomposed fractions
1662         ex sum = 0;
1663         for (size_t i=0; i<num_factors; i++)
1664                 sum += sol(i, 0) / factor[i];
1665
1666         return red_poly + sum;
1667 }
1668
1669
1670 /*
1671  *  Normal form of rational functions
1672  */
1673
1674 /*
1675  *  Note: The internal normal() functions (= basic::normal() and overloaded
1676  *  functions) all return lists of the form {numerator, denominator}. This
1677  *  is to get around mul::eval()'s automatic expansion of numeric coefficients.
1678  *  E.g. (a+b)/3 is automatically converted to a/3+b/3 but we want to keep
1679  *  the information that (a+b) is the numerator and 3 is the denominator.
1680  */
1681
1682
1683 /** Create a symbol for replacing the expression "e" (or return a previously
1684  *  assigned symbol). The symbol and expression are appended to repl, for
1685  *  a later application of subs().
1686  *  @see ex::normal */
1687 static ex replace_with_symbol(const ex & e, exmap & repl, exmap & rev_lookup)
1688 {
1689         // Expression already replaced? Then return the assigned symbol
1690         exmap::const_iterator it = rev_lookup.find(e);
1691         if (it != rev_lookup.end())
1692                 return it->second;
1693         
1694         // Otherwise create new symbol and add to list, taking care that the
1695         // replacement expression doesn't itself contain symbols from repl,
1696         // because subs() is not recursive
1697         ex es = (new symbol)->setflag(status_flags::dynallocated);
1698         ex e_replaced = e.subs(repl, subs_options::no_pattern);
1699         repl.insert(std::make_pair(es, e_replaced));
1700         rev_lookup.insert(std::make_pair(e_replaced, es));
1701         return es;
1702 }
1703
1704 /** Create a symbol for replacing the expression "e" (or return a previously
1705  *  assigned symbol). The symbol and expression are appended to repl, and the
1706  *  symbol is returned.
1707  *  @see basic::to_rational
1708  *  @see basic::to_polynomial */
1709 static ex replace_with_symbol(const ex & e, exmap & repl)
1710 {
1711         // Expression already replaced? Then return the assigned symbol
1712         for (exmap::const_iterator it = repl.begin(); it != repl.end(); ++it)
1713                 if (it->second.is_equal(e))
1714                         return it->first;
1715         
1716         // Otherwise create new symbol and add to list, taking care that the
1717         // replacement expression doesn't itself contain symbols from repl,
1718         // because subs() is not recursive
1719         ex es = (new symbol)->setflag(status_flags::dynallocated);
1720         ex e_replaced = e.subs(repl, subs_options::no_pattern);
1721         repl.insert(std::make_pair(es, e_replaced));
1722         return es;
1723 }
1724
1725
1726 /** Function object to be applied by basic::normal(). */
1727 struct normal_map_function : public map_function {
1728         int level;
1729         normal_map_function(int l) : level(l) {}
1730         ex operator()(const ex & e) { return normal(e, level); }
1731 };
1732
1733 /** Default implementation of ex::normal(). It normalizes the children and
1734  *  replaces the object with a temporary symbol.
1735  *  @see ex::normal */
1736 ex basic::normal(exmap & repl, exmap & rev_lookup, int level) const
1737 {
1738         if (nops() == 0)
1739                 return (new lst(replace_with_symbol(*this, repl, rev_lookup), _ex1))->setflag(status_flags::dynallocated);
1740         else {
1741                 if (level == 1)
1742                         return (new lst(replace_with_symbol(*this, repl, rev_lookup), _ex1))->setflag(status_flags::dynallocated);
1743                 else if (level == -max_recursion_level)
1744                         throw(std::runtime_error("max recursion level reached"));
1745                 else {
1746                         normal_map_function map_normal(level - 1);
1747                         return (new lst(replace_with_symbol(map(map_normal), repl, rev_lookup), _ex1))->setflag(status_flags::dynallocated);
1748                 }
1749         }
1750 }
1751
1752
1753 /** Implementation of ex::normal() for symbols. This returns the unmodified symbol.
1754  *  @see ex::normal */
1755 ex symbol::normal(exmap & repl, exmap & rev_lookup, int level) const
1756 {
1757         return (new lst(*this, _ex1))->setflag(status_flags::dynallocated);
1758 }
1759
1760
1761 /** Implementation of ex::normal() for a numeric. It splits complex numbers
1762  *  into re+I*im and replaces I and non-rational real numbers with a temporary
1763  *  symbol.
1764  *  @see ex::normal */
1765 ex numeric::normal(exmap & repl, exmap & rev_lookup, int level) const
1766 {
1767         numeric num = numer();
1768         ex numex = num;
1769
1770         if (num.is_real()) {
1771                 if (!num.is_integer())
1772                         numex = replace_with_symbol(numex, repl, rev_lookup);
1773         } else { // complex
1774                 numeric re = num.real(), im = num.imag();
1775                 ex re_ex = re.is_rational() ? re : replace_with_symbol(re, repl, rev_lookup);
1776                 ex im_ex = im.is_rational() ? im : replace_with_symbol(im, repl, rev_lookup);
1777                 numex = re_ex + im_ex * replace_with_symbol(I, repl, rev_lookup);
1778         }
1779
1780         // Denominator is always a real integer (see numeric::denom())
1781         return (new lst(numex, denom()))->setflag(status_flags::dynallocated);
1782 }
1783
1784
1785 /** Fraction cancellation.
1786  *  @param n  numerator
1787  *  @param d  denominator
1788  *  @return cancelled fraction {n, d} as a list */
1789 static ex frac_cancel(const ex &n, const ex &d)
1790 {
1791         ex num = n;
1792         ex den = d;
1793         numeric pre_factor = _num1;
1794
1795 //std::clog << "frac_cancel num = " << num << ", den = " << den << std::endl;
1796
1797         // Handle trivial case where denominator is 1
1798         if (den.is_equal(_ex1))
1799                 return (new lst(num, den))->setflag(status_flags::dynallocated);
1800
1801         // Handle special cases where numerator or denominator is 0
1802         if (num.is_zero())
1803                 return (new lst(num, _ex1))->setflag(status_flags::dynallocated);
1804         if (den.expand().is_zero())
1805                 throw(std::overflow_error("frac_cancel: division by zero in frac_cancel"));
1806
1807         // Bring numerator and denominator to Z[X] by multiplying with
1808         // LCM of all coefficients' denominators
1809         numeric num_lcm = lcm_of_coefficients_denominators(num);
1810         numeric den_lcm = lcm_of_coefficients_denominators(den);
1811         num = multiply_lcm(num, num_lcm);
1812         den = multiply_lcm(den, den_lcm);
1813         pre_factor = den_lcm / num_lcm;
1814
1815         // Cancel GCD from numerator and denominator
1816         ex cnum, cden;
1817         if (gcd(num, den, &cnum, &cden, false) != _ex1) {
1818                 num = cnum;
1819                 den = cden;
1820         }
1821
1822         // Make denominator unit normal (i.e. coefficient of first symbol
1823         // as defined by get_first_symbol() is made positive)
1824         if (is_exactly_a<numeric>(den)) {
1825                 if (ex_to<numeric>(den).is_negative()) {
1826                         num *= _ex_1;
1827                         den *= _ex_1;
1828                 }
1829         } else {
1830                 ex x;
1831                 if (get_first_symbol(den, x)) {
1832                         GINAC_ASSERT(is_exactly_a<numeric>(den.unit(x)));
1833                         if (ex_to<numeric>(den.unit(x)).is_negative()) {
1834                                 num *= _ex_1;
1835                                 den *= _ex_1;
1836                         }
1837                 }
1838         }
1839
1840         // Return result as list
1841 //std::clog << " returns num = " << num << ", den = " << den << ", pre_factor = " << pre_factor << std::endl;
1842         return (new lst(num * pre_factor.numer(), den * pre_factor.denom()))->setflag(status_flags::dynallocated);
1843 }
1844
1845
1846 /** Implementation of ex::normal() for a sum. It expands terms and performs
1847  *  fractional addition.
1848  *  @see ex::normal */
1849 ex add::normal(exmap & repl, exmap & rev_lookup, int level) const
1850 {
1851         if (level == 1)
1852                 return (new lst(replace_with_symbol(*this, repl, rev_lookup), _ex1))->setflag(status_flags::dynallocated);
1853         else if (level == -max_recursion_level)
1854                 throw(std::runtime_error("max recursion level reached"));
1855
1856         // Normalize children and split each one into numerator and denominator
1857         exvector nums, dens;
1858         nums.reserve(seq.size()+1);
1859         dens.reserve(seq.size()+1);
1860         epvector::const_iterator it = seq.begin(), itend = seq.end();
1861         while (it != itend) {
1862                 ex n = ex_to<basic>(recombine_pair_to_ex(*it)).normal(repl, rev_lookup, level-1);
1863                 nums.push_back(n.op(0));
1864                 dens.push_back(n.op(1));
1865                 it++;
1866         }
1867         ex n = ex_to<numeric>(overall_coeff).normal(repl, rev_lookup, level-1);
1868         nums.push_back(n.op(0));
1869         dens.push_back(n.op(1));
1870         GINAC_ASSERT(nums.size() == dens.size());
1871
1872         // Now, nums is a vector of all numerators and dens is a vector of
1873         // all denominators
1874 //std::clog << "add::normal uses " << nums.size() << " summands:\n";
1875
1876         // Add fractions sequentially
1877         exvector::const_iterator num_it = nums.begin(), num_itend = nums.end();
1878         exvector::const_iterator den_it = dens.begin(), den_itend = dens.end();
1879 //std::clog << " num = " << *num_it << ", den = " << *den_it << std::endl;
1880         ex num = *num_it++, den = *den_it++;
1881         while (num_it != num_itend) {
1882 //std::clog << " num = " << *num_it << ", den = " << *den_it << std::endl;
1883                 ex next_num = *num_it++, next_den = *den_it++;
1884
1885                 // Trivially add sequences of fractions with identical denominators
1886                 while ((den_it != den_itend) && next_den.is_equal(*den_it)) {
1887                         next_num += *num_it;
1888                         num_it++; den_it++;
1889                 }
1890
1891                 // Additiion of two fractions, taking advantage of the fact that
1892                 // the heuristic GCD algorithm computes the cofactors at no extra cost
1893                 ex co_den1, co_den2;
1894                 ex g = gcd(den, next_den, &co_den1, &co_den2, false);
1895                 num = ((num * co_den2) + (next_num * co_den1)).expand();
1896                 den *= co_den2;         // this is the lcm(den, next_den)
1897         }
1898 //std::clog << " common denominator = " << den << std::endl;
1899
1900         // Cancel common factors from num/den
1901         return frac_cancel(num, den);
1902 }
1903
1904
1905 /** Implementation of ex::normal() for a product. It cancels common factors
1906  *  from fractions.
1907  *  @see ex::normal() */
1908 ex mul::normal(exmap & repl, exmap & rev_lookup, int level) const
1909 {
1910         if (level == 1)
1911                 return (new lst(replace_with_symbol(*this, repl, rev_lookup), _ex1))->setflag(status_flags::dynallocated);
1912         else if (level == -max_recursion_level)
1913                 throw(std::runtime_error("max recursion level reached"));
1914
1915         // Normalize children, separate into numerator and denominator
1916         exvector num; num.reserve(seq.size());
1917         exvector den; den.reserve(seq.size());
1918         ex n;
1919         epvector::const_iterator it = seq.begin(), itend = seq.end();
1920         while (it != itend) {
1921                 n = ex_to<basic>(recombine_pair_to_ex(*it)).normal(repl, rev_lookup, level-1);
1922                 num.push_back(n.op(0));
1923                 den.push_back(n.op(1));
1924                 it++;
1925         }
1926         n = ex_to<numeric>(overall_coeff).normal(repl, rev_lookup, level-1);
1927         num.push_back(n.op(0));
1928         den.push_back(n.op(1));
1929
1930         // Perform fraction cancellation
1931         return frac_cancel((new mul(num))->setflag(status_flags::dynallocated),
1932                            (new mul(den))->setflag(status_flags::dynallocated));
1933 }
1934
1935
1936 /** Implementation of ex::normal([B) for powers. It normalizes the basis,
1937  *  distributes integer exponents to numerator and denominator, and replaces
1938  *  non-integer powers by temporary symbols.
1939  *  @see ex::normal */
1940 ex power::normal(exmap & repl, exmap & rev_lookup, int level) const
1941 {
1942         if (level == 1)
1943                 return (new lst(replace_with_symbol(*this, repl, rev_lookup), _ex1))->setflag(status_flags::dynallocated);
1944         else if (level == -max_recursion_level)
1945                 throw(std::runtime_error("max recursion level reached"));
1946
1947         // Normalize basis and exponent (exponent gets reassembled)
1948         ex n_basis = ex_to<basic>(basis).normal(repl, rev_lookup, level-1);
1949         ex n_exponent = ex_to<basic>(exponent).normal(repl, rev_lookup, level-1);
1950         n_exponent = n_exponent.op(0) / n_exponent.op(1);
1951
1952         if (n_exponent.info(info_flags::integer)) {
1953
1954                 if (n_exponent.info(info_flags::positive)) {
1955
1956                         // (a/b)^n -> {a^n, b^n}
1957                         return (new lst(power(n_basis.op(0), n_exponent), power(n_basis.op(1), n_exponent)))->setflag(status_flags::dynallocated);
1958
1959                 } else if (n_exponent.info(info_flags::negative)) {
1960
1961                         // (a/b)^-n -> {b^n, a^n}
1962                         return (new lst(power(n_basis.op(1), -n_exponent), power(n_basis.op(0), -n_exponent)))->setflag(status_flags::dynallocated);
1963                 }
1964
1965         } else {
1966
1967                 if (n_exponent.info(info_flags::positive)) {
1968
1969                         // (a/b)^x -> {sym((a/b)^x), 1}
1970                         return (new lst(replace_with_symbol(power(n_basis.op(0) / n_basis.op(1), n_exponent), repl, rev_lookup), _ex1))->setflag(status_flags::dynallocated);
1971
1972                 } else if (n_exponent.info(info_flags::negative)) {
1973
1974                         if (n_basis.op(1).is_equal(_ex1)) {
1975
1976                                 // a^-x -> {1, sym(a^x)}
1977                                 return (new lst(_ex1, replace_with_symbol(power(n_basis.op(0), -n_exponent), repl, rev_lookup)))->setflag(status_flags::dynallocated);
1978
1979                         } else {
1980
1981                                 // (a/b)^-x -> {sym((b/a)^x), 1}
1982                                 return (new lst(replace_with_symbol(power(n_basis.op(1) / n_basis.op(0), -n_exponent), repl, rev_lookup), _ex1))->setflag(status_flags::dynallocated);
1983                         }
1984                 }
1985         }
1986
1987         // (a/b)^x -> {sym((a/b)^x, 1}
1988         return (new lst(replace_with_symbol(power(n_basis.op(0) / n_basis.op(1), n_exponent), repl, rev_lookup), _ex1))->setflag(status_flags::dynallocated);
1989 }
1990
1991
1992 /** Implementation of ex::normal() for pseries. It normalizes each coefficient
1993  *  and replaces the series by a temporary symbol.
1994  *  @see ex::normal */
1995 ex pseries::normal(exmap & repl, exmap & rev_lookup, int level) const
1996 {
1997         epvector newseq;
1998         epvector::const_iterator i = seq.begin(), end = seq.end();
1999         while (i != end) {
2000                 ex restexp = i->rest.normal();
2001                 if (!restexp.is_zero())
2002                         newseq.push_back(expair(restexp, i->coeff));
2003                 ++i;
2004         }
2005         ex n = pseries(relational(var,point), newseq);
2006         return (new lst(replace_with_symbol(n, repl, rev_lookup), _ex1))->setflag(status_flags::dynallocated);
2007 }
2008
2009
2010 /** Normalization of rational functions.
2011  *  This function converts an expression to its normal form
2012  *  "numerator/denominator", where numerator and denominator are (relatively
2013  *  prime) polynomials. Any subexpressions which are not rational functions
2014  *  (like non-rational numbers, non-integer powers or functions like sin(),
2015  *  cos() etc.) are replaced by temporary symbols which are re-substituted by
2016  *  the (normalized) subexpressions before normal() returns (this way, any
2017  *  expression can be treated as a rational function). normal() is applied
2018  *  recursively to arguments of functions etc.
2019  *
2020  *  @param level maximum depth of recursion
2021  *  @return normalized expression */
2022 ex ex::normal(int level) const
2023 {
2024         exmap repl, rev_lookup;
2025
2026         ex e = bp->normal(repl, rev_lookup, level);
2027         GINAC_ASSERT(is_a<lst>(e));
2028
2029         // Re-insert replaced symbols
2030         if (!repl.empty())
2031                 e = e.subs(repl, subs_options::no_pattern);
2032
2033         // Convert {numerator, denominator} form back to fraction
2034         return e.op(0) / e.op(1);
2035 }
2036
2037 /** Get numerator of an expression. If the expression is not of the normal
2038  *  form "numerator/denominator", it is first converted to this form and
2039  *  then the numerator is returned.
2040  *
2041  *  @see ex::normal
2042  *  @return numerator */
2043 ex ex::numer() const
2044 {
2045         exmap repl, rev_lookup;
2046
2047         ex e = bp->normal(repl, rev_lookup, 0);
2048         GINAC_ASSERT(is_a<lst>(e));
2049
2050         // Re-insert replaced symbols
2051         if (repl.empty())
2052                 return e.op(0);
2053         else
2054                 return e.op(0).subs(repl, subs_options::no_pattern);
2055 }
2056
2057 /** Get denominator of an expression. If the expression is not of the normal
2058  *  form "numerator/denominator", it is first converted to this form and
2059  *  then the denominator is returned.
2060  *
2061  *  @see ex::normal
2062  *  @return denominator */
2063 ex ex::denom() const
2064 {
2065         exmap repl, rev_lookup;
2066
2067         ex e = bp->normal(repl, rev_lookup, 0);
2068         GINAC_ASSERT(is_a<lst>(e));
2069
2070         // Re-insert replaced symbols
2071         if (repl.empty())
2072                 return e.op(1);
2073         else
2074                 return e.op(1).subs(repl, subs_options::no_pattern);
2075 }
2076
2077 /** Get numerator and denominator of an expression. If the expresison is not
2078  *  of the normal form "numerator/denominator", it is first converted to this
2079  *  form and then a list [numerator, denominator] is returned.
2080  *
2081  *  @see ex::normal
2082  *  @return a list [numerator, denominator] */
2083 ex ex::numer_denom() const
2084 {
2085         exmap repl, rev_lookup;
2086
2087         ex e = bp->normal(repl, rev_lookup, 0);
2088         GINAC_ASSERT(is_a<lst>(e));
2089
2090         // Re-insert replaced symbols
2091         if (repl.empty())
2092                 return e;
2093         else
2094                 return e.subs(repl, subs_options::no_pattern);
2095 }
2096
2097
2098 /** Rationalization of non-rational functions.
2099  *  This function converts a general expression to a rational function
2100  *  by replacing all non-rational subexpressions (like non-rational numbers,
2101  *  non-integer powers or functions like sin(), cos() etc.) to temporary
2102  *  symbols. This makes it possible to use functions like gcd() and divide()
2103  *  on non-rational functions by applying to_rational() on the arguments,
2104  *  calling the desired function and re-substituting the temporary symbols
2105  *  in the result. To make the last step possible, all temporary symbols and
2106  *  their associated expressions are collected in the map specified by the
2107  *  repl parameter, ready to be passed as an argument to ex::subs().
2108  *
2109  *  @param repl collects all temporary symbols and their replacements
2110  *  @return rationalized expression */
2111 ex ex::to_rational(exmap & repl) const
2112 {
2113         return bp->to_rational(repl);
2114 }
2115
2116 // GiNaC 1.1 compatibility function
2117 ex ex::to_rational(lst & repl_lst) const
2118 {
2119         // Convert lst to exmap
2120         exmap m;
2121         for (lst::const_iterator it = repl_lst.begin(); it != repl_lst.end(); ++it)
2122                 m.insert(std::make_pair(it->op(0), it->op(1)));
2123
2124         ex ret = bp->to_rational(m);
2125
2126         // Convert exmap back to lst
2127         repl_lst.remove_all();
2128         for (exmap::const_iterator it = m.begin(); it != m.end(); ++it)
2129                 repl_lst.append(it->first == it->second);
2130
2131         return ret;
2132 }
2133
2134 ex ex::to_polynomial(exmap & repl) const
2135 {
2136         return bp->to_polynomial(repl);
2137 }
2138
2139 // GiNaC 1.1 compatibility function
2140 ex ex::to_polynomial(lst & repl_lst) const
2141 {
2142         // Convert lst to exmap
2143         exmap m;
2144         for (lst::const_iterator it = repl_lst.begin(); it != repl_lst.end(); ++it)
2145                 m.insert(std::make_pair(it->op(0), it->op(1)));
2146
2147         ex ret = bp->to_polynomial(m);
2148
2149         // Convert exmap back to lst
2150         repl_lst.remove_all();
2151         for (exmap::const_iterator it = m.begin(); it != m.end(); ++it)
2152                 repl_lst.append(it->first == it->second);
2153
2154         return ret;
2155 }
2156
2157 /** Default implementation of ex::to_rational(). This replaces the object with
2158  *  a temporary symbol. */
2159 ex basic::to_rational(exmap & repl) const
2160 {
2161         return replace_with_symbol(*this, repl);
2162 }
2163
2164 ex basic::to_polynomial(exmap & repl) const
2165 {
2166         return replace_with_symbol(*this, repl);
2167 }
2168
2169
2170 /** Implementation of ex::to_rational() for symbols. This returns the
2171  *  unmodified symbol. */
2172 ex symbol::to_rational(exmap & repl) const
2173 {
2174         return *this;
2175 }
2176
2177 /** Implementation of ex::to_polynomial() for symbols. This returns the
2178  *  unmodified symbol. */
2179 ex symbol::to_polynomial(exmap & repl) const
2180 {
2181         return *this;
2182 }
2183
2184
2185 /** Implementation of ex::to_rational() for a numeric. It splits complex
2186  *  numbers into re+I*im and replaces I and non-rational real numbers with a
2187  *  temporary symbol. */
2188 ex numeric::to_rational(exmap & repl) const
2189 {
2190         if (is_real()) {
2191                 if (!is_rational())
2192                         return replace_with_symbol(*this, repl);
2193         } else { // complex
2194                 numeric re = real();
2195                 numeric im = imag();
2196                 ex re_ex = re.is_rational() ? re : replace_with_symbol(re, repl);
2197                 ex im_ex = im.is_rational() ? im : replace_with_symbol(im, repl);
2198                 return re_ex + im_ex * replace_with_symbol(I, repl);
2199         }
2200         return *this;
2201 }
2202
2203 /** Implementation of ex::to_polynomial() for a numeric. It splits complex
2204  *  numbers into re+I*im and replaces I and non-integer real numbers with a
2205  *  temporary symbol. */
2206 ex numeric::to_polynomial(exmap & repl) const
2207 {
2208         if (is_real()) {
2209                 if (!is_integer())
2210                         return replace_with_symbol(*this, repl);
2211         } else { // complex
2212                 numeric re = real();
2213                 numeric im = imag();
2214                 ex re_ex = re.is_integer() ? re : replace_with_symbol(re, repl);
2215                 ex im_ex = im.is_integer() ? im : replace_with_symbol(im, repl);
2216                 return re_ex + im_ex * replace_with_symbol(I, repl);
2217         }
2218         return *this;
2219 }
2220
2221
2222 /** Implementation of ex::to_rational() for powers. It replaces non-integer
2223  *  powers by temporary symbols. */
2224 ex power::to_rational(exmap & repl) const
2225 {
2226         if (exponent.info(info_flags::integer))
2227                 return power(basis.to_rational(repl), exponent);
2228         else
2229                 return replace_with_symbol(*this, repl);
2230 }
2231
2232 /** Implementation of ex::to_polynomial() for powers. It replaces non-posint
2233  *  powers by temporary symbols. */
2234 ex power::to_polynomial(exmap & repl) const
2235 {
2236         if (exponent.info(info_flags::posint))
2237                 return power(basis.to_rational(repl), exponent);
2238         else
2239                 return replace_with_symbol(*this, repl);
2240 }
2241
2242
2243 /** Implementation of ex::to_rational() for expairseqs. */
2244 ex expairseq::to_rational(exmap & repl) const
2245 {
2246         epvector s;
2247         s.reserve(seq.size());
2248         epvector::const_iterator i = seq.begin(), end = seq.end();
2249         while (i != end) {
2250                 s.push_back(split_ex_to_pair(recombine_pair_to_ex(*i).to_rational(repl)));
2251                 ++i;
2252         }
2253         ex oc = overall_coeff.to_rational(repl);
2254         if (oc.info(info_flags::numeric))
2255                 return thisexpairseq(s, overall_coeff);
2256         else
2257                 s.push_back(combine_ex_with_coeff_to_pair(oc, _ex1));
2258         return thisexpairseq(s, default_overall_coeff());
2259 }
2260
2261 /** Implementation of ex::to_polynomial() for expairseqs. */
2262 ex expairseq::to_polynomial(exmap & repl) const
2263 {
2264         epvector s;
2265         s.reserve(seq.size());
2266         epvector::const_iterator i = seq.begin(), end = seq.end();
2267         while (i != end) {
2268                 s.push_back(split_ex_to_pair(recombine_pair_to_ex(*i).to_polynomial(repl)));
2269                 ++i;
2270         }
2271         ex oc = overall_coeff.to_polynomial(repl);
2272         if (oc.info(info_flags::numeric))
2273                 return thisexpairseq(s, overall_coeff);
2274         else
2275                 s.push_back(combine_ex_with_coeff_to_pair(oc, _ex1));
2276         return thisexpairseq(s, default_overall_coeff());
2277 }
2278
2279
2280 /** Remove the common factor in the terms of a sum 'e' by calculating the GCD,
2281  *  and multiply it into the expression 'factor' (which needs to be initialized
2282  *  to 1, unless you're accumulating factors). */
2283 static ex find_common_factor(const ex & e, ex & factor, exmap & repl)
2284 {
2285         if (is_exactly_a<add>(e)) {
2286
2287                 size_t num = e.nops();
2288                 exvector terms; terms.reserve(num);
2289                 ex gc;
2290
2291                 // Find the common GCD
2292                 for (size_t i=0; i<num; i++) {
2293                         ex x = e.op(i).to_polynomial(repl);
2294
2295                         if (is_exactly_a<add>(x) || is_exactly_a<mul>(x)) {
2296                                 ex f = 1;
2297                                 x = find_common_factor(x, f, repl);
2298                                 x *= f;
2299                         }
2300
2301                         if (i == 0)
2302                                 gc = x;
2303                         else
2304                                 gc = gcd(gc, x);
2305
2306                         terms.push_back(x);
2307                 }
2308
2309                 if (gc.is_equal(_ex1))
2310                         return e;
2311
2312                 // The GCD is the factor we pull out
2313                 factor *= gc;
2314
2315                 // Now divide all terms by the GCD
2316                 for (size_t i=0; i<num; i++) {
2317                         ex x;
2318
2319                         // Try to avoid divide() because it expands the polynomial
2320                         ex &t = terms[i];
2321                         if (is_exactly_a<mul>(t)) {
2322                                 for (size_t j=0; j<t.nops(); j++) {
2323                                         if (t.op(j).is_equal(gc)) {
2324                                                 exvector v; v.reserve(t.nops());
2325                                                 for (size_t k=0; k<t.nops(); k++) {
2326                                                         if (k == j)
2327                                                                 v.push_back(_ex1);
2328                                                         else
2329                                                                 v.push_back(t.op(k));
2330                                                 }
2331                                                 t = (new mul(v))->setflag(status_flags::dynallocated);
2332                                                 goto term_done;
2333                                         }
2334                                 }
2335                         }
2336
2337                         divide(t, gc, x);
2338                         t = x;
2339 term_done:      ;
2340                 }
2341                 return (new add(terms))->setflag(status_flags::dynallocated);
2342
2343         } else if (is_exactly_a<mul>(e)) {
2344
2345                 size_t num = e.nops();
2346                 exvector v; v.reserve(num);
2347
2348                 for (size_t i=0; i<num; i++)
2349                         v.push_back(find_common_factor(e.op(i), factor, repl));
2350
2351                 return (new mul(v))->setflag(status_flags::dynallocated);
2352
2353         } else if (is_exactly_a<power>(e)) {
2354
2355                 return e.to_polynomial(repl);
2356
2357         } else
2358                 return e;
2359 }
2360
2361
2362 /** Collect common factors in sums. This converts expressions like
2363  *  'a*(b*x+b*y)' to 'a*b*(x+y)'. */
2364 ex collect_common_factors(const ex & e)
2365 {
2366         if (is_exactly_a<add>(e) || is_exactly_a<mul>(e)) {
2367
2368                 exmap repl;
2369                 ex factor = 1;
2370                 ex r = find_common_factor(e, factor, repl);
2371                 return factor.subs(repl, subs_options::no_pattern) * r.subs(repl, subs_options::no_pattern);
2372
2373         } else
2374                 return e;
2375 }
2376
2377
2378 } // namespace GiNaC