]> www.ginac.de Git - ginac.git/blob - ginac/normal.cpp
67091f5003aef503359fdee4814f3c4e07d504be
[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 /** Compute a square-free factorization of a multivariate polynomial in Q[X].
1745  *
1746  *  @param a  multivariate polynomial over Q[X]
1747  *  @param x  lst of variables to factor in, may be left empty for autodetection
1748  *  @return   a square-free factorization of \p a.
1749  *
1750  * \note
1751  * A polynomial \f$p(X) \in C[X]\f$ is said <EM>square-free</EM>
1752  * if, whenever any two polynomials \f$q(X)\f$ and \f$r(X)\f$
1753  * are such that
1754  * \f[
1755  *     p(X) = q(X)^2 r(X),
1756  * \f]
1757  * we have \f$q(X) \in C\f$.
1758  * This means that \f$p(X)\f$ has no repeated factors, apart
1759  * eventually from constants.
1760  * Given a polynomial \f$p(X) \in C[X]\f$, we say that the
1761  * decomposition
1762  * \f[
1763  *   p(X) = b \cdot p_1(X)^{a_1} \cdot p_2(X)^{a_2} \cdots p_r(X)^{a_r}
1764  * \f]
1765  * is a <EM>square-free factorization</EM> of \f$p(X)\f$ if the
1766  * following conditions hold:
1767  * -#  \f$b \in C\f$ and \f$b \neq 0\f$;
1768  * -#  \f$a_i\f$ is a positive integer for \f$i = 1, \ldots, r\f$;
1769  * -#  the degree of the polynomial \f$p_i\f$ is strictly positive
1770  *     for \f$i = 1, \ldots, r\f$;
1771  * -#  the polynomial \f$\Pi_{i=1}^r p_i(X)\f$ is square-free.
1772  *
1773  * Square-free factorizations need not be unique.  For example, if
1774  * \f$a_i\f$ is even, we could change the polynomial \f$p_i(X)\f$
1775  * into \f$-p_i(X)\f$.
1776  * Observe also that the factors \f$p_i(X)\f$ need not be irreducible
1777  * polynomials.
1778  */
1779 ex sqrfree(const ex &a, const lst &l)
1780 {
1781         if (is_a<numeric>(a) ||     // algorithm does not trap a==0
1782             is_a<symbol>(a))        // shortcut
1783                 return a;
1784
1785         // If no lst of variables to factorize in was specified we have to
1786         // invent one now.  Maybe one can optimize here by reversing the order
1787         // or so, I don't know.
1788         lst args;
1789         if (l.nops()==0) {
1790                 sym_desc_vec sdv;
1791                 get_symbol_stats(a, _ex0, sdv);
1792                 sym_desc_vec::const_iterator it = sdv.begin(), itend = sdv.end();
1793                 while (it != itend) {
1794                         args.append(*it->sym);
1795                         ++it;
1796                 }
1797         } else {
1798                 args = l;
1799         }
1800
1801         // Find the symbol to factor in at this stage
1802         if (!is_ex_of_type(args.op(0), symbol))
1803                 throw (std::runtime_error("sqrfree(): invalid factorization variable"));
1804         const symbol &x = ex_to<symbol>(args.op(0));
1805
1806         // convert the argument from something in Q[X] to something in Z[X]
1807         const numeric lcm = lcm_of_coefficients_denominators(a);
1808         const ex tmp = multiply_lcm(a,lcm);
1809
1810         // find the factors
1811         exvector factors = sqrfree_yun(tmp,x);
1812
1813         // construct the next list of symbols with the first element popped
1814         lst newargs = args;
1815         newargs.remove_first();
1816
1817         // recurse down the factors in remaining variables
1818         if (newargs.nops()>0) {
1819                 exvector::iterator i = factors.begin();
1820                 while (i != factors.end()) {
1821                         *i = sqrfree(*i, newargs);
1822                         ++i;
1823                 }
1824         }
1825
1826         // Done with recursion, now construct the final result
1827         ex result = _ex1;
1828         exvector::const_iterator it = factors.begin(), itend = factors.end();
1829         for (int p = 1; it!=itend; ++it, ++p)
1830                 result *= power(*it, p);
1831
1832         // Yun's algorithm does not account for constant factors.  (For univariate
1833         // polynomials it works only in the monic case.)  We can correct this by
1834         // inserting what has been lost back into the result.  For completeness
1835         // we'll also have to recurse down that factor in the remaining variables.
1836         if (newargs.nops()>0)
1837                 result *= sqrfree(quo(tmp, result, x), newargs);
1838         else
1839                 result *= quo(tmp, result, x);
1840
1841         // Put in the reational overall factor again and return
1842         return result * lcm.inverse();
1843 }
1844
1845 /** Compute square-free partial fraction decomposition of rational function
1846  *  a(x).
1847  *
1848  *  @param a rational function over Z[x], treated as univariate polynomial
1849  *           in x
1850  *  @param x variable to factor in
1851  *  @return decomposed rational function */
1852 ex sqrfree_parfrac(const ex & a, const symbol & x)
1853 {
1854         // Find numerator and denominator
1855         ex nd = numer_denom(a);
1856         ex numer = nd.op(0), denom = nd.op(1);
1857 //clog << "numer = " << numer << ", denom = " << denom << endl;
1858
1859         // Convert N(x)/D(x) -> Q(x) + R(x)/D(x), so degree(R) < degree(D)
1860         ex red_poly = quo(numer, denom, x), red_numer = rem(numer, denom, x).expand();
1861 //clog << "red_poly = " << red_poly << ", red_numer = " << red_numer << endl;
1862
1863         // Factorize denominator and compute cofactors
1864         exvector yun = sqrfree_yun(denom, x);
1865 //clog << "yun factors: " << exprseq(yun) << endl;
1866         unsigned num_yun = yun.size();
1867         exvector factor; factor.reserve(num_yun);
1868         exvector cofac; cofac.reserve(num_yun);
1869         for (unsigned i=0; i<num_yun; i++) {
1870                 if (!yun[i].is_equal(_ex1)) {
1871                         for (unsigned j=0; j<=i; j++) {
1872                                 factor.push_back(pow(yun[i], j+1));
1873                                 ex prod = _ex1;
1874                                 for (unsigned k=0; k<num_yun; k++) {
1875                                         if (k == i)
1876                                                 prod *= pow(yun[k], i-j);
1877                                         else
1878                                                 prod *= pow(yun[k], k+1);
1879                                 }
1880                                 cofac.push_back(prod.expand());
1881                         }
1882                 }
1883         }
1884         unsigned num_factors = factor.size();
1885 //clog << "factors  : " << exprseq(factor) << endl;
1886 //clog << "cofactors: " << exprseq(cofac) << endl;
1887
1888         // Construct coefficient matrix for decomposition
1889         int max_denom_deg = denom.degree(x);
1890         matrix sys(max_denom_deg + 1, num_factors);
1891         matrix rhs(max_denom_deg + 1, 1);
1892         for (int i=0; i<=max_denom_deg; i++) {
1893                 for (unsigned j=0; j<num_factors; j++)
1894                         sys(i, j) = cofac[j].coeff(x, i);
1895                 rhs(i, 0) = red_numer.coeff(x, i);
1896         }
1897 //clog << "coeffs: " << sys << endl;
1898 //clog << "rhs   : " << rhs << endl;
1899
1900         // Solve resulting linear system
1901         matrix vars(num_factors, 1);
1902         for (unsigned i=0; i<num_factors; i++)
1903                 vars(i, 0) = symbol();
1904         matrix sol = sys.solve(vars, rhs);
1905
1906         // Sum up decomposed fractions
1907         ex sum = 0;
1908         for (unsigned i=0; i<num_factors; i++)
1909                 sum += sol(i, 0) / factor[i];
1910
1911         return red_poly + sum;
1912 }
1913
1914
1915 /** Remove the common factor in the terms of a sum 'e' by calculating the GCD,
1916  *  and multiply it into the expression 'factor' (which needs to be initialized
1917  *  to 1, unless you're accumulating factors). */
1918 static ex find_common_factor(const ex & e, ex & factor)
1919 {
1920         if (is_a<add>(e)) {
1921
1922                 unsigned num = e.nops();
1923                 exvector terms; terms.reserve(num);
1924                 lst repl;
1925                 ex gc;
1926
1927                 // Find the common GCD
1928                 for (unsigned i=0; i<num; i++) {
1929                         ex x = e.op(i).to_rational(repl);
1930                         if (is_a<add>(x) || is_a<mul>(x)) {
1931                                 ex f = 1;
1932                                 x = find_common_factor(x, f);
1933                                 x *= f;
1934                         }
1935
1936                         if (i == 0)
1937                                 gc = x;
1938                         else
1939                                 gc = gcd(gc, x);
1940
1941                         terms.push_back(x);
1942                 }
1943
1944                 if (gc.is_equal(_ex1))
1945                         return e;
1946
1947                 // The GCD is the factor we pull out
1948                 factor *= gc.subs(repl);
1949
1950                 // Now divide all terms by the GCD
1951                 for (unsigned i=0; i<num; i++) {
1952                         ex x;
1953
1954                         // Try to avoid divide() because it expands the polynomial
1955                         ex &t = terms[i];
1956                         if (is_a<mul>(t)) {
1957                                 for (unsigned j=0; j<t.nops(); j++) {
1958                                         if (t.op(j).is_equal(gc)) {
1959                                                 exvector v; v.reserve(t.nops());
1960                                                 for (unsigned k=0; k<t.nops(); k++) {
1961                                                         if (k == j)
1962                                                                 v.push_back(_ex1);
1963                                                         else
1964                                                                 v.push_back(t.op(k));
1965                                                 }
1966                                                 t = (new mul(v))->setflag(status_flags::dynallocated).subs(repl);
1967                                                 goto term_done;
1968                                         }
1969                                 }
1970                         }
1971
1972                         divide(t, gc, x);
1973                         t = x.subs(repl);
1974 term_done:      ;
1975                 }
1976                 return (new add(terms))->setflag(status_flags::dynallocated);
1977
1978         } else if (is_a<mul>(e)) {
1979
1980                 exvector v;
1981                 for (unsigned i=0; i<e.nops(); i++)
1982                         v.push_back(find_common_factor(e.op(i), factor));
1983                 return (new mul(v))->setflag(status_flags::dynallocated);
1984
1985         } else
1986                 return e;
1987 }
1988
1989
1990 /** Collect common factors in sums. This converts expressions like
1991  *  'a*(b*x+b*y)' to 'a*b*(x+y)'. */
1992 ex collect_common_factors(const ex & e)
1993 {
1994         if (is_a<add>(e) || is_a<mul>(e)) {
1995
1996                 ex factor = 1;
1997                 ex r = find_common_factor(e, factor);
1998                 return factor * r;
1999
2000         } else
2001                 return e;
2002 }
2003
2004
2005 /*
2006  *  Normal form of rational functions
2007  */
2008
2009 /*
2010  *  Note: The internal normal() functions (= basic::normal() and overloaded
2011  *  functions) all return lists of the form {numerator, denominator}. This
2012  *  is to get around mul::eval()'s automatic expansion of numeric coefficients.
2013  *  E.g. (a+b)/3 is automatically converted to a/3+b/3 but we want to keep
2014  *  the information that (a+b) is the numerator and 3 is the denominator.
2015  */
2016
2017
2018 /** Create a symbol for replacing the expression "e" (or return a previously
2019  *  assigned symbol). The symbol is appended to sym_lst and returned, the
2020  *  expression is appended to repl_lst.
2021  *  @see ex::normal */
2022 static ex replace_with_symbol(const ex &e, lst &sym_lst, lst &repl_lst)
2023 {
2024         // Expression already in repl_lst? Then return the assigned symbol
2025         for (unsigned i=0; i<repl_lst.nops(); i++)
2026                 if (repl_lst.op(i).is_equal(e))
2027                         return sym_lst.op(i);
2028         
2029         // Otherwise create new symbol and add to list, taking care that the
2030         // replacement expression doesn't contain symbols from the sym_lst
2031         // because subs() is not recursive
2032         symbol s;
2033         ex es(s);
2034         ex e_replaced = e.subs(sym_lst, repl_lst);
2035         sym_lst.append(es);
2036         repl_lst.append(e_replaced);
2037         return es;
2038 }
2039
2040 /** Create a symbol for replacing the expression "e" (or return a previously
2041  *  assigned symbol). An expression of the form "symbol == expression" is added
2042  *  to repl_lst and the symbol is returned.
2043  *  @see basic::to_rational */
2044 static ex replace_with_symbol(const ex &e, lst &repl_lst)
2045 {
2046         // Expression already in repl_lst? Then return the assigned symbol
2047         for (unsigned i=0; i<repl_lst.nops(); i++)
2048                 if (repl_lst.op(i).op(1).is_equal(e))
2049                         return repl_lst.op(i).op(0);
2050         
2051         // Otherwise create new symbol and add to list, taking care that the
2052         // replacement expression doesn't contain symbols from the sym_lst
2053         // because subs() is not recursive
2054         symbol s;
2055         ex es(s);
2056         ex e_replaced = e.subs(repl_lst);
2057         repl_lst.append(es == e_replaced);
2058         return es;
2059 }
2060
2061
2062 /** Function object to be applied by basic::normal(). */
2063 struct normal_map_function : public map_function {
2064         int level;
2065         normal_map_function(int l) : level(l) {}
2066         ex operator()(const ex & e) { return normal(e, level); }
2067 };
2068
2069 /** Default implementation of ex::normal(). It normalizes the children and
2070  *  replaces the object with a temporary symbol.
2071  *  @see ex::normal */
2072 ex basic::normal(lst &sym_lst, lst &repl_lst, int level) const
2073 {
2074         if (nops() == 0)
2075                 return (new lst(replace_with_symbol(*this, sym_lst, repl_lst), _ex1))->setflag(status_flags::dynallocated);
2076         else {
2077                 if (level == 1)
2078                         return (new lst(replace_with_symbol(*this, sym_lst, repl_lst), _ex1))->setflag(status_flags::dynallocated);
2079                 else if (level == -max_recursion_level)
2080                         throw(std::runtime_error("max recursion level reached"));
2081                 else {
2082                         normal_map_function map_normal(level - 1);
2083                         return (new lst(replace_with_symbol(map(map_normal), sym_lst, repl_lst), _ex1))->setflag(status_flags::dynallocated);
2084                 }
2085         }
2086 }
2087
2088
2089 /** Implementation of ex::normal() for symbols. This returns the unmodified symbol.
2090  *  @see ex::normal */
2091 ex symbol::normal(lst &sym_lst, lst &repl_lst, int level) const
2092 {
2093         return (new lst(*this, _ex1))->setflag(status_flags::dynallocated);
2094 }
2095
2096
2097 /** Implementation of ex::normal() for a numeric. It splits complex numbers
2098  *  into re+I*im and replaces I and non-rational real numbers with a temporary
2099  *  symbol.
2100  *  @see ex::normal */
2101 ex numeric::normal(lst &sym_lst, lst &repl_lst, int level) const
2102 {
2103         numeric num = numer();
2104         ex numex = num;
2105
2106         if (num.is_real()) {
2107                 if (!num.is_integer())
2108                         numex = replace_with_symbol(numex, sym_lst, repl_lst);
2109         } else { // complex
2110                 numeric re = num.real(), im = num.imag();
2111                 ex re_ex = re.is_rational() ? re : replace_with_symbol(re, sym_lst, repl_lst);
2112                 ex im_ex = im.is_rational() ? im : replace_with_symbol(im, sym_lst, repl_lst);
2113                 numex = re_ex + im_ex * replace_with_symbol(I, sym_lst, repl_lst);
2114         }
2115
2116         // Denominator is always a real integer (see numeric::denom())
2117         return (new lst(numex, denom()))->setflag(status_flags::dynallocated);
2118 }
2119
2120
2121 /** Fraction cancellation.
2122  *  @param n  numerator
2123  *  @param d  denominator
2124  *  @return cancelled fraction {n, d} as a list */
2125 static ex frac_cancel(const ex &n, const ex &d)
2126 {
2127         ex num = n;
2128         ex den = d;
2129         numeric pre_factor = _num1;
2130
2131 //std::clog << "frac_cancel num = " << num << ", den = " << den << std::endl;
2132
2133         // Handle trivial case where denominator is 1
2134         if (den.is_equal(_ex1))
2135                 return (new lst(num, den))->setflag(status_flags::dynallocated);
2136
2137         // Handle special cases where numerator or denominator is 0
2138         if (num.is_zero())
2139                 return (new lst(num, _ex1))->setflag(status_flags::dynallocated);
2140         if (den.expand().is_zero())
2141                 throw(std::overflow_error("frac_cancel: division by zero in frac_cancel"));
2142
2143         // Bring numerator and denominator to Z[X] by multiplying with
2144         // LCM of all coefficients' denominators
2145         numeric num_lcm = lcm_of_coefficients_denominators(num);
2146         numeric den_lcm = lcm_of_coefficients_denominators(den);
2147         num = multiply_lcm(num, num_lcm);
2148         den = multiply_lcm(den, den_lcm);
2149         pre_factor = den_lcm / num_lcm;
2150
2151         // Cancel GCD from numerator and denominator
2152         ex cnum, cden;
2153         if (gcd(num, den, &cnum, &cden, false) != _ex1) {
2154                 num = cnum;
2155                 den = cden;
2156         }
2157
2158         // Make denominator unit normal (i.e. coefficient of first symbol
2159         // as defined by get_first_symbol() is made positive)
2160         const symbol *x;
2161         if (get_first_symbol(den, x)) {
2162                 GINAC_ASSERT(is_exactly_a<numeric>(den.unit(*x)));
2163                 if (ex_to<numeric>(den.unit(*x)).is_negative()) {
2164                         num *= _ex_1;
2165                         den *= _ex_1;
2166                 }
2167         }
2168
2169         // Return result as list
2170 //std::clog << " returns num = " << num << ", den = " << den << ", pre_factor = " << pre_factor << std::endl;
2171         return (new lst(num * pre_factor.numer(), den * pre_factor.denom()))->setflag(status_flags::dynallocated);
2172 }
2173
2174
2175 /** Implementation of ex::normal() for a sum. It expands terms and performs
2176  *  fractional addition.
2177  *  @see ex::normal */
2178 ex add::normal(lst &sym_lst, lst &repl_lst, int level) const
2179 {
2180         if (level == 1)
2181                 return (new lst(replace_with_symbol(*this, sym_lst, repl_lst), _ex1))->setflag(status_flags::dynallocated);
2182         else if (level == -max_recursion_level)
2183                 throw(std::runtime_error("max recursion level reached"));
2184
2185         // Normalize children and split each one into numerator and denominator
2186         exvector nums, dens;
2187         nums.reserve(seq.size()+1);
2188         dens.reserve(seq.size()+1);
2189         epvector::const_iterator it = seq.begin(), itend = seq.end();
2190         while (it != itend) {
2191                 ex n = ex_to<basic>(recombine_pair_to_ex(*it)).normal(sym_lst, repl_lst, level-1);
2192                 nums.push_back(n.op(0));
2193                 dens.push_back(n.op(1));
2194                 it++;
2195         }
2196         ex n = ex_to<numeric>(overall_coeff).normal(sym_lst, repl_lst, level-1);
2197         nums.push_back(n.op(0));
2198         dens.push_back(n.op(1));
2199         GINAC_ASSERT(nums.size() == dens.size());
2200
2201         // Now, nums is a vector of all numerators and dens is a vector of
2202         // all denominators
2203 //std::clog << "add::normal uses " << nums.size() << " summands:\n";
2204
2205         // Add fractions sequentially
2206         exvector::const_iterator num_it = nums.begin(), num_itend = nums.end();
2207         exvector::const_iterator den_it = dens.begin(), den_itend = dens.end();
2208 //std::clog << " num = " << *num_it << ", den = " << *den_it << std::endl;
2209         ex num = *num_it++, den = *den_it++;
2210         while (num_it != num_itend) {
2211 //std::clog << " num = " << *num_it << ", den = " << *den_it << std::endl;
2212                 ex next_num = *num_it++, next_den = *den_it++;
2213
2214                 // Trivially add sequences of fractions with identical denominators
2215                 while ((den_it != den_itend) && next_den.is_equal(*den_it)) {
2216                         next_num += *num_it;
2217                         num_it++; den_it++;
2218                 }
2219
2220                 // Additiion of two fractions, taking advantage of the fact that
2221                 // the heuristic GCD algorithm computes the cofactors at no extra cost
2222                 ex co_den1, co_den2;
2223                 ex g = gcd(den, next_den, &co_den1, &co_den2, false);
2224                 num = ((num * co_den2) + (next_num * co_den1)).expand();
2225                 den *= co_den2;         // this is the lcm(den, next_den)
2226         }
2227 //std::clog << " common denominator = " << den << std::endl;
2228
2229         // Cancel common factors from num/den
2230         return frac_cancel(num, den);
2231 }
2232
2233
2234 /** Implementation of ex::normal() for a product. It cancels common factors
2235  *  from fractions.
2236  *  @see ex::normal() */
2237 ex mul::normal(lst &sym_lst, lst &repl_lst, int level) const
2238 {
2239         if (level == 1)
2240                 return (new lst(replace_with_symbol(*this, sym_lst, repl_lst), _ex1))->setflag(status_flags::dynallocated);
2241         else if (level == -max_recursion_level)
2242                 throw(std::runtime_error("max recursion level reached"));
2243
2244         // Normalize children, separate into numerator and denominator
2245         exvector num; num.reserve(seq.size());
2246         exvector den; den.reserve(seq.size());
2247         ex n;
2248         epvector::const_iterator it = seq.begin(), itend = seq.end();
2249         while (it != itend) {
2250                 n = ex_to<basic>(recombine_pair_to_ex(*it)).normal(sym_lst, repl_lst, level-1);
2251                 num.push_back(n.op(0));
2252                 den.push_back(n.op(1));
2253                 it++;
2254         }
2255         n = ex_to<numeric>(overall_coeff).normal(sym_lst, repl_lst, level-1);
2256         num.push_back(n.op(0));
2257         den.push_back(n.op(1));
2258
2259         // Perform fraction cancellation
2260         return frac_cancel((new mul(num))->setflag(status_flags::dynallocated),
2261                            (new mul(den))->setflag(status_flags::dynallocated));
2262 }
2263
2264
2265 /** Implementation of ex::normal() for powers. It normalizes the basis,
2266  *  distributes integer exponents to numerator and denominator, and replaces
2267  *  non-integer powers by temporary symbols.
2268  *  @see ex::normal */
2269 ex power::normal(lst &sym_lst, lst &repl_lst, int level) const
2270 {
2271         if (level == 1)
2272                 return (new lst(replace_with_symbol(*this, sym_lst, repl_lst), _ex1))->setflag(status_flags::dynallocated);
2273         else if (level == -max_recursion_level)
2274                 throw(std::runtime_error("max recursion level reached"));
2275
2276         // Normalize basis and exponent (exponent gets reassembled)
2277         ex n_basis = ex_to<basic>(basis).normal(sym_lst, repl_lst, level-1);
2278         ex n_exponent = ex_to<basic>(exponent).normal(sym_lst, repl_lst, level-1);
2279         n_exponent = n_exponent.op(0) / n_exponent.op(1);
2280
2281         if (n_exponent.info(info_flags::integer)) {
2282
2283                 if (n_exponent.info(info_flags::positive)) {
2284
2285                         // (a/b)^n -> {a^n, b^n}
2286                         return (new lst(power(n_basis.op(0), n_exponent), power(n_basis.op(1), n_exponent)))->setflag(status_flags::dynallocated);
2287
2288                 } else if (n_exponent.info(info_flags::negative)) {
2289
2290                         // (a/b)^-n -> {b^n, a^n}
2291                         return (new lst(power(n_basis.op(1), -n_exponent), power(n_basis.op(0), -n_exponent)))->setflag(status_flags::dynallocated);
2292                 }
2293
2294         } else {
2295
2296                 if (n_exponent.info(info_flags::positive)) {
2297
2298                         // (a/b)^x -> {sym((a/b)^x), 1}
2299                         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);
2300
2301                 } else if (n_exponent.info(info_flags::negative)) {
2302
2303                         if (n_basis.op(1).is_equal(_ex1)) {
2304
2305                                 // a^-x -> {1, sym(a^x)}
2306                                 return (new lst(_ex1, replace_with_symbol(power(n_basis.op(0), -n_exponent), sym_lst, repl_lst)))->setflag(status_flags::dynallocated);
2307
2308                         } else {
2309
2310                                 // (a/b)^-x -> {sym((b/a)^x), 1}
2311                                 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);
2312                         }
2313
2314                 } else {        // n_exponent not numeric
2315
2316                         // (a/b)^x -> {sym((a/b)^x, 1}
2317                         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);
2318                 }
2319         }
2320 }
2321
2322
2323 /** Implementation of ex::normal() for pseries. It normalizes each coefficient
2324  *  and replaces the series by a temporary symbol.
2325  *  @see ex::normal */
2326 ex pseries::normal(lst &sym_lst, lst &repl_lst, int level) const
2327 {
2328         epvector newseq;
2329         epvector::const_iterator i = seq.begin(), end = seq.end();
2330         while (i != end) {
2331                 ex restexp = i->rest.normal();
2332                 if (!restexp.is_zero())
2333                         newseq.push_back(expair(restexp, i->coeff));
2334                 ++i;
2335         }
2336         ex n = pseries(relational(var,point), newseq);
2337         return (new lst(replace_with_symbol(n, sym_lst, repl_lst), _ex1))->setflag(status_flags::dynallocated);
2338 }
2339
2340
2341 /** Normalization of rational functions.
2342  *  This function converts an expression to its normal form
2343  *  "numerator/denominator", where numerator and denominator are (relatively
2344  *  prime) polynomials. Any subexpressions which are not rational functions
2345  *  (like non-rational numbers, non-integer powers or functions like sin(),
2346  *  cos() etc.) are replaced by temporary symbols which are re-substituted by
2347  *  the (normalized) subexpressions before normal() returns (this way, any
2348  *  expression can be treated as a rational function). normal() is applied
2349  *  recursively to arguments of functions etc.
2350  *
2351  *  @param level maximum depth of recursion
2352  *  @return normalized expression */
2353 ex ex::normal(int level) const
2354 {
2355         lst sym_lst, repl_lst;
2356
2357         ex e = bp->normal(sym_lst, repl_lst, level);
2358         GINAC_ASSERT(is_a<lst>(e));
2359
2360         // Re-insert replaced symbols
2361         if (sym_lst.nops() > 0)
2362                 e = e.subs(sym_lst, repl_lst);
2363
2364         // Convert {numerator, denominator} form back to fraction
2365         return e.op(0) / e.op(1);
2366 }
2367
2368 /** Get numerator of an expression. If the expression is not of the normal
2369  *  form "numerator/denominator", it is first converted to this form and
2370  *  then the numerator is returned.
2371  *
2372  *  @see ex::normal
2373  *  @return numerator */
2374 ex ex::numer(void) const
2375 {
2376         lst sym_lst, repl_lst;
2377
2378         ex e = bp->normal(sym_lst, repl_lst, 0);
2379         GINAC_ASSERT(is_a<lst>(e));
2380
2381         // Re-insert replaced symbols
2382         if (sym_lst.nops() > 0)
2383                 return e.op(0).subs(sym_lst, repl_lst);
2384         else
2385                 return e.op(0);
2386 }
2387
2388 /** Get denominator of an expression. If the expression is not of the normal
2389  *  form "numerator/denominator", it is first converted to this form and
2390  *  then the denominator is returned.
2391  *
2392  *  @see ex::normal
2393  *  @return denominator */
2394 ex ex::denom(void) const
2395 {
2396         lst sym_lst, repl_lst;
2397
2398         ex e = bp->normal(sym_lst, repl_lst, 0);
2399         GINAC_ASSERT(is_a<lst>(e));
2400
2401         // Re-insert replaced symbols
2402         if (sym_lst.nops() > 0)
2403                 return e.op(1).subs(sym_lst, repl_lst);
2404         else
2405                 return e.op(1);
2406 }
2407
2408 /** Get numerator and denominator of an expression. If the expresison is not
2409  *  of the normal form "numerator/denominator", it is first converted to this
2410  *  form and then a list [numerator, denominator] is returned.
2411  *
2412  *  @see ex::normal
2413  *  @return a list [numerator, denominator] */
2414 ex ex::numer_denom(void) const
2415 {
2416         lst sym_lst, repl_lst;
2417
2418         ex e = bp->normal(sym_lst, repl_lst, 0);
2419         GINAC_ASSERT(is_a<lst>(e));
2420
2421         // Re-insert replaced symbols
2422         if (sym_lst.nops() > 0)
2423                 return e.subs(sym_lst, repl_lst);
2424         else
2425                 return e;
2426 }
2427
2428
2429 /** Rationalization of non-rational functions.
2430  *  This function converts a general expression to a rational polynomial
2431  *  by replacing all non-rational subexpressions (like non-rational numbers,
2432  *  non-integer powers or functions like sin(), cos() etc.) to temporary
2433  *  symbols. This makes it possible to use functions like gcd() and divide()
2434  *  on non-rational functions by applying to_rational() on the arguments,
2435  *  calling the desired function and re-substituting the temporary symbols
2436  *  in the result. To make the last step possible, all temporary symbols and
2437  *  their associated expressions are collected in the list specified by the
2438  *  repl_lst parameter in the form {symbol == expression}, ready to be passed
2439  *  as an argument to ex::subs().
2440  *
2441  *  @param repl_lst collects a list of all temporary symbols and their replacements
2442  *  @return rationalized expression */
2443 ex basic::to_rational(lst &repl_lst) const
2444 {
2445         return replace_with_symbol(*this, repl_lst);
2446 }
2447
2448
2449 /** Implementation of ex::to_rational() for symbols. This returns the
2450  *  unmodified symbol. */
2451 ex symbol::to_rational(lst &repl_lst) const
2452 {
2453         return *this;
2454 }
2455
2456
2457 /** Implementation of ex::to_rational() for a numeric. It splits complex
2458  *  numbers into re+I*im and replaces I and non-rational real numbers with a
2459  *  temporary symbol. */
2460 ex numeric::to_rational(lst &repl_lst) const
2461 {
2462         if (is_real()) {
2463                 if (!is_rational())
2464                         return replace_with_symbol(*this, repl_lst);
2465         } else { // complex
2466                 numeric re = real();
2467                 numeric im = imag();
2468                 ex re_ex = re.is_rational() ? re : replace_with_symbol(re, repl_lst);
2469                 ex im_ex = im.is_rational() ? im : replace_with_symbol(im, repl_lst);
2470                 return re_ex + im_ex * replace_with_symbol(I, repl_lst);
2471         }
2472         return *this;
2473 }
2474
2475
2476 /** Implementation of ex::to_rational() for powers. It replaces non-integer
2477  *  powers by temporary symbols. */
2478 ex power::to_rational(lst &repl_lst) const
2479 {
2480         if (exponent.info(info_flags::integer))
2481                 return power(basis.to_rational(repl_lst), exponent);
2482         else
2483                 return replace_with_symbol(*this, repl_lst);
2484 }
2485
2486
2487 /** Implementation of ex::to_rational() for expairseqs. */
2488 ex expairseq::to_rational(lst &repl_lst) const
2489 {
2490         epvector s;
2491         s.reserve(seq.size());
2492         epvector::const_iterator i = seq.begin(), end = seq.end();
2493         while (i != end) {
2494                 s.push_back(split_ex_to_pair(recombine_pair_to_ex(*i).to_rational(repl_lst)));
2495                 ++i;
2496         }
2497         ex oc = overall_coeff.to_rational(repl_lst);
2498         if (oc.info(info_flags::numeric))
2499                 return thisexpairseq(s, overall_coeff);
2500         else
2501                 s.push_back(combine_ex_with_coeff_to_pair(oc, _ex1));
2502         return thisexpairseq(s, default_overall_coeff());
2503 }
2504
2505
2506 } // namespace GiNaC