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