]> www.ginac.de Git - ginac.git/blob - ginac/normal.cpp
- collect_common_factors() works better with negative powers
[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-2002 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 "matrix.h"
43 #include "pseries.h"
44 #include "symbol.h"
45 #include "utils.h"
46
47 namespace GiNaC {
48
49 // If comparing expressions (ex::compare()) is fast, you can set this to 1.
50 // Some routines like quo(), rem() and gcd() will then return a quick answer
51 // when they are called with two identical arguments.
52 #define FAST_COMPARE 1
53
54 // Set this if you want divide_in_z() to use remembering
55 #define USE_REMEMBER 0
56
57 // Set this if you want divide_in_z() to use trial division followed by
58 // polynomial interpolation (always slower except for completely dense
59 // polynomials)
60 #define USE_TRIAL_DIVISION 0
61
62 // Set this to enable some statistical output for the GCD routines
63 #define STATISTICS 0
64
65
66 #if STATISTICS
67 // Statistics variables
68 static int gcd_called = 0;
69 static int sr_gcd_called = 0;
70 static int heur_gcd_called = 0;
71 static int heur_gcd_failed = 0;
72
73 // Print statistics at end of program
74 static struct _stat_print {
75         _stat_print() {}
76         ~_stat_print() {
77                 std::cout << "gcd() called " << gcd_called << " times\n";
78                 std::cout << "sr_gcd() called " << sr_gcd_called << " times\n";
79                 std::cout << "heur_gcd() called " << heur_gcd_called << " times\n";
80                 std::cout << "heur_gcd() failed " << heur_gcd_failed << " times\n";
81         }
82 } stat_print;
83 #endif
84
85
86 /** Return pointer to first symbol found in expression.  Due to GiNaCĀ“s
87  *  internal ordering of terms, it may not be obvious which symbol this
88  *  function returns for a given expression.
89  *
90  *  @param e  expression to search
91  *  @param x  pointer to first symbol found (returned)
92  *  @return "false" if no symbol was found, "true" otherwise */
93 static bool get_first_symbol(const ex &e, const symbol *&x)
94 {
95         if (is_ex_exactly_of_type(e, symbol)) {
96                 x = &ex_to<symbol>(e);
97                 return true;
98         } else if (is_ex_exactly_of_type(e, add) || is_ex_exactly_of_type(e, mul)) {
99                 for (unsigned i=0; i<e.nops(); i++)
100                         if (get_first_symbol(e.op(i), x))
101                                 return true;
102         } else if (is_ex_exactly_of_type(e, power)) {
103                 if (get_first_symbol(e.op(0), x))
104                         return true;
105         }
106         return false;
107 }
108
109
110 /*
111  *  Statistical information about symbols in polynomials
112  */
113
114 /** This structure holds information about the highest and lowest degrees
115  *  in which a symbol appears in two multivariate polynomials "a" and "b".
116  *  A vector of these structures with information about all symbols in
117  *  two polynomials can be created with the function get_symbol_stats().
118  *
119  *  @see get_symbol_stats */
120 struct sym_desc {
121         /** Pointer to symbol */
122         const symbol *sym;
123
124         /** Highest degree of symbol in polynomial "a" */
125         int deg_a;
126
127         /** Highest degree of symbol in polynomial "b" */
128         int deg_b;
129
130         /** Lowest degree of symbol in polynomial "a" */
131         int ldeg_a;
132
133         /** Lowest degree of symbol in polynomial "b" */
134         int ldeg_b;
135
136         /** Maximum of deg_a and deg_b (Used for sorting) */
137         int max_deg;
138
139         /** Maximum number of terms of leading coefficient of symbol in both polynomials */
140         int max_lcnops;
141
142         /** Commparison operator for sorting */
143         bool operator<(const sym_desc &x) const
144         {
145                 if (max_deg == x.max_deg)
146                         return max_lcnops < x.max_lcnops;
147                 else
148                         return max_deg < x.max_deg;
149         }
150 };
151
152 // Vector of sym_desc structures
153 typedef std::vector<sym_desc> sym_desc_vec;
154
155 // Add symbol the sym_desc_vec (used internally by get_symbol_stats())
156 static void add_symbol(const symbol *s, sym_desc_vec &v)
157 {
158         sym_desc_vec::const_iterator it = v.begin(), itend = v.end();
159         while (it != itend) {
160                 if (it->sym->compare(*s) == 0)  // If it's already in there, don't add it a second time
161                         return;
162                 ++it;
163         }
164         sym_desc d;
165         d.sym = s;
166         v.push_back(d);
167 }
168
169 // Collect all symbols of an expression (used internally by get_symbol_stats())
170 static void collect_symbols(const ex &e, sym_desc_vec &v)
171 {
172         if (is_ex_exactly_of_type(e, symbol)) {
173                 add_symbol(&ex_to<symbol>(e), v);
174         } else if (is_ex_exactly_of_type(e, add) || is_ex_exactly_of_type(e, mul)) {
175                 for (unsigned i=0; i<e.nops(); i++)
176                         collect_symbols(e.op(i), v);
177         } else if (is_ex_exactly_of_type(e, power)) {
178                 collect_symbols(e.op(0), v);
179         }
180 }
181
182 /** Collect statistical information about symbols in polynomials.
183  *  This function fills in a vector of "sym_desc" structs which contain
184  *  information about the highest and lowest degrees of all symbols that
185  *  appear in two polynomials. The vector is then sorted by minimum
186  *  degree (lowest to highest). The information gathered by this
187  *  function is used by the GCD routines to identify trivial factors
188  *  and to determine which variable to choose as the main variable
189  *  for GCD computation.
190  *
191  *  @param a  first multivariate polynomial
192  *  @param b  second multivariate polynomial
193  *  @param v  vector of sym_desc structs (filled in) */
194 static void get_symbol_stats(const ex &a, const ex &b, sym_desc_vec &v)
195 {
196         collect_symbols(a.eval(), v);   // eval() to expand assigned symbols
197         collect_symbols(b.eval(), v);
198         sym_desc_vec::iterator it = v.begin(), itend = v.end();
199         while (it != itend) {
200                 int deg_a = a.degree(*(it->sym));
201                 int deg_b = b.degree(*(it->sym));
202                 it->deg_a = deg_a;
203                 it->deg_b = deg_b;
204                 it->max_deg = std::max(deg_a, deg_b);
205                 it->max_lcnops = std::max(a.lcoeff(*(it->sym)).nops(), b.lcoeff(*(it->sym)).nops());
206                 it->ldeg_a = a.ldegree(*(it->sym));
207                 it->ldeg_b = b.ldegree(*(it->sym));
208                 ++it;
209         }
210         std::sort(v.begin(), v.end());
211 #if 0
212         std::clog << "Symbols:\n";
213         it = v.begin(); itend = v.end();
214         while (it != itend) {
215                 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;
216                 std::clog << "  lcoeff_a=" << a.lcoeff(*(it->sym)) << ", lcoeff_b=" << b.lcoeff(*(it->sym)) << endl;
217                 ++it;
218         }
219 #endif
220 }
221
222
223 /*
224  *  Computation of LCM of denominators of coefficients of a polynomial
225  */
226
227 // Compute LCM of denominators of coefficients by going through the
228 // expression recursively (used internally by lcm_of_coefficients_denominators())
229 static numeric lcmcoeff(const ex &e, const numeric &l)
230 {
231         if (e.info(info_flags::rational))
232                 return lcm(ex_to<numeric>(e).denom(), l);
233         else if (is_ex_exactly_of_type(e, add)) {
234                 numeric c = _num1;
235                 for (unsigned i=0; i<e.nops(); i++)
236                         c = lcmcoeff(e.op(i), c);
237                 return lcm(c, l);
238         } else if (is_ex_exactly_of_type(e, mul)) {
239                 numeric c = _num1;
240                 for (unsigned i=0; i<e.nops(); i++)
241                         c *= lcmcoeff(e.op(i), _num1);
242                 return lcm(c, l);
243         } else if (is_ex_exactly_of_type(e, power)) {
244                 if (is_ex_exactly_of_type(e.op(0), symbol))
245                         return l;
246                 else
247                         return pow(lcmcoeff(e.op(0), l), ex_to<numeric>(e.op(1)));
248         }
249         return l;
250 }
251
252 /** Compute LCM of denominators of coefficients of a polynomial.
253  *  Given a polynomial with rational coefficients, this function computes
254  *  the LCM of the denominators of all coefficients. This can be used
255  *  to bring a polynomial from Q[X] to Z[X].
256  *
257  *  @param e  multivariate polynomial (need not be expanded)
258  *  @return LCM of denominators of coefficients */
259 static numeric lcm_of_coefficients_denominators(const ex &e)
260 {
261         return lcmcoeff(e, _num1);
262 }
263
264 /** Bring polynomial from Q[X] to Z[X] by multiplying in the previously
265  *  determined LCM of the coefficient's denominators.
266  *
267  *  @param e  multivariate polynomial (need not be expanded)
268  *  @param lcm  LCM to multiply in */
269 static ex multiply_lcm(const ex &e, const numeric &lcm)
270 {
271         if (is_ex_exactly_of_type(e, mul)) {
272                 unsigned num = e.nops();
273                 exvector v; v.reserve(num + 1);
274                 numeric lcm_accum = _num1;
275                 for (unsigned i=0; i<e.nops(); i++) {
276                         numeric op_lcm = lcmcoeff(e.op(i), _num1);
277                         v.push_back(multiply_lcm(e.op(i), op_lcm));
278                         lcm_accum *= op_lcm;
279                 }
280                 v.push_back(lcm / lcm_accum);
281                 return (new mul(v))->setflag(status_flags::dynallocated);
282         } else if (is_ex_exactly_of_type(e, add)) {
283                 unsigned num = e.nops();
284                 exvector v; v.reserve(num);
285                 for (unsigned i=0; i<num; i++)
286                         v.push_back(multiply_lcm(e.op(i), lcm));
287                 return (new add(v))->setflag(status_flags::dynallocated);
288         } else if (is_ex_exactly_of_type(e, power)) {
289                 if (is_ex_exactly_of_type(e.op(0), symbol))
290                         return e * lcm;
291                 else
292                         return pow(multiply_lcm(e.op(0), lcm.power(ex_to<numeric>(e.op(1)).inverse())), e.op(1));
293         } else
294                 return e * lcm;
295 }
296
297
298 /** Compute the integer content (= GCD of all numeric coefficients) of an
299  *  expanded polynomial.
300  *
301  *  @param e  expanded polynomial
302  *  @return integer content */
303 numeric ex::integer_content(void) const
304 {
305         GINAC_ASSERT(bp!=0);
306         return bp->integer_content();
307 }
308
309 numeric basic::integer_content(void) const
310 {
311         return _num1;
312 }
313
314 numeric numeric::integer_content(void) const
315 {
316         return abs(*this);
317 }
318
319 numeric add::integer_content(void) 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(void) 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 symbol &x, bool check_args)
364 {
365         if (b.is_zero())
366                 throw(std::overflow_error("quo: division by zero"));
367         if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric))
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_ex_exactly_of_type(blcoeff, numeric);
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 symbol &x, bool check_args)
414 {
415         if (b.is_zero())
416                 throw(std::overflow_error("rem: division by zero"));
417         if (is_ex_exactly_of_type(a, numeric)) {
418                 if  (is_ex_exactly_of_type(b, numeric))
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_ex_exactly_of_type(blcoeff, numeric);
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 symbol &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_ex_exactly_of_type(q, fail))
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 symbol &x, bool check_args)
483 {
484         if (b.is_zero())
485                 throw(std::overflow_error("prem: division by zero"));
486         if (is_ex_exactly_of_type(a, numeric)) {
487                 if (is_ex_exactly_of_type(b, numeric))
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 symbol &x, bool check_args)
535 {
536         if (b.is_zero())
537                 throw(std::overflow_error("prem: division by zero"));
538         if (is_ex_exactly_of_type(a, numeric)) {
539                 if (is_ex_exactly_of_type(b, numeric))
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_ex_exactly_of_type(b, numeric)) {
594                 q = a / b;
595                 return true;
596         } else if (is_ex_exactly_of_type(a, numeric))
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         const symbol *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_ex_exactly_of_type(blcoeff, numeric);
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_ex_exactly_of_type(a, numeric)) {
690                 if (is_ex_exactly_of_type(b, numeric)) {
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 symbol *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);
733                 while (bs.is_zero()) {
734                         point += _num1;
735                         bs = b.subs(*x == point);
736                 }
737                 if (!divide_in_z(a.subs(*x == point), 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 symbol &x) const
822 {
823         ex c = expand().lcoeff(x);
824         if (is_ex_exactly_of_type(c, numeric))
825                 return c < _ex0 ? _ex_1 : _ex1;
826         else {
827                 const symbol *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 symbol &x) const
844 {
845         if (is_zero())
846                 return _ex0;
847         if (is_ex_exactly_of_type(*this, numeric))
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 symbol &x) const
880 {
881         if (is_zero())
882                 return _ex0;
883         if (is_ex_exactly_of_type(*this, numeric))
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_ex_exactly_of_type(c, numeric))
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 symbol &x, const ex &c) const
905 {
906         if (is_zero())
907                 return _ex0;
908         if (c.is_zero())
909                 return _ex0;
910         if (is_ex_exactly_of_type(*this, numeric))
911                 return _ex1;
912
913         ex u = unit(x);
914         if (is_ex_exactly_of_type(c, numeric))
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 polynomials in Q[X] using the Euclidean algorithm (not
926  *  really suited for multivariate GCDs). This function is only provided for
927  *  testing purposes.
928  *
929  *  @param a  first multivariate polynomial
930  *  @param b  second multivariate polynomial
931  *  @param x  pointer to symbol (main variable) in which to compute the GCD in
932  *  @return the GCD as a new expression
933  *  @see gcd */
934
935 static ex eu_gcd(const ex &a, const ex &b, const symbol *x)
936 {
937 //std::clog << "eu_gcd(" << a << "," << b << ")\n";
938
939         // Sort c and d so that c has higher degree
940         ex c, d;
941         int adeg = a.degree(*x), bdeg = b.degree(*x);
942         if (adeg >= bdeg) {
943                 c = a;
944                 d = b;
945         } else {
946                 c = b;
947                 d = a;
948         }
949
950         // Normalize in Q[x]
951         c = c / c.lcoeff(*x);
952         d = d / d.lcoeff(*x);
953
954         // Euclidean algorithm
955         ex r;
956         for (;;) {
957 //std::clog << " d = " << d << endl;
958                 r = rem(c, d, *x, false);
959                 if (r.is_zero())
960                         return d / d.lcoeff(*x);
961                 c = d;
962                 d = r;
963         }
964 }
965
966
967 /** Compute GCD of multivariate polynomials using the Euclidean PRS algorithm
968  *  with pseudo-remainders ("World's Worst GCD Algorithm", staying in Z[X]).
969  *  This function is only provided for testing purposes.
970  *
971  *  @param a  first multivariate polynomial
972  *  @param b  second multivariate polynomial
973  *  @param x  pointer to symbol (main variable) in which to compute the GCD in
974  *  @return the GCD as a new expression
975  *  @see gcd */
976
977 static ex euprem_gcd(const ex &a, const ex &b, const symbol *x)
978 {
979 //std::clog << "euprem_gcd(" << a << "," << b << ")\n";
980
981         // Sort c and d so that c has higher degree
982         ex c, d;
983         int adeg = a.degree(*x), bdeg = b.degree(*x);
984         if (adeg >= bdeg) {
985                 c = a;
986                 d = b;
987         } else {
988                 c = b;
989                 d = a;
990         }
991
992         // Calculate GCD of contents
993         ex gamma = gcd(c.content(*x), d.content(*x), NULL, NULL, false);
994
995         // Euclidean algorithm with pseudo-remainders
996         ex r;
997         for (;;) {
998 //std::clog << " d = " << d << endl;
999                 r = prem(c, d, *x, false);
1000                 if (r.is_zero())
1001                         return d.primpart(*x) * gamma;
1002                 c = d;
1003                 d = r;
1004         }
1005 }
1006
1007
1008 /** Compute GCD of multivariate polynomials using the primitive Euclidean
1009  *  PRS algorithm (complete content removal at each step). This function is
1010  *  only provided for testing purposes.
1011  *
1012  *  @param a  first multivariate polynomial
1013  *  @param b  second multivariate polynomial
1014  *  @param x  pointer to symbol (main variable) in which to compute the GCD in
1015  *  @return the GCD as a new expression
1016  *  @see gcd */
1017
1018 static ex peu_gcd(const ex &a, const ex &b, const symbol *x)
1019 {
1020 //std::clog << "peu_gcd(" << a << "," << b << ")\n";
1021
1022         // Sort c and d so that c has higher degree
1023         ex c, d;
1024         int adeg = a.degree(*x), bdeg = b.degree(*x);
1025         int ddeg;
1026         if (adeg >= bdeg) {
1027                 c = a;
1028                 d = b;
1029                 ddeg = bdeg;
1030         } else {
1031                 c = b;
1032                 d = a;
1033                 ddeg = adeg;
1034         }
1035
1036         // Remove content from c and d, to be attached to GCD later
1037         ex cont_c = c.content(*x);
1038         ex cont_d = d.content(*x);
1039         ex gamma = gcd(cont_c, cont_d, NULL, NULL, false);
1040         if (ddeg == 0)
1041                 return gamma;
1042         c = c.primpart(*x, cont_c);
1043         d = d.primpart(*x, cont_d);
1044
1045         // Euclidean algorithm with content removal
1046         ex r;
1047         for (;;) {
1048 //std::clog << " d = " << d << endl;
1049                 r = prem(c, d, *x, false);
1050                 if (r.is_zero())
1051                         return gamma * d;
1052                 c = d;
1053                 d = r.primpart(*x);
1054         }
1055 }
1056
1057
1058 /** Compute GCD of multivariate polynomials using the reduced PRS algorithm.
1059  *  This function is only provided for testing purposes.
1060  *
1061  *  @param a  first multivariate polynomial
1062  *  @param b  second multivariate polynomial
1063  *  @param x  pointer to symbol (main variable) in which to compute the GCD in
1064  *  @return the GCD as a new expression
1065  *  @see gcd */
1066
1067 static ex red_gcd(const ex &a, const ex &b, const symbol *x)
1068 {
1069 //std::clog << "red_gcd(" << a << "," << b << ")\n";
1070
1071         // Sort c and d so that c has higher degree
1072         ex c, d;
1073         int adeg = a.degree(*x), bdeg = b.degree(*x);
1074         int cdeg, ddeg;
1075         if (adeg >= bdeg) {
1076                 c = a;
1077                 d = b;
1078                 cdeg = adeg;
1079                 ddeg = bdeg;
1080         } else {
1081                 c = b;
1082                 d = a;
1083                 cdeg = bdeg;
1084                 ddeg = adeg;
1085         }
1086
1087         // Remove content from c and d, to be attached to GCD later
1088         ex cont_c = c.content(*x);
1089         ex cont_d = d.content(*x);
1090         ex gamma = gcd(cont_c, cont_d, NULL, NULL, false);
1091         if (ddeg == 0)
1092                 return gamma;
1093         c = c.primpart(*x, cont_c);
1094         d = d.primpart(*x, cont_d);
1095
1096         // First element of divisor sequence
1097         ex r, ri = _ex1;
1098         int delta = cdeg - ddeg;
1099
1100         for (;;) {
1101                 // Calculate polynomial pseudo-remainder
1102 //std::clog << " d = " << d << endl;
1103                 r = prem(c, d, *x, false);
1104                 if (r.is_zero())
1105                         return gamma * d.primpart(*x);
1106                 c = d;
1107                 cdeg = ddeg;
1108
1109                 if (!divide(r, pow(ri, delta), d, false))
1110                         throw(std::runtime_error("invalid expression in red_gcd(), division failed"));
1111                 ddeg = d.degree(*x);
1112                 if (ddeg == 0) {
1113                         if (is_ex_exactly_of_type(r, numeric))
1114                                 return gamma;
1115                         else
1116                                 return gamma * r.primpart(*x);
1117                 }
1118
1119                 ri = c.expand().lcoeff(*x);
1120                 delta = cdeg - ddeg;
1121         }
1122 }
1123
1124
1125 /** Compute GCD of multivariate polynomials using the subresultant PRS
1126  *  algorithm. This function is used internally by gcd().
1127  *
1128  *  @param a   first multivariate polynomial
1129  *  @param b   second multivariate polynomial
1130  *  @param var iterator to first element of vector of sym_desc structs
1131  *  @return the GCD as a new expression
1132  *  @see gcd */
1133
1134 static ex sr_gcd(const ex &a, const ex &b, sym_desc_vec::const_iterator var)
1135 {
1136 //std::clog << "sr_gcd(" << a << "," << b << ")\n";
1137 #if STATISTICS
1138         sr_gcd_called++;
1139 #endif
1140
1141         // The first symbol is our main variable
1142         const symbol &x = *(var->sym);
1143
1144         // Sort c and d so that c has higher degree
1145         ex c, d;
1146         int adeg = a.degree(x), bdeg = b.degree(x);
1147         int cdeg, ddeg;
1148         if (adeg >= bdeg) {
1149                 c = a;
1150                 d = b;
1151                 cdeg = adeg;
1152                 ddeg = bdeg;
1153         } else {
1154                 c = b;
1155                 d = a;
1156                 cdeg = bdeg;
1157                 ddeg = adeg;
1158         }
1159
1160         // Remove content from c and d, to be attached to GCD later
1161         ex cont_c = c.content(x);
1162         ex cont_d = d.content(x);
1163         ex gamma = gcd(cont_c, cont_d, NULL, NULL, false);
1164         if (ddeg == 0)
1165                 return gamma;
1166         c = c.primpart(x, cont_c);
1167         d = d.primpart(x, cont_d);
1168 //std::clog << " content " << gamma << " removed, continuing with sr_gcd(" << c << "," << d << ")\n";
1169
1170         // First element of subresultant sequence
1171         ex r = _ex0, ri = _ex1, psi = _ex1;
1172         int delta = cdeg - ddeg;
1173
1174         for (;;) {
1175                 // Calculate polynomial pseudo-remainder
1176 //std::clog << " start of loop, psi = " << psi << ", calculating pseudo-remainder...\n";
1177 //std::clog << " d = " << d << endl;
1178                 r = prem(c, d, x, false);
1179                 if (r.is_zero())
1180                         return gamma * d.primpart(x);
1181                 c = d;
1182                 cdeg = ddeg;
1183 //std::clog << " dividing...\n";
1184                 if (!divide_in_z(r, ri * pow(psi, delta), d, var))
1185                         throw(std::runtime_error("invalid expression in sr_gcd(), division failed"));
1186                 ddeg = d.degree(x);
1187                 if (ddeg == 0) {
1188                         if (is_ex_exactly_of_type(r, numeric))
1189                                 return gamma;
1190                         else
1191                                 return gamma * r.primpart(x);
1192                 }
1193
1194                 // Next element of subresultant sequence
1195 //std::clog << " calculating next subresultant...\n";
1196                 ri = c.expand().lcoeff(x);
1197                 if (delta == 1)
1198                         psi = ri;
1199                 else if (delta)
1200                         divide_in_z(pow(ri, delta), pow(psi, delta-1), psi, var+1);
1201                 delta = cdeg - ddeg;
1202         }
1203 }
1204
1205
1206 /** Return maximum (absolute value) coefficient of a polynomial.
1207  *  This function is used internally by heur_gcd().
1208  *
1209  *  @param e  expanded multivariate polynomial
1210  *  @return maximum coefficient
1211  *  @see heur_gcd */
1212 numeric ex::max_coefficient(void) const
1213 {
1214         GINAC_ASSERT(bp!=0);
1215         return bp->max_coefficient();
1216 }
1217
1218 /** Implementation ex::max_coefficient().
1219  *  @see heur_gcd */
1220 numeric basic::max_coefficient(void) const
1221 {
1222         return _num1;
1223 }
1224
1225 numeric numeric::max_coefficient(void) const
1226 {
1227         return abs(*this);
1228 }
1229
1230 numeric add::max_coefficient(void) const
1231 {
1232         epvector::const_iterator it = seq.begin();
1233         epvector::const_iterator itend = seq.end();
1234         GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
1235         numeric cur_max = abs(ex_to<numeric>(overall_coeff));
1236         while (it != itend) {
1237                 numeric a;
1238                 GINAC_ASSERT(!is_exactly_a<numeric>(it->rest));
1239                 a = abs(ex_to<numeric>(it->coeff));
1240                 if (a > cur_max)
1241                         cur_max = a;
1242                 it++;
1243         }
1244         return cur_max;
1245 }
1246
1247 numeric mul::max_coefficient(void) const
1248 {
1249 #ifdef DO_GINAC_ASSERT
1250         epvector::const_iterator it = seq.begin();
1251         epvector::const_iterator itend = seq.end();
1252         while (it != itend) {
1253                 GINAC_ASSERT(!is_exactly_a<numeric>(recombine_pair_to_ex(*it)));
1254                 it++;
1255         }
1256 #endif // def DO_GINAC_ASSERT
1257         GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
1258         return abs(ex_to<numeric>(overall_coeff));
1259 }
1260
1261
1262 /** Apply symmetric modular homomorphism to an expanded multivariate
1263  *  polynomial.  This function is usually used internally by heur_gcd().
1264  *
1265  *  @param xi  modulus
1266  *  @return mapped polynomial
1267  *  @see heur_gcd */
1268 ex basic::smod(const numeric &xi) const
1269 {
1270         return *this;
1271 }
1272
1273 ex numeric::smod(const numeric &xi) const
1274 {
1275         return GiNaC::smod(*this, xi);
1276 }
1277
1278 ex add::smod(const numeric &xi) const
1279 {
1280         epvector newseq;
1281         newseq.reserve(seq.size()+1);
1282         epvector::const_iterator it = seq.begin();
1283         epvector::const_iterator itend = seq.end();
1284         while (it != itend) {
1285                 GINAC_ASSERT(!is_exactly_a<numeric>(it->rest));
1286                 numeric coeff = GiNaC::smod(ex_to<numeric>(it->coeff), xi);
1287                 if (!coeff.is_zero())
1288                         newseq.push_back(expair(it->rest, coeff));
1289                 it++;
1290         }
1291         GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
1292         numeric coeff = GiNaC::smod(ex_to<numeric>(overall_coeff), xi);
1293         return (new add(newseq,coeff))->setflag(status_flags::dynallocated);
1294 }
1295
1296 ex mul::smod(const numeric &xi) const
1297 {
1298 #ifdef DO_GINAC_ASSERT
1299         epvector::const_iterator it = seq.begin();
1300         epvector::const_iterator itend = seq.end();
1301         while (it != itend) {
1302                 GINAC_ASSERT(!is_exactly_a<numeric>(recombine_pair_to_ex(*it)));
1303                 it++;
1304         }
1305 #endif // def DO_GINAC_ASSERT
1306         mul * mulcopyp = new mul(*this);
1307         GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
1308         mulcopyp->overall_coeff = GiNaC::smod(ex_to<numeric>(overall_coeff),xi);
1309         mulcopyp->clearflag(status_flags::evaluated);
1310         mulcopyp->clearflag(status_flags::hash_calculated);
1311         return mulcopyp->setflag(status_flags::dynallocated);
1312 }
1313
1314
1315 /** xi-adic polynomial interpolation */
1316 static ex interpolate(const ex &gamma, const numeric &xi, const symbol &x, int degree_hint = 1)
1317 {
1318         exvector g; g.reserve(degree_hint);
1319         ex e = gamma;
1320         numeric rxi = xi.inverse();
1321         for (int i=0; !e.is_zero(); i++) {
1322                 ex gi = e.smod(xi);
1323                 g.push_back(gi * power(x, i));
1324                 e = (e - gi) * rxi;
1325         }
1326         return (new add(g))->setflag(status_flags::dynallocated);
1327 }
1328
1329 /** Exception thrown by heur_gcd() to signal failure. */
1330 class gcdheu_failed {};
1331
1332 /** Compute GCD of multivariate polynomials using the heuristic GCD algorithm.
1333  *  get_symbol_stats() must have been called previously with the input
1334  *  polynomials and an iterator to the first element of the sym_desc vector
1335  *  passed in. This function is used internally by gcd().
1336  *
1337  *  @param a  first multivariate polynomial (expanded)
1338  *  @param b  second multivariate polynomial (expanded)
1339  *  @param ca  cofactor of polynomial a (returned), NULL to suppress
1340  *             calculation of cofactor
1341  *  @param cb  cofactor of polynomial b (returned), NULL to suppress
1342  *             calculation of cofactor
1343  *  @param var iterator to first element of vector of sym_desc structs
1344  *  @return the GCD as a new expression
1345  *  @see gcd
1346  *  @exception gcdheu_failed() */
1347 static ex heur_gcd(const ex &a, const ex &b, ex *ca, ex *cb, sym_desc_vec::const_iterator var)
1348 {
1349 //std::clog << "heur_gcd(" << a << "," << b << ")\n";
1350 #if STATISTICS
1351         heur_gcd_called++;
1352 #endif
1353
1354         // Algorithm only works for non-vanishing input polynomials
1355         if (a.is_zero() || b.is_zero())
1356                 return (new fail())->setflag(status_flags::dynallocated);
1357
1358         // GCD of two numeric values -> CLN
1359         if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric)) {
1360                 numeric g = gcd(ex_to<numeric>(a), ex_to<numeric>(b));
1361                 if (ca)
1362                         *ca = ex_to<numeric>(a) / g;
1363                 if (cb)
1364                         *cb = ex_to<numeric>(b) / g;
1365                 return g;
1366         }
1367
1368         // The first symbol is our main variable
1369         const symbol &x = *(var->sym);
1370
1371         // Remove integer content
1372         numeric gc = gcd(a.integer_content(), b.integer_content());
1373         numeric rgc = gc.inverse();
1374         ex p = a * rgc;
1375         ex q = b * rgc;
1376         int maxdeg =  std::max(p.degree(x), q.degree(x));
1377         
1378         // Find evaluation point
1379         numeric mp = p.max_coefficient();
1380         numeric mq = q.max_coefficient();
1381         numeric xi;
1382         if (mp > mq)
1383                 xi = mq * _num2 + _num2;
1384         else
1385                 xi = mp * _num2 + _num2;
1386
1387         // 6 tries maximum
1388         for (int t=0; t<6; t++) {
1389                 if (xi.int_length() * maxdeg > 100000) {
1390 //std::clog << "giving up heur_gcd, xi.int_length = " << xi.int_length() << ", maxdeg = " << maxdeg << std::endl;
1391                         throw gcdheu_failed();
1392                 }
1393
1394                 // Apply evaluation homomorphism and calculate GCD
1395                 ex cp, cq;
1396                 ex gamma = heur_gcd(p.subs(x == xi), q.subs(x == xi), &cp, &cq, var+1).expand();
1397                 if (!is_ex_exactly_of_type(gamma, fail)) {
1398
1399                         // Reconstruct polynomial from GCD of mapped polynomials
1400                         ex g = interpolate(gamma, xi, x, maxdeg);
1401
1402                         // Remove integer content
1403                         g /= g.integer_content();
1404
1405                         // If the calculated polynomial divides both p and q, this is the GCD
1406                         ex dummy;
1407                         if (divide_in_z(p, g, ca ? *ca : dummy, var) && divide_in_z(q, g, cb ? *cb : dummy, var)) {
1408                                 g *= gc;
1409                                 ex lc = g.lcoeff(x);
1410                                 if (is_ex_exactly_of_type(lc, numeric) && ex_to<numeric>(lc).is_negative())
1411                                         return -g;
1412                                 else
1413                                         return g;
1414                         }
1415 #if 0
1416                         cp = interpolate(cp, xi, x);
1417                         if (divide_in_z(cp, p, g, var)) {
1418                                 if (divide_in_z(g, q, cb ? *cb : dummy, var)) {
1419                                         g *= gc;
1420                                         if (ca)
1421                                                 *ca = cp;
1422                                         ex lc = g.lcoeff(x);
1423                                         if (is_ex_exactly_of_type(lc, numeric) && ex_to<numeric>(lc).is_negative())
1424                                                 return -g;
1425                                         else
1426                                                 return g;
1427                                 }
1428                         }
1429                         cq = interpolate(cq, xi, x);
1430                         if (divide_in_z(cq, q, g, var)) {
1431                                 if (divide_in_z(g, p, ca ? *ca : dummy, var)) {
1432                                         g *= gc;
1433                                         if (cb)
1434                                                 *cb = cq;
1435                                         ex lc = g.lcoeff(x);
1436                                         if (is_ex_exactly_of_type(lc, numeric) && ex_to<numeric>(lc).is_negative())
1437                                                 return -g;
1438                                         else
1439                                                 return g;
1440                                 }
1441                         }
1442 #endif
1443                 }
1444
1445                 // Next evaluation point
1446                 xi = iquo(xi * isqrt(isqrt(xi)) * numeric(73794), numeric(27011));
1447         }
1448         return (new fail())->setflag(status_flags::dynallocated);
1449 }
1450
1451
1452 /** Compute GCD (Greatest Common Divisor) of multivariate polynomials a(X)
1453  *  and b(X) in Z[X].
1454  *
1455  *  @param a  first multivariate polynomial
1456  *  @param b  second multivariate polynomial
1457  *  @param check_args  check whether a and b are polynomials with rational
1458  *         coefficients (defaults to "true")
1459  *  @return the GCD as a new expression */
1460 ex gcd(const ex &a, const ex &b, ex *ca, ex *cb, bool check_args)
1461 {
1462 //std::clog << "gcd(" << a << "," << b << ")\n";
1463 #if STATISTICS
1464         gcd_called++;
1465 #endif
1466
1467         // GCD of numerics -> CLN
1468         if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric)) {
1469                 numeric g = gcd(ex_to<numeric>(a), ex_to<numeric>(b));
1470                 if (ca || cb) {
1471                         if (g.is_zero()) {
1472                                 if (ca)
1473                                         *ca = _ex0;
1474                                 if (cb)
1475                                         *cb = _ex0;
1476                         } else {
1477                                 if (ca)
1478                                         *ca = ex_to<numeric>(a) / g;
1479                                 if (cb)
1480                                         *cb = ex_to<numeric>(b) / g;
1481                         }
1482                 }
1483                 return g;
1484         }
1485
1486         // Check arguments
1487         if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial))) {
1488                 throw(std::invalid_argument("gcd: arguments must be polynomials over the rationals"));
1489         }
1490
1491         // Partially factored cases (to avoid expanding large expressions)
1492         if (is_ex_exactly_of_type(a, mul)) {
1493                 if (is_ex_exactly_of_type(b, mul) && b.nops() > a.nops())
1494                         goto factored_b;
1495 factored_a:
1496                 unsigned num = a.nops();
1497                 exvector g; g.reserve(num);
1498                 exvector acc_ca; acc_ca.reserve(num);
1499                 ex part_b = b;
1500                 for (unsigned i=0; i<num; i++) {
1501                         ex part_ca, part_cb;
1502                         g.push_back(gcd(a.op(i), part_b, &part_ca, &part_cb, check_args));
1503                         acc_ca.push_back(part_ca);
1504                         part_b = part_cb;
1505                 }
1506                 if (ca)
1507                         *ca = (new mul(acc_ca))->setflag(status_flags::dynallocated);
1508                 if (cb)
1509                         *cb = part_b;
1510                 return (new mul(g))->setflag(status_flags::dynallocated);
1511         } else if (is_ex_exactly_of_type(b, mul)) {
1512                 if (is_ex_exactly_of_type(a, mul) && a.nops() > b.nops())
1513                         goto factored_a;
1514 factored_b:
1515                 unsigned num = b.nops();
1516                 exvector g; g.reserve(num);
1517                 exvector acc_cb; acc_cb.reserve(num);
1518                 ex part_a = a;
1519                 for (unsigned i=0; i<num; i++) {
1520                         ex part_ca, part_cb;
1521                         g.push_back(gcd(part_a, b.op(i), &part_ca, &part_cb, check_args));
1522                         acc_cb.push_back(part_cb);
1523                         part_a = part_ca;
1524                 }
1525                 if (ca)
1526                         *ca = part_a;
1527                 if (cb)
1528                         *cb = (new mul(acc_cb))->setflag(status_flags::dynallocated);
1529                 return (new mul(g))->setflag(status_flags::dynallocated);
1530         }
1531
1532 #if FAST_COMPARE
1533         // Input polynomials of the form poly^n are sometimes also trivial
1534         if (is_ex_exactly_of_type(a, power)) {
1535                 ex p = a.op(0);
1536                 if (is_ex_exactly_of_type(b, power)) {
1537                         if (p.is_equal(b.op(0))) {
1538                                 // a = p^n, b = p^m, gcd = p^min(n, m)
1539                                 ex exp_a = a.op(1), exp_b = b.op(1);
1540                                 if (exp_a < exp_b) {
1541                                         if (ca)
1542                                                 *ca = _ex1;
1543                                         if (cb)
1544                                                 *cb = power(p, exp_b - exp_a);
1545                                         return power(p, exp_a);
1546                                 } else {
1547                                         if (ca)
1548                                                 *ca = power(p, exp_a - exp_b);
1549                                         if (cb)
1550                                                 *cb = _ex1;
1551                                         return power(p, exp_b);
1552                                 }
1553                         }
1554                 } else {
1555                         if (p.is_equal(b)) {
1556                                 // a = p^n, b = p, gcd = p
1557                                 if (ca)
1558                                         *ca = power(p, a.op(1) - 1);
1559                                 if (cb)
1560                                         *cb = _ex1;
1561                                 return p;
1562                         }
1563                 }
1564         } else if (is_ex_exactly_of_type(b, power)) {
1565                 ex p = b.op(0);
1566                 if (p.is_equal(a)) {
1567                         // a = p, b = p^n, gcd = p
1568                         if (ca)
1569                                 *ca = _ex1;
1570                         if (cb)
1571                                 *cb = power(p, b.op(1) - 1);
1572                         return p;
1573                 }
1574         }
1575 #endif
1576
1577         // Some trivial cases
1578         ex aex = a.expand(), bex = b.expand();
1579         if (aex.is_zero()) {
1580                 if (ca)
1581                         *ca = _ex0;
1582                 if (cb)
1583                         *cb = _ex1;
1584                 return b;
1585         }
1586         if (bex.is_zero()) {
1587                 if (ca)
1588                         *ca = _ex1;
1589                 if (cb)
1590                         *cb = _ex0;
1591                 return a;
1592         }
1593         if (aex.is_equal(_ex1) || bex.is_equal(_ex1)) {
1594                 if (ca)
1595                         *ca = a;
1596                 if (cb)
1597                         *cb = b;
1598                 return _ex1;
1599         }
1600 #if FAST_COMPARE
1601         if (a.is_equal(b)) {
1602                 if (ca)
1603                         *ca = _ex1;
1604                 if (cb)
1605                         *cb = _ex1;
1606                 return a;
1607         }
1608 #endif
1609
1610         // Gather symbol statistics
1611         sym_desc_vec sym_stats;
1612         get_symbol_stats(a, b, sym_stats);
1613
1614         // The symbol with least degree is our main variable
1615         sym_desc_vec::const_iterator var = sym_stats.begin();
1616         const symbol &x = *(var->sym);
1617
1618         // Cancel trivial common factor
1619         int ldeg_a = var->ldeg_a;
1620         int ldeg_b = var->ldeg_b;
1621         int min_ldeg = std::min(ldeg_a,ldeg_b);
1622         if (min_ldeg > 0) {
1623                 ex common = power(x, min_ldeg);
1624 //std::clog << "trivial common factor " << common << std::endl;
1625                 return gcd((aex / common).expand(), (bex / common).expand(), ca, cb, false) * common;
1626         }
1627
1628         // Try to eliminate variables
1629         if (var->deg_a == 0) {
1630 //std::clog << "eliminating variable " << x << " from b" << std::endl;
1631                 ex c = bex.content(x);
1632                 ex g = gcd(aex, c, ca, cb, false);
1633                 if (cb)
1634                         *cb *= bex.unit(x) * bex.primpart(x, c);
1635                 return g;
1636         } else if (var->deg_b == 0) {
1637 //std::clog << "eliminating variable " << x << " from a" << std::endl;
1638                 ex c = aex.content(x);
1639                 ex g = gcd(c, bex, ca, cb, false);
1640                 if (ca)
1641                         *ca *= aex.unit(x) * aex.primpart(x, c);
1642                 return g;
1643         }
1644
1645         ex g;
1646 #if 1
1647         // Try heuristic algorithm first, fall back to PRS if that failed
1648         try {
1649                 g = heur_gcd(aex, bex, ca, cb, var);
1650         } catch (gcdheu_failed) {
1651                 g = fail();
1652         }
1653         if (is_ex_exactly_of_type(g, fail)) {
1654 //std::clog << "heuristics failed" << std::endl;
1655 #if STATISTICS
1656                 heur_gcd_failed++;
1657 #endif
1658 #endif
1659 //              g = heur_gcd(aex, bex, ca, cb, var);
1660 //              g = eu_gcd(aex, bex, &x);
1661 //              g = euprem_gcd(aex, bex, &x);
1662 //              g = peu_gcd(aex, bex, &x);
1663 //              g = red_gcd(aex, bex, &x);
1664                 g = sr_gcd(aex, bex, var);
1665                 if (g.is_equal(_ex1)) {
1666                         // Keep cofactors factored if possible
1667                         if (ca)
1668                                 *ca = a;
1669                         if (cb)
1670                                 *cb = b;
1671                 } else {
1672                         if (ca)
1673                                 divide(aex, g, *ca, false);
1674                         if (cb)
1675                                 divide(bex, g, *cb, false);
1676                 }
1677 #if 1
1678         } else {
1679                 if (g.is_equal(_ex1)) {
1680                         // Keep cofactors factored if possible
1681                         if (ca)
1682                                 *ca = a;
1683                         if (cb)
1684                                 *cb = b;
1685                 }
1686         }
1687 #endif
1688         return g;
1689 }
1690
1691
1692 /** Compute LCM (Least Common Multiple) of multivariate polynomials in Z[X].
1693  *
1694  *  @param a  first multivariate polynomial
1695  *  @param b  second multivariate polynomial
1696  *  @param check_args  check whether a and b are polynomials with rational
1697  *         coefficients (defaults to "true")
1698  *  @return the LCM as a new expression */
1699 ex lcm(const ex &a, const ex &b, bool check_args)
1700 {
1701         if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric))
1702                 return lcm(ex_to<numeric>(a), ex_to<numeric>(b));
1703         if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
1704                 throw(std::invalid_argument("lcm: arguments must be polynomials over the rationals"));
1705         
1706         ex ca, cb;
1707         ex g = gcd(a, b, &ca, &cb, false);
1708         return ca * cb * g;
1709 }
1710
1711
1712 /*
1713  *  Square-free factorization
1714  */
1715
1716 /** Compute square-free factorization of multivariate polynomial a(x) using
1717  *  YunĀ“s algorithm.  Used internally by sqrfree().
1718  *
1719  *  @param a  multivariate polynomial over Z[X], treated here as univariate
1720  *            polynomial in x.
1721  *  @param x  variable to factor in
1722  *  @return   vector of factors sorted in ascending degree */
1723 static exvector sqrfree_yun(const ex &a, const symbol &x)
1724 {
1725         exvector res;
1726         ex w = a;
1727         ex z = w.diff(x);
1728         ex g = gcd(w, z);
1729         if (g.is_equal(_ex1)) {
1730                 res.push_back(a);
1731                 return res;
1732         }
1733         ex y;
1734         do {
1735                 w = quo(w, g, x);
1736                 y = quo(z, g, x);
1737                 z = y - w.diff(x);
1738                 g = gcd(w, z);
1739                 res.push_back(g);
1740         } while (!z.is_zero());
1741         return res;
1742 }
1743
1744
1745 /** Compute a square-free factorization of a multivariate polynomial in Q[X].
1746  *
1747  *  @param a  multivariate polynomial over Q[X]
1748  *  @param x  lst of variables to factor in, may be left empty for autodetection
1749  *  @return   a square-free factorization of \p a.
1750  *
1751  * \note
1752  * A polynomial \f$p(X) \in C[X]\f$ is said <EM>square-free</EM>
1753  * if, whenever any two polynomials \f$q(X)\f$ and \f$r(X)\f$
1754  * are such that
1755  * \f[
1756  *     p(X) = q(X)^2 r(X),
1757  * \f]
1758  * we have \f$q(X) \in C\f$.
1759  * This means that \f$p(X)\f$ has no repeated factors, apart
1760  * eventually from constants.
1761  * Given a polynomial \f$p(X) \in C[X]\f$, we say that the
1762  * decomposition
1763  * \f[
1764  *   p(X) = b \cdot p_1(X)^{a_1} \cdot p_2(X)^{a_2} \cdots p_r(X)^{a_r}
1765  * \f]
1766  * is a <EM>square-free factorization</EM> of \f$p(X)\f$ if the
1767  * following conditions hold:
1768  * -#  \f$b \in C\f$ and \f$b \neq 0\f$;
1769  * -#  \f$a_i\f$ is a positive integer for \f$i = 1, \ldots, r\f$;
1770  * -#  the degree of the polynomial \f$p_i\f$ is strictly positive
1771  *     for \f$i = 1, \ldots, r\f$;
1772  * -#  the polynomial \f$\Pi_{i=1}^r p_i(X)\f$ is square-free.
1773  *
1774  * Square-free factorizations need not be unique.  For example, if
1775  * \f$a_i\f$ is even, we could change the polynomial \f$p_i(X)\f$
1776  * into \f$-p_i(X)\f$.
1777  * Observe also that the factors \f$p_i(X)\f$ need not be irreducible
1778  * polynomials.
1779  */
1780 ex sqrfree(const ex &a, const lst &l)
1781 {
1782         if (is_a<numeric>(a) ||     // algorithm does not trap a==0
1783             is_a<symbol>(a))        // shortcut
1784                 return a;
1785
1786         // If no lst of variables to factorize in was specified we have to
1787         // invent one now.  Maybe one can optimize here by reversing the order
1788         // or so, I don't know.
1789         lst args;
1790         if (l.nops()==0) {
1791                 sym_desc_vec sdv;
1792                 get_symbol_stats(a, _ex0, sdv);
1793                 sym_desc_vec::const_iterator it = sdv.begin(), itend = sdv.end();
1794                 while (it != itend) {
1795                         args.append(*it->sym);
1796                         ++it;
1797                 }
1798         } else {
1799                 args = l;
1800         }
1801
1802         // Find the symbol to factor in at this stage
1803         if (!is_ex_of_type(args.op(0), symbol))
1804                 throw (std::runtime_error("sqrfree(): invalid factorization variable"));
1805         const symbol &x = ex_to<symbol>(args.op(0));
1806
1807         // convert the argument from something in Q[X] to something in Z[X]
1808         const numeric lcm = lcm_of_coefficients_denominators(a);
1809         const ex tmp = multiply_lcm(a,lcm);
1810
1811         // find the factors
1812         exvector factors = sqrfree_yun(tmp,x);
1813
1814         // construct the next list of symbols with the first element popped
1815         lst newargs = args;
1816         newargs.remove_first();
1817
1818         // recurse down the factors in remaining variables
1819         if (newargs.nops()>0) {
1820                 exvector::iterator i = factors.begin();
1821                 while (i != factors.end()) {
1822                         *i = sqrfree(*i, newargs);
1823                         ++i;
1824                 }
1825         }
1826
1827         // Done with recursion, now construct the final result
1828         ex result = _ex1;
1829         exvector::const_iterator it = factors.begin(), itend = factors.end();
1830         for (int p = 1; it!=itend; ++it, ++p)
1831                 result *= power(*it, p);
1832
1833         // Yun's algorithm does not account for constant factors.  (For univariate
1834         // polynomials it works only in the monic case.)  We can correct this by
1835         // inserting what has been lost back into the result.  For completeness
1836         // we'll also have to recurse down that factor in the remaining variables.
1837         if (newargs.nops()>0)
1838                 result *= sqrfree(quo(tmp, result, x), newargs);
1839         else
1840                 result *= quo(tmp, result, x);
1841
1842         // Put in the reational overall factor again and return
1843         return result * lcm.inverse();
1844 }
1845
1846
1847 /** Compute square-free partial fraction decomposition of rational function
1848  *  a(x).
1849  *
1850  *  @param a rational function over Z[x], treated as univariate polynomial
1851  *           in x
1852  *  @param x variable to factor in
1853  *  @return decomposed rational function */
1854 ex sqrfree_parfrac(const ex & a, const symbol & x)
1855 {
1856         // Find numerator and denominator
1857         ex nd = numer_denom(a);
1858         ex numer = nd.op(0), denom = nd.op(1);
1859 //clog << "numer = " << numer << ", denom = " << denom << endl;
1860
1861         // Convert N(x)/D(x) -> Q(x) + R(x)/D(x), so degree(R) < degree(D)
1862         ex red_poly = quo(numer, denom, x), red_numer = rem(numer, denom, x).expand();
1863 //clog << "red_poly = " << red_poly << ", red_numer = " << red_numer << endl;
1864
1865         // Factorize denominator and compute cofactors
1866         exvector yun = sqrfree_yun(denom, x);
1867 //clog << "yun factors: " << exprseq(yun) << endl;
1868         unsigned num_yun = yun.size();
1869         exvector factor; factor.reserve(num_yun);
1870         exvector cofac; cofac.reserve(num_yun);
1871         for (unsigned i=0; i<num_yun; i++) {
1872                 if (!yun[i].is_equal(_ex1)) {
1873                         for (unsigned j=0; j<=i; j++) {
1874                                 factor.push_back(pow(yun[i], j+1));
1875                                 ex prod = _ex1;
1876                                 for (unsigned k=0; k<num_yun; k++) {
1877                                         if (k == i)
1878                                                 prod *= pow(yun[k], i-j);
1879                                         else
1880                                                 prod *= pow(yun[k], k+1);
1881                                 }
1882                                 cofac.push_back(prod.expand());
1883                         }
1884                 }
1885         }
1886         unsigned num_factors = factor.size();
1887 //clog << "factors  : " << exprseq(factor) << endl;
1888 //clog << "cofactors: " << exprseq(cofac) << endl;
1889
1890         // Construct coefficient matrix for decomposition
1891         int max_denom_deg = denom.degree(x);
1892         matrix sys(max_denom_deg + 1, num_factors);
1893         matrix rhs(max_denom_deg + 1, 1);
1894         for (int i=0; i<=max_denom_deg; i++) {
1895                 for (unsigned j=0; j<num_factors; j++)
1896                         sys(i, j) = cofac[j].coeff(x, i);
1897                 rhs(i, 0) = red_numer.coeff(x, i);
1898         }
1899 //clog << "coeffs: " << sys << endl;
1900 //clog << "rhs   : " << rhs << endl;
1901
1902         // Solve resulting linear system
1903         matrix vars(num_factors, 1);
1904         for (unsigned i=0; i<num_factors; i++)
1905                 vars(i, 0) = symbol();
1906         matrix sol = sys.solve(vars, rhs);
1907
1908         // Sum up decomposed fractions
1909         ex sum = 0;
1910         for (unsigned i=0; i<num_factors; i++)
1911                 sum += sol(i, 0) / factor[i];
1912
1913         return red_poly + sum;
1914 }
1915
1916
1917 /*
1918  *  Normal form of rational functions
1919  */
1920
1921 /*
1922  *  Note: The internal normal() functions (= basic::normal() and overloaded
1923  *  functions) all return lists of the form {numerator, denominator}. This
1924  *  is to get around mul::eval()'s automatic expansion of numeric coefficients.
1925  *  E.g. (a+b)/3 is automatically converted to a/3+b/3 but we want to keep
1926  *  the information that (a+b) is the numerator and 3 is the denominator.
1927  */
1928
1929
1930 /** Create a symbol for replacing the expression "e" (or return a previously
1931  *  assigned symbol). The symbol is appended to sym_lst and returned, the
1932  *  expression is appended to repl_lst.
1933  *  @see ex::normal */
1934 static ex replace_with_symbol(const ex &e, lst &sym_lst, lst &repl_lst)
1935 {
1936         // Expression already in repl_lst? Then return the assigned symbol
1937         for (unsigned i=0; i<repl_lst.nops(); i++)
1938                 if (repl_lst.op(i).is_equal(e))
1939                         return sym_lst.op(i);
1940         
1941         // Otherwise create new symbol and add to list, taking care that the
1942         // replacement expression doesn't contain symbols from the sym_lst
1943         // because subs() is not recursive
1944         symbol s;
1945         ex es(s);
1946         ex e_replaced = e.subs(sym_lst, repl_lst);
1947         sym_lst.append(es);
1948         repl_lst.append(e_replaced);
1949         return es;
1950 }
1951
1952 /** Create a symbol for replacing the expression "e" (or return a previously
1953  *  assigned symbol). An expression of the form "symbol == expression" is added
1954  *  to repl_lst and the symbol is returned.
1955  *  @see basic::to_rational */
1956 static ex replace_with_symbol(const ex &e, lst &repl_lst)
1957 {
1958         // Expression already in repl_lst? Then return the assigned symbol
1959         for (unsigned i=0; i<repl_lst.nops(); i++)
1960                 if (repl_lst.op(i).op(1).is_equal(e))
1961                         return repl_lst.op(i).op(0);
1962         
1963         // Otherwise create new symbol and add to list, taking care that the
1964         // replacement expression doesn't contain symbols from the sym_lst
1965         // because subs() is not recursive
1966         symbol s;
1967         ex es(s);
1968         ex e_replaced = e.subs(repl_lst);
1969         repl_lst.append(es == e_replaced);
1970         return es;
1971 }
1972
1973
1974 /** Function object to be applied by basic::normal(). */
1975 struct normal_map_function : public map_function {
1976         int level;
1977         normal_map_function(int l) : level(l) {}
1978         ex operator()(const ex & e) { return normal(e, level); }
1979 };
1980
1981 /** Default implementation of ex::normal(). It normalizes the children and
1982  *  replaces the object with a temporary symbol.
1983  *  @see ex::normal */
1984 ex basic::normal(lst &sym_lst, lst &repl_lst, int level) const
1985 {
1986         if (nops() == 0)
1987                 return (new lst(replace_with_symbol(*this, sym_lst, repl_lst), _ex1))->setflag(status_flags::dynallocated);
1988         else {
1989                 if (level == 1)
1990                         return (new lst(replace_with_symbol(*this, sym_lst, repl_lst), _ex1))->setflag(status_flags::dynallocated);
1991                 else if (level == -max_recursion_level)
1992                         throw(std::runtime_error("max recursion level reached"));
1993                 else {
1994                         normal_map_function map_normal(level - 1);
1995                         return (new lst(replace_with_symbol(map(map_normal), sym_lst, repl_lst), _ex1))->setflag(status_flags::dynallocated);
1996                 }
1997         }
1998 }
1999
2000
2001 /** Implementation of ex::normal() for symbols. This returns the unmodified symbol.
2002  *  @see ex::normal */
2003 ex symbol::normal(lst &sym_lst, lst &repl_lst, int level) const
2004 {
2005         return (new lst(*this, _ex1))->setflag(status_flags::dynallocated);
2006 }
2007
2008
2009 /** Implementation of ex::normal() for a numeric. It splits complex numbers
2010  *  into re+I*im and replaces I and non-rational real numbers with a temporary
2011  *  symbol.
2012  *  @see ex::normal */
2013 ex numeric::normal(lst &sym_lst, lst &repl_lst, int level) const
2014 {
2015         numeric num = numer();
2016         ex numex = num;
2017
2018         if (num.is_real()) {
2019                 if (!num.is_integer())
2020                         numex = replace_with_symbol(numex, sym_lst, repl_lst);
2021         } else { // complex
2022                 numeric re = num.real(), im = num.imag();
2023                 ex re_ex = re.is_rational() ? re : replace_with_symbol(re, sym_lst, repl_lst);
2024                 ex im_ex = im.is_rational() ? im : replace_with_symbol(im, sym_lst, repl_lst);
2025                 numex = re_ex + im_ex * replace_with_symbol(I, sym_lst, repl_lst);
2026         }
2027
2028         // Denominator is always a real integer (see numeric::denom())
2029         return (new lst(numex, denom()))->setflag(status_flags::dynallocated);
2030 }
2031
2032
2033 /** Fraction cancellation.
2034  *  @param n  numerator
2035  *  @param d  denominator
2036  *  @return cancelled fraction {n, d} as a list */
2037 static ex frac_cancel(const ex &n, const ex &d)
2038 {
2039         ex num = n;
2040         ex den = d;
2041         numeric pre_factor = _num1;
2042
2043 //std::clog << "frac_cancel num = " << num << ", den = " << den << std::endl;
2044
2045         // Handle trivial case where denominator is 1
2046         if (den.is_equal(_ex1))
2047                 return (new lst(num, den))->setflag(status_flags::dynallocated);
2048
2049         // Handle special cases where numerator or denominator is 0
2050         if (num.is_zero())
2051                 return (new lst(num, _ex1))->setflag(status_flags::dynallocated);
2052         if (den.expand().is_zero())
2053                 throw(std::overflow_error("frac_cancel: division by zero in frac_cancel"));
2054
2055         // Bring numerator and denominator to Z[X] by multiplying with
2056         // LCM of all coefficients' denominators
2057         numeric num_lcm = lcm_of_coefficients_denominators(num);
2058         numeric den_lcm = lcm_of_coefficients_denominators(den);
2059         num = multiply_lcm(num, num_lcm);
2060         den = multiply_lcm(den, den_lcm);
2061         pre_factor = den_lcm / num_lcm;
2062
2063         // Cancel GCD from numerator and denominator
2064         ex cnum, cden;
2065         if (gcd(num, den, &cnum, &cden, false) != _ex1) {
2066                 num = cnum;
2067                 den = cden;
2068         }
2069
2070         // Make denominator unit normal (i.e. coefficient of first symbol
2071         // as defined by get_first_symbol() is made positive)
2072         const symbol *x;
2073         if (get_first_symbol(den, x)) {
2074                 GINAC_ASSERT(is_exactly_a<numeric>(den.unit(*x)));
2075                 if (ex_to<numeric>(den.unit(*x)).is_negative()) {
2076                         num *= _ex_1;
2077                         den *= _ex_1;
2078                 }
2079         }
2080
2081         // Return result as list
2082 //std::clog << " returns num = " << num << ", den = " << den << ", pre_factor = " << pre_factor << std::endl;
2083         return (new lst(num * pre_factor.numer(), den * pre_factor.denom()))->setflag(status_flags::dynallocated);
2084 }
2085
2086
2087 /** Implementation of ex::normal() for a sum. It expands terms and performs
2088  *  fractional addition.
2089  *  @see ex::normal */
2090 ex add::normal(lst &sym_lst, lst &repl_lst, int level) const
2091 {
2092         if (level == 1)
2093                 return (new lst(replace_with_symbol(*this, sym_lst, repl_lst), _ex1))->setflag(status_flags::dynallocated);
2094         else if (level == -max_recursion_level)
2095                 throw(std::runtime_error("max recursion level reached"));
2096
2097         // Normalize children and split each one into numerator and denominator
2098         exvector nums, dens;
2099         nums.reserve(seq.size()+1);
2100         dens.reserve(seq.size()+1);
2101         epvector::const_iterator it = seq.begin(), itend = seq.end();
2102         while (it != itend) {
2103                 ex n = ex_to<basic>(recombine_pair_to_ex(*it)).normal(sym_lst, repl_lst, level-1);
2104                 nums.push_back(n.op(0));
2105                 dens.push_back(n.op(1));
2106                 it++;
2107         }
2108         ex n = ex_to<numeric>(overall_coeff).normal(sym_lst, repl_lst, level-1);
2109         nums.push_back(n.op(0));
2110         dens.push_back(n.op(1));
2111         GINAC_ASSERT(nums.size() == dens.size());
2112
2113         // Now, nums is a vector of all numerators and dens is a vector of
2114         // all denominators
2115 //std::clog << "add::normal uses " << nums.size() << " summands:\n";
2116
2117         // Add fractions sequentially
2118         exvector::const_iterator num_it = nums.begin(), num_itend = nums.end();
2119         exvector::const_iterator den_it = dens.begin(), den_itend = dens.end();
2120 //std::clog << " num = " << *num_it << ", den = " << *den_it << std::endl;
2121         ex num = *num_it++, den = *den_it++;
2122         while (num_it != num_itend) {
2123 //std::clog << " num = " << *num_it << ", den = " << *den_it << std::endl;
2124                 ex next_num = *num_it++, next_den = *den_it++;
2125
2126                 // Trivially add sequences of fractions with identical denominators
2127                 while ((den_it != den_itend) && next_den.is_equal(*den_it)) {
2128                         next_num += *num_it;
2129                         num_it++; den_it++;
2130                 }
2131
2132                 // Additiion of two fractions, taking advantage of the fact that
2133                 // the heuristic GCD algorithm computes the cofactors at no extra cost
2134                 ex co_den1, co_den2;
2135                 ex g = gcd(den, next_den, &co_den1, &co_den2, false);
2136                 num = ((num * co_den2) + (next_num * co_den1)).expand();
2137                 den *= co_den2;         // this is the lcm(den, next_den)
2138         }
2139 //std::clog << " common denominator = " << den << std::endl;
2140
2141         // Cancel common factors from num/den
2142         return frac_cancel(num, den);
2143 }
2144
2145
2146 /** Implementation of ex::normal() for a product. It cancels common factors
2147  *  from fractions.
2148  *  @see ex::normal() */
2149 ex mul::normal(lst &sym_lst, lst &repl_lst, int level) const
2150 {
2151         if (level == 1)
2152                 return (new lst(replace_with_symbol(*this, sym_lst, repl_lst), _ex1))->setflag(status_flags::dynallocated);
2153         else if (level == -max_recursion_level)
2154                 throw(std::runtime_error("max recursion level reached"));
2155
2156         // Normalize children, separate into numerator and denominator
2157         exvector num; num.reserve(seq.size());
2158         exvector den; den.reserve(seq.size());
2159         ex n;
2160         epvector::const_iterator it = seq.begin(), itend = seq.end();
2161         while (it != itend) {
2162                 n = ex_to<basic>(recombine_pair_to_ex(*it)).normal(sym_lst, repl_lst, level-1);
2163                 num.push_back(n.op(0));
2164                 den.push_back(n.op(1));
2165                 it++;
2166         }
2167         n = ex_to<numeric>(overall_coeff).normal(sym_lst, repl_lst, level-1);
2168         num.push_back(n.op(0));
2169         den.push_back(n.op(1));
2170
2171         // Perform fraction cancellation
2172         return frac_cancel((new mul(num))->setflag(status_flags::dynallocated),
2173                            (new mul(den))->setflag(status_flags::dynallocated));
2174 }
2175
2176
2177 /** Implementation of ex::normal() for powers. It normalizes the basis,
2178  *  distributes integer exponents to numerator and denominator, and replaces
2179  *  non-integer powers by temporary symbols.
2180  *  @see ex::normal */
2181 ex power::normal(lst &sym_lst, lst &repl_lst, int level) const
2182 {
2183         if (level == 1)
2184                 return (new lst(replace_with_symbol(*this, sym_lst, repl_lst), _ex1))->setflag(status_flags::dynallocated);
2185         else if (level == -max_recursion_level)
2186                 throw(std::runtime_error("max recursion level reached"));
2187
2188         // Normalize basis and exponent (exponent gets reassembled)
2189         ex n_basis = ex_to<basic>(basis).normal(sym_lst, repl_lst, level-1);
2190         ex n_exponent = ex_to<basic>(exponent).normal(sym_lst, repl_lst, level-1);
2191         n_exponent = n_exponent.op(0) / n_exponent.op(1);
2192
2193         if (n_exponent.info(info_flags::integer)) {
2194
2195                 if (n_exponent.info(info_flags::positive)) {
2196
2197                         // (a/b)^n -> {a^n, b^n}
2198                         return (new lst(power(n_basis.op(0), n_exponent), power(n_basis.op(1), n_exponent)))->setflag(status_flags::dynallocated);
2199
2200                 } else if (n_exponent.info(info_flags::negative)) {
2201
2202                         // (a/b)^-n -> {b^n, a^n}
2203                         return (new lst(power(n_basis.op(1), -n_exponent), power(n_basis.op(0), -n_exponent)))->setflag(status_flags::dynallocated);
2204                 }
2205
2206         } else {
2207
2208                 if (n_exponent.info(info_flags::positive)) {
2209
2210                         // (a/b)^x -> {sym((a/b)^x), 1}
2211                         return (new lst(replace_with_symbol(power(n_basis.op(0) / n_basis.op(1), n_exponent), sym_lst, repl_lst), _ex1))->setflag(status_flags::dynallocated);
2212
2213                 } else if (n_exponent.info(info_flags::negative)) {
2214
2215                         if (n_basis.op(1).is_equal(_ex1)) {
2216
2217                                 // a^-x -> {1, sym(a^x)}
2218                                 return (new lst(_ex1, replace_with_symbol(power(n_basis.op(0), -n_exponent), sym_lst, repl_lst)))->setflag(status_flags::dynallocated);
2219
2220                         } else {
2221
2222                                 // (a/b)^-x -> {sym((b/a)^x), 1}
2223                                 return (new lst(replace_with_symbol(power(n_basis.op(1) / n_basis.op(0), -n_exponent), sym_lst, repl_lst), _ex1))->setflag(status_flags::dynallocated);
2224                         }
2225
2226                 } else {        // n_exponent not numeric
2227
2228                         // (a/b)^x -> {sym((a/b)^x, 1}
2229                         return (new lst(replace_with_symbol(power(n_basis.op(0) / n_basis.op(1), n_exponent), sym_lst, repl_lst), _ex1))->setflag(status_flags::dynallocated);
2230                 }
2231         }
2232 }
2233
2234
2235 /** Implementation of ex::normal() for pseries. It normalizes each coefficient
2236  *  and replaces the series by a temporary symbol.
2237  *  @see ex::normal */
2238 ex pseries::normal(lst &sym_lst, lst &repl_lst, int level) const
2239 {
2240         epvector newseq;
2241         epvector::const_iterator i = seq.begin(), end = seq.end();
2242         while (i != end) {
2243                 ex restexp = i->rest.normal();
2244                 if (!restexp.is_zero())
2245                         newseq.push_back(expair(restexp, i->coeff));
2246                 ++i;
2247         }
2248         ex n = pseries(relational(var,point), newseq);
2249         return (new lst(replace_with_symbol(n, sym_lst, repl_lst), _ex1))->setflag(status_flags::dynallocated);
2250 }
2251
2252
2253 /** Normalization of rational functions.
2254  *  This function converts an expression to its normal form
2255  *  "numerator/denominator", where numerator and denominator are (relatively
2256  *  prime) polynomials. Any subexpressions which are not rational functions
2257  *  (like non-rational numbers, non-integer powers or functions like sin(),
2258  *  cos() etc.) are replaced by temporary symbols which are re-substituted by
2259  *  the (normalized) subexpressions before normal() returns (this way, any
2260  *  expression can be treated as a rational function). normal() is applied
2261  *  recursively to arguments of functions etc.
2262  *
2263  *  @param level maximum depth of recursion
2264  *  @return normalized expression */
2265 ex ex::normal(int level) const
2266 {
2267         lst sym_lst, repl_lst;
2268
2269         ex e = bp->normal(sym_lst, repl_lst, level);
2270         GINAC_ASSERT(is_a<lst>(e));
2271
2272         // Re-insert replaced symbols
2273         if (sym_lst.nops() > 0)
2274                 e = e.subs(sym_lst, repl_lst);
2275
2276         // Convert {numerator, denominator} form back to fraction
2277         return e.op(0) / e.op(1);
2278 }
2279
2280 /** Get numerator of an expression. If the expression is not of the normal
2281  *  form "numerator/denominator", it is first converted to this form and
2282  *  then the numerator is returned.
2283  *
2284  *  @see ex::normal
2285  *  @return numerator */
2286 ex ex::numer(void) const
2287 {
2288         lst sym_lst, repl_lst;
2289
2290         ex e = bp->normal(sym_lst, repl_lst, 0);
2291         GINAC_ASSERT(is_a<lst>(e));
2292
2293         // Re-insert replaced symbols
2294         if (sym_lst.nops() > 0)
2295                 return e.op(0).subs(sym_lst, repl_lst);
2296         else
2297                 return e.op(0);
2298 }
2299
2300 /** Get denominator of an expression. If the expression is not of the normal
2301  *  form "numerator/denominator", it is first converted to this form and
2302  *  then the denominator is returned.
2303  *
2304  *  @see ex::normal
2305  *  @return denominator */
2306 ex ex::denom(void) const
2307 {
2308         lst sym_lst, repl_lst;
2309
2310         ex e = bp->normal(sym_lst, repl_lst, 0);
2311         GINAC_ASSERT(is_a<lst>(e));
2312
2313         // Re-insert replaced symbols
2314         if (sym_lst.nops() > 0)
2315                 return e.op(1).subs(sym_lst, repl_lst);
2316         else
2317                 return e.op(1);
2318 }
2319
2320 /** Get numerator and denominator of an expression. If the expresison is not
2321  *  of the normal form "numerator/denominator", it is first converted to this
2322  *  form and then a list [numerator, denominator] is returned.
2323  *
2324  *  @see ex::normal
2325  *  @return a list [numerator, denominator] */
2326 ex ex::numer_denom(void) const
2327 {
2328         lst sym_lst, repl_lst;
2329
2330         ex e = bp->normal(sym_lst, repl_lst, 0);
2331         GINAC_ASSERT(is_a<lst>(e));
2332
2333         // Re-insert replaced symbols
2334         if (sym_lst.nops() > 0)
2335                 return e.subs(sym_lst, repl_lst);
2336         else
2337                 return e;
2338 }
2339
2340
2341 /** Rationalization of non-rational functions.
2342  *  This function converts a general expression to a rational polynomial
2343  *  by replacing all non-rational subexpressions (like non-rational numbers,
2344  *  non-integer powers or functions like sin(), cos() etc.) to temporary
2345  *  symbols. This makes it possible to use functions like gcd() and divide()
2346  *  on non-rational functions by applying to_rational() on the arguments,
2347  *  calling the desired function and re-substituting the temporary symbols
2348  *  in the result. To make the last step possible, all temporary symbols and
2349  *  their associated expressions are collected in the list specified by the
2350  *  repl_lst parameter in the form {symbol == expression}, ready to be passed
2351  *  as an argument to ex::subs().
2352  *
2353  *  @param repl_lst collects a list of all temporary symbols and their replacements
2354  *  @return rationalized expression */
2355 ex basic::to_rational(lst &repl_lst) const
2356 {
2357         return replace_with_symbol(*this, repl_lst);
2358 }
2359
2360
2361 /** Implementation of ex::to_rational() for symbols. This returns the
2362  *  unmodified symbol. */
2363 ex symbol::to_rational(lst &repl_lst) const
2364 {
2365         return *this;
2366 }
2367
2368
2369 /** Implementation of ex::to_rational() for a numeric. It splits complex
2370  *  numbers into re+I*im and replaces I and non-rational real numbers with a
2371  *  temporary symbol. */
2372 ex numeric::to_rational(lst &repl_lst) const
2373 {
2374         if (is_real()) {
2375                 if (!is_rational())
2376                         return replace_with_symbol(*this, repl_lst);
2377         } else { // complex
2378                 numeric re = real();
2379                 numeric im = imag();
2380                 ex re_ex = re.is_rational() ? re : replace_with_symbol(re, repl_lst);
2381                 ex im_ex = im.is_rational() ? im : replace_with_symbol(im, repl_lst);
2382                 return re_ex + im_ex * replace_with_symbol(I, repl_lst);
2383         }
2384         return *this;
2385 }
2386
2387
2388 /** Implementation of ex::to_rational() for powers. It replaces non-integer
2389  *  powers by temporary symbols. */
2390 ex power::to_rational(lst &repl_lst) const
2391 {
2392         if (exponent.info(info_flags::integer))
2393                 return power(basis.to_rational(repl_lst), exponent);
2394         else
2395                 return replace_with_symbol(*this, repl_lst);
2396 }
2397
2398
2399 /** Implementation of ex::to_rational() for expairseqs. */
2400 ex expairseq::to_rational(lst &repl_lst) const
2401 {
2402         epvector s;
2403         s.reserve(seq.size());
2404         epvector::const_iterator i = seq.begin(), end = seq.end();
2405         while (i != end) {
2406                 s.push_back(split_ex_to_pair(recombine_pair_to_ex(*i).to_rational(repl_lst)));
2407                 ++i;
2408         }
2409         ex oc = overall_coeff.to_rational(repl_lst);
2410         if (oc.info(info_flags::numeric))
2411                 return thisexpairseq(s, overall_coeff);
2412         else
2413                 s.push_back(combine_ex_with_coeff_to_pair(oc, _ex1));
2414         return thisexpairseq(s, default_overall_coeff());
2415 }
2416
2417
2418 /** Remove the common factor in the terms of a sum 'e' by calculating the GCD,
2419  *  and multiply it into the expression 'factor' (which needs to be initialized
2420  *  to 1, unless you're accumulating factors). */
2421 static ex find_common_factor(const ex & e, ex & factor, lst & repl)
2422 {
2423         if (is_a<add>(e)) {
2424
2425                 unsigned num = e.nops();
2426                 exvector terms; terms.reserve(num);
2427                 ex gc;
2428
2429                 // Find the common GCD
2430                 for (unsigned i=0; i<num; i++) {
2431                         ex x = e.op(i).to_rational(repl);
2432
2433                         if (is_a<add>(x) || is_a<mul>(x)) {
2434                                 ex f = 1;
2435                                 x = find_common_factor(x, f, repl);
2436                                 x *= f;
2437                         }
2438
2439                         if (i == 0)
2440                                 gc = x;
2441                         else
2442                                 gc = gcd(gc, x);
2443
2444                         terms.push_back(x);
2445                 }
2446
2447                 if (gc.is_equal(_ex1))
2448                         return e;
2449
2450                 // The GCD is the factor we pull out
2451                 factor *= gc;
2452
2453                 // Now divide all terms by the GCD
2454                 for (unsigned i=0; i<num; i++) {
2455                         ex x;
2456
2457                         // Try to avoid divide() because it expands the polynomial
2458                         ex &t = terms[i];
2459                         if (is_a<mul>(t)) {
2460                                 for (unsigned j=0; j<t.nops(); j++) {
2461                                         if (t.op(j).is_equal(gc)) {
2462                                                 exvector v; v.reserve(t.nops());
2463                                                 for (unsigned k=0; k<t.nops(); k++) {
2464                                                         if (k == j)
2465                                                                 v.push_back(_ex1);
2466                                                         else
2467                                                                 v.push_back(t.op(k));
2468                                                 }
2469                                                 t = (new mul(v))->setflag(status_flags::dynallocated);
2470                                                 goto term_done;
2471                                         }
2472                                 }
2473                         }
2474
2475                         divide(t, gc, x);
2476                         t = x;
2477 term_done:      ;
2478                 }
2479                 return (new add(terms))->setflag(status_flags::dynallocated);
2480
2481         } else if (is_a<mul>(e)) {
2482
2483                 unsigned num = e.nops();
2484                 exvector v; v.reserve(num);
2485
2486                 for (unsigned i=0; i<num; i++)
2487                         v.push_back(find_common_factor(e.op(i), factor, repl));
2488
2489                 return (new mul(v))->setflag(status_flags::dynallocated);
2490
2491         } else if (is_a<power>(e)) {
2492
2493                 ex x = e.to_rational(repl);
2494                 if (is_a<power>(x) && x.op(1).info(info_flags::negative))
2495                         return replace_with_symbol(x, repl);
2496                 else
2497                         return x;
2498
2499         } else
2500                 return e;
2501 }
2502
2503
2504 /** Collect common factors in sums. This converts expressions like
2505  *  'a*(b*x+b*y)' to 'a*b*(x+y)'. */
2506 ex collect_common_factors(const ex & e)
2507 {
2508         if (is_a<add>(e) || is_a<mul>(e)) {
2509
2510                 lst repl;
2511                 ex factor = 1;
2512                 ex r = find_common_factor(e, factor, repl);
2513                 return factor.subs(repl) * r.subs(repl);
2514
2515         } else
2516                 return e;
2517 }
2518
2519
2520 } // namespace GiNaC