]> www.ginac.de Git - ginac.git/blob - ginac/normal.cpp
Fixed bug in expanding expressions containing dummy indices. [V.Kisil]
[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;
237                 for (size_t i=0; i<e.nops(); i++)
238                         c = lcmcoeff(e.op(i), c);
239                 return lcm(c, l);
240         } else if (is_exactly_a<mul>(e)) {
241                 numeric c = _num1;
242                 for (size_t i=0; i<e.nops(); i++)
243                         c *= lcmcoeff(e.op(i), _num1);
244                 return lcm(c, l);
245         } else if (is_exactly_a<power>(e)) {
246                 if (is_a<symbol>(e.op(0)))
247                         return l;
248                 else
249                         return pow(lcmcoeff(e.op(0), l), ex_to<numeric>(e.op(1)));
250         }
251         return l;
252 }
253
254 /** Compute LCM of denominators of coefficients of a polynomial.
255  *  Given a polynomial with rational coefficients, this function computes
256  *  the LCM of the denominators of all coefficients. This can be used
257  *  to bring a polynomial from Q[X] to Z[X].
258  *
259  *  @param e  multivariate polynomial (need not be expanded)
260  *  @return LCM of denominators of coefficients */
261 static numeric lcm_of_coefficients_denominators(const ex &e)
262 {
263         return lcmcoeff(e, _num1);
264 }
265
266 /** Bring polynomial from Q[X] to Z[X] by multiplying in the previously
267  *  determined LCM of the coefficient's denominators.
268  *
269  *  @param e  multivariate polynomial (need not be expanded)
270  *  @param lcm  LCM to multiply in */
271 static ex multiply_lcm(const ex &e, const numeric &lcm)
272 {
273         if (is_exactly_a<mul>(e)) {
274                 size_t num = e.nops();
275                 exvector v; v.reserve(num + 1);
276                 numeric lcm_accum = _num1;
277                 for (size_t i=0; i<num; i++) {
278                         numeric op_lcm = lcmcoeff(e.op(i), _num1);
279                         v.push_back(multiply_lcm(e.op(i), op_lcm));
280                         lcm_accum *= op_lcm;
281                 }
282                 v.push_back(lcm / lcm_accum);
283                 return (new mul(v))->setflag(status_flags::dynallocated);
284         } else if (is_exactly_a<add>(e)) {
285                 size_t num = e.nops();
286                 exvector v; v.reserve(num);
287                 for (size_t i=0; i<num; i++)
288                         v.push_back(multiply_lcm(e.op(i), lcm));
289                 return (new add(v))->setflag(status_flags::dynallocated);
290         } else if (is_exactly_a<power>(e)) {
291                 if (is_a<symbol>(e.op(0)))
292                         return e * lcm;
293                 else
294                         return pow(multiply_lcm(e.op(0), lcm.power(ex_to<numeric>(e.op(1)).inverse())), e.op(1));
295         } else
296                 return e * lcm;
297 }
298
299
300 /** Compute the integer content (= GCD of all numeric coefficients) of an
301  *  expanded polynomial. 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;
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, l = _num1;
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         // Main symbol
718         const ex &x = var->sym;
719
720         // Compare degrees
721         int adeg = a.degree(x), bdeg = b.degree(x);
722         if (bdeg > adeg)
723                 return false;
724
725 #if USE_TRIAL_DIVISION
726
727         // Trial division with polynomial interpolation
728         int i, k;
729
730         // Compute values at evaluation points 0..adeg
731         vector<numeric> alpha; alpha.reserve(adeg + 1);
732         exvector u; u.reserve(adeg + 1);
733         numeric point = _num0;
734         ex c;
735         for (i=0; i<=adeg; i++) {
736                 ex bs = b.subs(x == point, subs_options::no_pattern);
737                 while (bs.is_zero()) {
738                         point += _num1;
739                         bs = b.subs(x == point, subs_options::no_pattern);
740                 }
741                 if (!divide_in_z(a.subs(x == point, subs_options::no_pattern), bs, c, var+1))
742                         return false;
743                 alpha.push_back(point);
744                 u.push_back(c);
745                 point += _num1;
746         }
747
748         // Compute inverses
749         vector<numeric> rcp; rcp.reserve(adeg + 1);
750         rcp.push_back(_num0);
751         for (k=1; k<=adeg; k++) {
752                 numeric product = alpha[k] - alpha[0];
753                 for (i=1; i<k; i++)
754                         product *= alpha[k] - alpha[i];
755                 rcp.push_back(product.inverse());
756         }
757
758         // Compute Newton coefficients
759         exvector v; v.reserve(adeg + 1);
760         v.push_back(u[0]);
761         for (k=1; k<=adeg; k++) {
762                 ex temp = v[k - 1];
763                 for (i=k-2; i>=0; i--)
764                         temp = temp * (alpha[k] - alpha[i]) + v[i];
765                 v.push_back((u[k] - temp) * rcp[k]);
766         }
767
768         // Convert from Newton form to standard form
769         c = v[adeg];
770         for (k=adeg-1; k>=0; k--)
771                 c = c * (x - alpha[k]) + v[k];
772
773         if (c.degree(x) == (adeg - bdeg)) {
774                 q = c.expand();
775                 return true;
776         } else
777                 return false;
778
779 #else
780
781         // Polynomial long division (recursive)
782         ex r = a.expand();
783         if (r.is_zero())
784                 return true;
785         int rdeg = adeg;
786         ex eb = b.expand();
787         ex blcoeff = eb.coeff(x, bdeg);
788         exvector v; v.reserve(std::max(rdeg - bdeg + 1, 0));
789         while (rdeg >= bdeg) {
790                 ex term, rcoeff = r.coeff(x, rdeg);
791                 if (!divide_in_z(rcoeff, blcoeff, term, var+1))
792                         break;
793                 term = (term * power(x, rdeg - bdeg)).expand();
794                 v.push_back(term);
795                 r -= (term * eb).expand();
796                 if (r.is_zero()) {
797                         q = (new add(v))->setflag(status_flags::dynallocated);
798 #if USE_REMEMBER
799                         dr_remember[ex2(a, b)] = exbool(q, true);
800 #endif
801                         return true;
802                 }
803                 rdeg = r.degree(x);
804         }
805 #if USE_REMEMBER
806         dr_remember[ex2(a, b)] = exbool(q, false);
807 #endif
808         return false;
809
810 #endif
811 }
812
813
814 /*
815  *  Separation of unit part, content part and primitive part of polynomials
816  */
817
818 /** Compute unit part (= sign of leading coefficient) of a multivariate
819  *  polynomial in Q[x]. The product of unit part, content part, and primitive
820  *  part is the polynomial itself.
821  *
822  *  @param x  main variable
823  *  @return unit part
824  *  @see ex::content, ex::primpart, ex::unitcontprim */
825 ex ex::unit(const ex &x) const
826 {
827         ex c = expand().lcoeff(x);
828         if (is_exactly_a<numeric>(c))
829                 return c.info(info_flags::negative) ?_ex_1 : _ex1;
830         else {
831                 ex y;
832                 if (get_first_symbol(c, y))
833                         return c.unit(y);
834                 else
835                         throw(std::invalid_argument("invalid expression in unit()"));
836         }
837 }
838
839
840 /** Compute content part (= unit normal GCD of all coefficients) of a
841  *  multivariate polynomial in Q[x]. The product of unit part, content part,
842  *  and primitive part is the polynomial itself.
843  *
844  *  @param x  main variable
845  *  @return content part
846  *  @see ex::unit, ex::primpart, ex::unitcontprim */
847 ex ex::content(const ex &x) const
848 {
849         if (is_exactly_a<numeric>(*this))
850                 return info(info_flags::negative) ? -*this : *this;
851
852         ex e = expand();
853         if (e.is_zero())
854                 return _ex0;
855
856         // First, divide out the integer content (which we can calculate very efficiently).
857         // If the leading coefficient of the quotient is an integer, we are done.
858         ex c = e.integer_content();
859         ex r = e / c;
860         int deg = r.degree(x);
861         ex lcoeff = r.coeff(x, deg);
862         if (lcoeff.info(info_flags::integer))
863                 return c;
864
865         // GCD of all coefficients
866         int ldeg = r.ldegree(x);
867         if (deg == ldeg)
868                 return lcoeff * c / lcoeff.unit(x);
869         ex cont = _ex0;
870         for (int i=ldeg; i<=deg; i++)
871                 cont = gcd(r.coeff(x, i), cont, NULL, NULL, false);
872         return cont * c;
873 }
874
875
876 /** Compute primitive part of a multivariate polynomial in Q[x]. The result
877  *  will be a unit-normal polynomial with a content part of 1. The product
878  *  of unit part, content part, and primitive part is the polynomial itself.
879  *
880  *  @param x  main variable
881  *  @return primitive part
882  *  @see ex::unit, ex::content, ex::unitcontprim */
883 ex ex::primpart(const ex &x) const
884 {
885         // We need to compute the unit and content anyway, so call unitcontprim()
886         ex u, c, p;
887         unitcontprim(x, u, c, p);
888         return p;
889 }
890
891
892 /** Compute primitive part of a multivariate polynomial in Q[x] when the
893  *  content part is already known. This function is faster in computing the
894  *  primitive part than the previous function.
895  *
896  *  @param x  main variable
897  *  @param c  previously computed content part
898  *  @return primitive part */
899 ex ex::primpart(const ex &x, const ex &c) const
900 {
901         if (is_zero() || c.is_zero())
902                 return _ex0;
903         if (is_exactly_a<numeric>(*this))
904                 return _ex1;
905
906         // Divide by unit and content to get primitive part
907         ex u = unit(x);
908         if (is_exactly_a<numeric>(c))
909                 return *this / (c * u);
910         else
911                 return quo(*this, c * u, x, false);
912 }
913
914
915 /** Compute unit part, content part, and primitive part of a multivariate
916  *  polynomial in Q[x]. The product of the three parts is the polynomial
917  *  itself.
918  *
919  *  @param x  main variable
920  *  @param u  unit part (returned)
921  *  @param c  content part (returned)
922  *  @param p  primitive part (returned)
923  *  @see ex::unit, ex::content, ex::primpart */
924 void ex::unitcontprim(const ex &x, ex &u, ex &c, ex &p) const
925 {
926         // Quick check for zero (avoid expanding)
927         if (is_zero()) {
928                 u = _ex1;
929                 c = p = _ex0;
930                 return;
931         }
932
933         // Special case: input is a number
934         if (is_exactly_a<numeric>(*this)) {
935                 if (info(info_flags::negative)) {
936                         u = _ex_1;
937                         c = abs(ex_to<numeric>(*this));
938                 } else {
939                         u = _ex1;
940                         c = *this;
941                 }
942                 p = _ex1;
943                 return;
944         }
945
946         // Expand input polynomial
947         ex e = expand();
948         if (e.is_zero()) {
949                 u = _ex1;
950                 c = p = _ex0;
951                 return;
952         }
953
954         // Compute unit and content
955         u = unit(x);
956         c = content(x);
957
958         // Divide by unit and content to get primitive part
959         if (c.is_zero()) {
960                 p = _ex0;
961                 return;
962         }
963         if (is_exactly_a<numeric>(c))
964                 p = *this / (c * u);
965         else
966                 p = quo(e, c * u, x, false);
967 }
968
969
970 /*
971  *  GCD of multivariate polynomials
972  */
973
974 /** Compute GCD of multivariate polynomials using the subresultant PRS
975  *  algorithm. This function is used internally by gcd().
976  *
977  *  @param a   first multivariate polynomial
978  *  @param b   second multivariate polynomial
979  *  @param var iterator to first element of vector of sym_desc structs
980  *  @return the GCD as a new expression
981  *  @see gcd */
982
983 static ex sr_gcd(const ex &a, const ex &b, sym_desc_vec::const_iterator var)
984 {
985 #if STATISTICS
986         sr_gcd_called++;
987 #endif
988
989         // The first symbol is our main variable
990         const ex &x = var->sym;
991
992         // Sort c and d so that c has higher degree
993         ex c, d;
994         int adeg = a.degree(x), bdeg = b.degree(x);
995         int cdeg, ddeg;
996         if (adeg >= bdeg) {
997                 c = a;
998                 d = b;
999                 cdeg = adeg;
1000                 ddeg = bdeg;
1001         } else {
1002                 c = b;
1003                 d = a;
1004                 cdeg = bdeg;
1005                 ddeg = adeg;
1006         }
1007
1008         // Remove content from c and d, to be attached to GCD later
1009         ex cont_c = c.content(x);
1010         ex cont_d = d.content(x);
1011         ex gamma = gcd(cont_c, cont_d, NULL, NULL, false);
1012         if (ddeg == 0)
1013                 return gamma;
1014         c = c.primpart(x, cont_c);
1015         d = d.primpart(x, cont_d);
1016
1017         // First element of subresultant sequence
1018         ex r = _ex0, ri = _ex1, psi = _ex1;
1019         int delta = cdeg - ddeg;
1020
1021         for (;;) {
1022
1023                 // Calculate polynomial pseudo-remainder
1024                 r = prem(c, d, x, false);
1025                 if (r.is_zero())
1026                         return gamma * d.primpart(x);
1027
1028                 c = d;
1029                 cdeg = ddeg;
1030                 if (!divide_in_z(r, ri * pow(psi, delta), d, var))
1031                         throw(std::runtime_error("invalid expression in sr_gcd(), division failed"));
1032                 ddeg = d.degree(x);
1033                 if (ddeg == 0) {
1034                         if (is_exactly_a<numeric>(r))
1035                                 return gamma;
1036                         else
1037                                 return gamma * r.primpart(x);
1038                 }
1039
1040                 // Next element of subresultant sequence
1041                 ri = c.expand().lcoeff(x);
1042                 if (delta == 1)
1043                         psi = ri;
1044                 else if (delta)
1045                         divide_in_z(pow(ri, delta), pow(psi, delta-1), psi, var+1);
1046                 delta = cdeg - ddeg;
1047         }
1048 }
1049
1050
1051 /** Return maximum (absolute value) coefficient of a polynomial.
1052  *  This function is used internally by heur_gcd().
1053  *
1054  *  @return maximum coefficient
1055  *  @see heur_gcd */
1056 numeric ex::max_coefficient() const
1057 {
1058         return bp->max_coefficient();
1059 }
1060
1061 /** Implementation ex::max_coefficient().
1062  *  @see heur_gcd */
1063 numeric basic::max_coefficient() const
1064 {
1065         return _num1;
1066 }
1067
1068 numeric numeric::max_coefficient() const
1069 {
1070         return abs(*this);
1071 }
1072
1073 numeric add::max_coefficient() const
1074 {
1075         epvector::const_iterator it = seq.begin();
1076         epvector::const_iterator itend = seq.end();
1077         GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
1078         numeric cur_max = abs(ex_to<numeric>(overall_coeff));
1079         while (it != itend) {
1080                 numeric a;
1081                 GINAC_ASSERT(!is_exactly_a<numeric>(it->rest));
1082                 a = abs(ex_to<numeric>(it->coeff));
1083                 if (a > cur_max)
1084                         cur_max = a;
1085                 it++;
1086         }
1087         return cur_max;
1088 }
1089
1090 numeric mul::max_coefficient() const
1091 {
1092 #ifdef DO_GINAC_ASSERT
1093         epvector::const_iterator it = seq.begin();
1094         epvector::const_iterator itend = seq.end();
1095         while (it != itend) {
1096                 GINAC_ASSERT(!is_exactly_a<numeric>(recombine_pair_to_ex(*it)));
1097                 it++;
1098         }
1099 #endif // def DO_GINAC_ASSERT
1100         GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
1101         return abs(ex_to<numeric>(overall_coeff));
1102 }
1103
1104
1105 /** Apply symmetric modular homomorphism to an expanded multivariate
1106  *  polynomial.  This function is usually used internally by heur_gcd().
1107  *
1108  *  @param xi  modulus
1109  *  @return mapped polynomial
1110  *  @see heur_gcd */
1111 ex basic::smod(const numeric &xi) const
1112 {
1113         return *this;
1114 }
1115
1116 ex numeric::smod(const numeric &xi) const
1117 {
1118         return GiNaC::smod(*this, xi);
1119 }
1120
1121 ex add::smod(const numeric &xi) const
1122 {
1123         epvector newseq;
1124         newseq.reserve(seq.size()+1);
1125         epvector::const_iterator it = seq.begin();
1126         epvector::const_iterator itend = seq.end();
1127         while (it != itend) {
1128                 GINAC_ASSERT(!is_exactly_a<numeric>(it->rest));
1129                 numeric coeff = GiNaC::smod(ex_to<numeric>(it->coeff), xi);
1130                 if (!coeff.is_zero())
1131                         newseq.push_back(expair(it->rest, coeff));
1132                 it++;
1133         }
1134         GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
1135         numeric coeff = GiNaC::smod(ex_to<numeric>(overall_coeff), xi);
1136         return (new add(newseq,coeff))->setflag(status_flags::dynallocated);
1137 }
1138
1139 ex mul::smod(const numeric &xi) const
1140 {
1141 #ifdef DO_GINAC_ASSERT
1142         epvector::const_iterator it = seq.begin();
1143         epvector::const_iterator itend = seq.end();
1144         while (it != itend) {
1145                 GINAC_ASSERT(!is_exactly_a<numeric>(recombine_pair_to_ex(*it)));
1146                 it++;
1147         }
1148 #endif // def DO_GINAC_ASSERT
1149         mul * mulcopyp = new mul(*this);
1150         GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
1151         mulcopyp->overall_coeff = GiNaC::smod(ex_to<numeric>(overall_coeff),xi);
1152         mulcopyp->clearflag(status_flags::evaluated);
1153         mulcopyp->clearflag(status_flags::hash_calculated);
1154         return mulcopyp->setflag(status_flags::dynallocated);
1155 }
1156
1157
1158 /** xi-adic polynomial interpolation */
1159 static ex interpolate(const ex &gamma, const numeric &xi, const ex &x, int degree_hint = 1)
1160 {
1161         exvector g; g.reserve(degree_hint);
1162         ex e = gamma;
1163         numeric rxi = xi.inverse();
1164         for (int i=0; !e.is_zero(); i++) {
1165                 ex gi = e.smod(xi);
1166                 g.push_back(gi * power(x, i));
1167                 e = (e - gi) * rxi;
1168         }
1169         return (new add(g))->setflag(status_flags::dynallocated);
1170 }
1171
1172 /** Exception thrown by heur_gcd() to signal failure. */
1173 class gcdheu_failed {};
1174
1175 /** Compute GCD of multivariate polynomials using the heuristic GCD algorithm.
1176  *  get_symbol_stats() must have been called previously with the input
1177  *  polynomials and an iterator to the first element of the sym_desc vector
1178  *  passed in. This function is used internally by gcd().
1179  *
1180  *  @param a  first multivariate polynomial (expanded)
1181  *  @param b  second multivariate polynomial (expanded)
1182  *  @param ca  cofactor of polynomial a (returned), NULL to suppress
1183  *             calculation of cofactor
1184  *  @param cb  cofactor of polynomial b (returned), NULL to suppress
1185  *             calculation of cofactor
1186  *  @param var iterator to first element of vector of sym_desc structs
1187  *  @return the GCD as a new expression
1188  *  @see gcd
1189  *  @exception gcdheu_failed() */
1190 static ex heur_gcd(const ex &a, const ex &b, ex *ca, ex *cb, sym_desc_vec::const_iterator var)
1191 {
1192 #if STATISTICS
1193         heur_gcd_called++;
1194 #endif
1195
1196         // Algorithm only works for non-vanishing input polynomials
1197         if (a.is_zero() || b.is_zero())
1198                 return (new fail())->setflag(status_flags::dynallocated);
1199
1200         // GCD of two numeric values -> CLN
1201         if (is_exactly_a<numeric>(a) && is_exactly_a<numeric>(b)) {
1202                 numeric g = gcd(ex_to<numeric>(a), ex_to<numeric>(b));
1203                 if (ca)
1204                         *ca = ex_to<numeric>(a) / g;
1205                 if (cb)
1206                         *cb = ex_to<numeric>(b) / g;
1207                 return g;
1208         }
1209
1210         // The first symbol is our main variable
1211         const ex &x = var->sym;
1212
1213         // Remove integer content
1214         numeric gc = gcd(a.integer_content(), b.integer_content());
1215         numeric rgc = gc.inverse();
1216         ex p = a * rgc;
1217         ex q = b * rgc;
1218         int maxdeg =  std::max(p.degree(x), q.degree(x));
1219         
1220         // Find evaluation point
1221         numeric mp = p.max_coefficient();
1222         numeric mq = q.max_coefficient();
1223         numeric xi;
1224         if (mp > mq)
1225                 xi = mq * _num2 + _num2;
1226         else
1227                 xi = mp * _num2 + _num2;
1228
1229         // 6 tries maximum
1230         for (int t=0; t<6; t++) {
1231                 if (xi.int_length() * maxdeg > 100000) {
1232                         throw gcdheu_failed();
1233                 }
1234
1235                 // Apply evaluation homomorphism and calculate GCD
1236                 ex cp, cq;
1237                 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();
1238                 if (!is_exactly_a<fail>(gamma)) {
1239
1240                         // Reconstruct polynomial from GCD of mapped polynomials
1241                         ex g = interpolate(gamma, xi, x, maxdeg);
1242
1243                         // Remove integer content
1244                         g /= g.integer_content();
1245
1246                         // If the calculated polynomial divides both p and q, this is the GCD
1247                         ex dummy;
1248                         if (divide_in_z(p, g, ca ? *ca : dummy, var) && divide_in_z(q, g, cb ? *cb : dummy, var)) {
1249                                 g *= gc;
1250                                 return g;
1251                         }
1252                 }
1253
1254                 // Next evaluation point
1255                 xi = iquo(xi * isqrt(isqrt(xi)) * numeric(73794), numeric(27011));
1256         }
1257         return (new fail())->setflag(status_flags::dynallocated);
1258 }
1259
1260
1261 /** Compute GCD (Greatest Common Divisor) of multivariate polynomials a(X)
1262  *  and b(X) in Z[X]. Optionally also compute the cofactors of a and b,
1263  *  defined by a = ca * gcd(a, b) and b = cb * gcd(a, b).
1264  *
1265  *  @param a  first multivariate polynomial
1266  *  @param b  second multivariate polynomial
1267  *  @param ca pointer to expression that will receive the cofactor of a, or NULL
1268  *  @param cb pointer to expression that will receive the cofactor of b, or NULL
1269  *  @param check_args  check whether a and b are polynomials with rational
1270  *         coefficients (defaults to "true")
1271  *  @return the GCD as a new expression */
1272 ex gcd(const ex &a, const ex &b, ex *ca, ex *cb, bool check_args)
1273 {
1274 #if STATISTICS
1275         gcd_called++;
1276 #endif
1277
1278         // GCD of numerics -> CLN
1279         if (is_exactly_a<numeric>(a) && is_exactly_a<numeric>(b)) {
1280                 numeric g = gcd(ex_to<numeric>(a), ex_to<numeric>(b));
1281                 if (ca || cb) {
1282                         if (g.is_zero()) {
1283                                 if (ca)
1284                                         *ca = _ex0;
1285                                 if (cb)
1286                                         *cb = _ex0;
1287                         } else {
1288                                 if (ca)
1289                                         *ca = ex_to<numeric>(a) / g;
1290                                 if (cb)
1291                                         *cb = ex_to<numeric>(b) / g;
1292                         }
1293                 }
1294                 return g;
1295         }
1296
1297         // Check arguments
1298         if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial))) {
1299                 throw(std::invalid_argument("gcd: arguments must be polynomials over the rationals"));
1300         }
1301
1302         // Partially factored cases (to avoid expanding large expressions)
1303         if (is_exactly_a<mul>(a)) {
1304                 if (is_exactly_a<mul>(b) && b.nops() > a.nops())
1305                         goto factored_b;
1306 factored_a:
1307                 size_t num = a.nops();
1308                 exvector g; g.reserve(num);
1309                 exvector acc_ca; acc_ca.reserve(num);
1310                 ex part_b = b;
1311                 for (size_t i=0; i<num; i++) {
1312                         ex part_ca, part_cb;
1313                         g.push_back(gcd(a.op(i), part_b, &part_ca, &part_cb, check_args));
1314                         acc_ca.push_back(part_ca);
1315                         part_b = part_cb;
1316                 }
1317                 if (ca)
1318                         *ca = (new mul(acc_ca))->setflag(status_flags::dynallocated);
1319                 if (cb)
1320                         *cb = part_b;
1321                 return (new mul(g))->setflag(status_flags::dynallocated);
1322         } else if (is_exactly_a<mul>(b)) {
1323                 if (is_exactly_a<mul>(a) && a.nops() > b.nops())
1324                         goto factored_a;
1325 factored_b:
1326                 size_t num = b.nops();
1327                 exvector g; g.reserve(num);
1328                 exvector acc_cb; acc_cb.reserve(num);
1329                 ex part_a = a;
1330                 for (size_t i=0; i<num; i++) {
1331                         ex part_ca, part_cb;
1332                         g.push_back(gcd(part_a, b.op(i), &part_ca, &part_cb, check_args));
1333                         acc_cb.push_back(part_cb);
1334                         part_a = part_ca;
1335                 }
1336                 if (ca)
1337                         *ca = part_a;
1338                 if (cb)
1339                         *cb = (new mul(acc_cb))->setflag(status_flags::dynallocated);
1340                 return (new mul(g))->setflag(status_flags::dynallocated);
1341         }
1342
1343 #if FAST_COMPARE
1344         // Input polynomials of the form poly^n are sometimes also trivial
1345         if (is_exactly_a<power>(a)) {
1346                 ex p = a.op(0);
1347                 const ex& exp_a = a.op(1);
1348                 if (is_exactly_a<power>(b)) {
1349                         ex pb = b.op(0);
1350                         const ex& exp_b = b.op(1);
1351                         if (p.is_equal(pb)) {
1352                                 // a = p^n, b = p^m, gcd = p^min(n, m)
1353                                 if (exp_a < exp_b) {
1354                                         if (ca)
1355                                                 *ca = _ex1;
1356                                         if (cb)
1357                                                 *cb = power(p, exp_b - exp_a);
1358                                         return power(p, exp_a);
1359                                 } else {
1360                                         if (ca)
1361                                                 *ca = power(p, exp_a - exp_b);
1362                                         if (cb)
1363                                                 *cb = _ex1;
1364                                         return power(p, exp_b);
1365                                 }
1366                         } else {
1367                                 ex p_co, pb_co;
1368                                 ex p_gcd = gcd(p, pb, &p_co, &pb_co, check_args);
1369                                 if (p_gcd.is_equal(_ex1)) {
1370                                         // a(x) = p(x)^n, b(x) = p_b(x)^m, gcd (p, p_b) = 1 ==>
1371                                         // gcd(a,b) = 1
1372                                         if (ca)
1373                                                 *ca = a;
1374                                         if (cb)
1375                                                 *cb = b;
1376                                         return _ex1;
1377                                         // XXX: do I need to check for p_gcd = -1?
1378                                 } else {
1379                                         // there are common factors:
1380                                         // a(x) = g(x)^n A(x)^n, b(x) = g(x)^m B(x)^m ==>
1381                                         // gcd(a, b) = g(x)^n gcd(A(x)^n, g(x)^(n-m) B(x)^m
1382                                         if (exp_a < exp_b) {
1383                                                 return power(p_gcd, exp_a)*
1384                                                         gcd(power(p_co, exp_a), power(p_gcd, exp_b-exp_a)*power(pb_co, exp_b), ca, cb, false);
1385                                         } else {
1386                                                 return power(p_gcd, exp_b)*
1387                                                         gcd(power(p_gcd, exp_a - exp_b)*power(p_co, exp_a), power(pb_co, exp_b), ca, cb, false);
1388                                         }
1389                                 } // p_gcd.is_equal(_ex1)
1390                         } // p.is_equal(pb)
1391
1392                 } else {
1393                         if (p.is_equal(b)) {
1394                                 // a = p^n, b = p, gcd = p
1395                                 if (ca)
1396                                         *ca = power(p, a.op(1) - 1);
1397                                 if (cb)
1398                                         *cb = _ex1;
1399                                 return p;
1400                         } 
1401
1402                         ex p_co, bpart_co;
1403                         ex p_gcd = gcd(p, b, &p_co, &bpart_co, false);
1404
1405                         if (p_gcd.is_equal(_ex1)) {
1406                                 // a(x) = p(x)^n, gcd(p, b) = 1 ==> gcd(a, b) = 1
1407                                 if (ca)
1408                                         *ca = a;
1409                                 if (cb)
1410                                         *cb = b;
1411                                 return _ex1;
1412                         } else {
1413                                 // 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))
1414                                 return p_gcd*gcd(power(p_gcd, exp_a-1)*power(p_co, exp_a), bpart_co, ca, cb, false);
1415                         }
1416                 } // is_exactly_a<power>(b)
1417
1418         } else if (is_exactly_a<power>(b)) {
1419                 ex p = b.op(0);
1420                 if (p.is_equal(a)) {
1421                         // a = p, b = p^n, gcd = p
1422                         if (ca)
1423                                 *ca = _ex1;
1424                         if (cb)
1425                                 *cb = power(p, b.op(1) - 1);
1426                         return p;
1427                 }
1428
1429                 ex p_co, apart_co;
1430                 const ex& exp_b(b.op(1));
1431                 ex p_gcd = gcd(a, p, &apart_co, &p_co, false);
1432                 if (p_gcd.is_equal(_ex1)) {
1433                         // b=p(x)^n, gcd(a, p) = 1 ==> gcd(a, b) == 1
1434                         if (ca)
1435                                 *ca = a;
1436                         if (cb)
1437                                 *cb = b;
1438                         return _ex1;
1439                 } else {
1440                         // there are common factors:
1441                         // 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))
1442
1443                         return p_gcd*gcd(apart_co, power(p_gcd, exp_b-1)*power(p_co, exp_b), ca, cb, false);
1444                 } // p_gcd.is_equal(_ex1)
1445         }
1446 #endif
1447
1448         // Some trivial cases
1449         ex aex = a.expand(), bex = b.expand();
1450         if (aex.is_zero()) {
1451                 if (ca)
1452                         *ca = _ex0;
1453                 if (cb)
1454                         *cb = _ex1;
1455                 return b;
1456         }
1457         if (bex.is_zero()) {
1458                 if (ca)
1459                         *ca = _ex1;
1460                 if (cb)
1461                         *cb = _ex0;
1462                 return a;
1463         }
1464         if (aex.is_equal(_ex1) || bex.is_equal(_ex1)) {
1465                 if (ca)
1466                         *ca = a;
1467                 if (cb)
1468                         *cb = b;
1469                 return _ex1;
1470         }
1471 #if FAST_COMPARE
1472         if (a.is_equal(b)) {
1473                 if (ca)
1474                         *ca = _ex1;
1475                 if (cb)
1476                         *cb = _ex1;
1477                 return a;
1478         }
1479 #endif
1480
1481         // Gather symbol statistics
1482         sym_desc_vec sym_stats;
1483         get_symbol_stats(a, b, sym_stats);
1484
1485         // The symbol with least degree is our main variable
1486         sym_desc_vec::const_iterator var = sym_stats.begin();
1487         const ex &x = var->sym;
1488
1489         // Cancel trivial common factor
1490         int ldeg_a = var->ldeg_a;
1491         int ldeg_b = var->ldeg_b;
1492         int min_ldeg = std::min(ldeg_a,ldeg_b);
1493         if (min_ldeg > 0) {
1494                 ex common = power(x, min_ldeg);
1495                 return gcd((aex / common).expand(), (bex / common).expand(), ca, cb, false) * common;
1496         }
1497
1498         // Try to eliminate variables
1499         if (var->deg_a == 0) {
1500                 ex bex_u, bex_c, bex_p;
1501                 bex.unitcontprim(x, bex_u, bex_c, bex_p);
1502                 ex g = gcd(aex, bex_c, ca, cb, false);
1503                 if (cb)
1504                         *cb *= bex_u * bex_p;
1505                 return g;
1506         } else if (var->deg_b == 0) {
1507                 ex aex_u, aex_c, aex_p;
1508                 aex.unitcontprim(x, aex_u, aex_c, aex_p);
1509                 ex g = gcd(aex_c, bex, ca, cb, false);
1510                 if (ca)
1511                         *ca *= aex_u * aex_p;
1512                 return g;
1513         }
1514
1515         // Try heuristic algorithm first, fall back to PRS if that failed
1516         ex g;
1517         try {
1518                 g = heur_gcd(aex, bex, ca, cb, var);
1519         } catch (gcdheu_failed) {
1520                 g = fail();
1521         }
1522         if (is_exactly_a<fail>(g)) {
1523 #if STATISTICS
1524                 heur_gcd_failed++;
1525 #endif
1526                 g = sr_gcd(aex, bex, var);
1527                 if (g.is_equal(_ex1)) {
1528                         // Keep cofactors factored if possible
1529                         if (ca)
1530                                 *ca = a;
1531                         if (cb)
1532                                 *cb = b;
1533                 } else {
1534                         if (ca)
1535                                 divide(aex, g, *ca, false);
1536                         if (cb)
1537                                 divide(bex, g, *cb, false);
1538                 }
1539         } else {
1540                 if (g.is_equal(_ex1)) {
1541                         // Keep cofactors factored if possible
1542                         if (ca)
1543                                 *ca = a;
1544                         if (cb)
1545                                 *cb = b;
1546                 }
1547         }
1548
1549         return g;
1550 }
1551
1552
1553 /** Compute LCM (Least Common Multiple) of multivariate polynomials in Z[X].
1554  *
1555  *  @param a  first multivariate polynomial
1556  *  @param b  second multivariate polynomial
1557  *  @param check_args  check whether a and b are polynomials with rational
1558  *         coefficients (defaults to "true")
1559  *  @return the LCM as a new expression */
1560 ex lcm(const ex &a, const ex &b, bool check_args)
1561 {
1562         if (is_exactly_a<numeric>(a) && is_exactly_a<numeric>(b))
1563                 return lcm(ex_to<numeric>(a), ex_to<numeric>(b));
1564         if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
1565                 throw(std::invalid_argument("lcm: arguments must be polynomials over the rationals"));
1566         
1567         ex ca, cb;
1568         ex g = gcd(a, b, &ca, &cb, false);
1569         return ca * cb * g;
1570 }
1571
1572
1573 /*
1574  *  Square-free factorization
1575  */
1576
1577 /** Compute square-free factorization of multivariate polynomial a(x) using
1578  *  Yun's algorithm.  Used internally by sqrfree().
1579  *
1580  *  @param a  multivariate polynomial over Z[X], treated here as univariate
1581  *            polynomial in x.
1582  *  @param x  variable to factor in
1583  *  @return   vector of factors sorted in ascending degree */
1584 static exvector sqrfree_yun(const ex &a, const symbol &x)
1585 {
1586         exvector res;
1587         ex w = a;
1588         ex z = w.diff(x);
1589         ex g = gcd(w, z);
1590         if (g.is_equal(_ex1)) {
1591                 res.push_back(a);
1592                 return res;
1593         }
1594         ex y;
1595         do {
1596                 w = quo(w, g, x);
1597                 y = quo(z, g, x);
1598                 z = y - w.diff(x);
1599                 g = gcd(w, z);
1600                 res.push_back(g);
1601         } while (!z.is_zero());
1602         return res;
1603 }
1604
1605
1606 /** Compute a square-free factorization of a multivariate polynomial in Q[X].
1607  *
1608  *  @param a  multivariate polynomial over Q[X]
1609  *  @param l  lst of variables to factor in, may be left empty for autodetection
1610  *  @return   a square-free factorization of \p a.
1611  *
1612  * \note
1613  * A polynomial \f$p(X) \in C[X]\f$ is said <EM>square-free</EM>
1614  * if, whenever any two polynomials \f$q(X)\f$ and \f$r(X)\f$
1615  * are such that
1616  * \f[
1617  *     p(X) = q(X)^2 r(X),
1618  * \f]
1619  * we have \f$q(X) \in C\f$.
1620  * This means that \f$p(X)\f$ has no repeated factors, apart
1621  * eventually from constants.
1622  * Given a polynomial \f$p(X) \in C[X]\f$, we say that the
1623  * decomposition
1624  * \f[
1625  *   p(X) = b \cdot p_1(X)^{a_1} \cdot p_2(X)^{a_2} \cdots p_r(X)^{a_r}
1626  * \f]
1627  * is a <EM>square-free factorization</EM> of \f$p(X)\f$ if the
1628  * following conditions hold:
1629  * -#  \f$b \in C\f$ and \f$b \neq 0\f$;
1630  * -#  \f$a_i\f$ is a positive integer for \f$i = 1, \ldots, r\f$;
1631  * -#  the degree of the polynomial \f$p_i\f$ is strictly positive
1632  *     for \f$i = 1, \ldots, r\f$;
1633  * -#  the polynomial \f$\Pi_{i=1}^r p_i(X)\f$ is square-free.
1634  *
1635  * Square-free factorizations need not be unique.  For example, if
1636  * \f$a_i\f$ is even, we could change the polynomial \f$p_i(X)\f$
1637  * into \f$-p_i(X)\f$.
1638  * Observe also that the factors \f$p_i(X)\f$ need not be irreducible
1639  * polynomials.
1640  */
1641 ex sqrfree(const ex &a, const lst &l)
1642 {
1643         if (is_exactly_a<numeric>(a) ||     // algorithm does not trap a==0
1644             is_a<symbol>(a))        // shortcut
1645                 return a;
1646
1647         // If no lst of variables to factorize in was specified we have to
1648         // invent one now.  Maybe one can optimize here by reversing the order
1649         // or so, I don't know.
1650         lst args;
1651         if (l.nops()==0) {
1652                 sym_desc_vec sdv;
1653                 get_symbol_stats(a, _ex0, sdv);
1654                 sym_desc_vec::const_iterator it = sdv.begin(), itend = sdv.end();
1655                 while (it != itend) {
1656                         args.append(it->sym);
1657                         ++it;
1658                 }
1659         } else {
1660                 args = l;
1661         }
1662
1663         // Find the symbol to factor in at this stage
1664         if (!is_a<symbol>(args.op(0)))
1665                 throw (std::runtime_error("sqrfree(): invalid factorization variable"));
1666         const symbol &x = ex_to<symbol>(args.op(0));
1667
1668         // convert the argument from something in Q[X] to something in Z[X]
1669         const numeric lcm = lcm_of_coefficients_denominators(a);
1670         const ex tmp = multiply_lcm(a,lcm);
1671
1672         // find the factors
1673         exvector factors = sqrfree_yun(tmp, x);
1674
1675         // construct the next list of symbols with the first element popped
1676         lst newargs = args;
1677         newargs.remove_first();
1678
1679         // recurse down the factors in remaining variables
1680         if (newargs.nops()>0) {
1681                 exvector::iterator i = factors.begin();
1682                 while (i != factors.end()) {
1683                         *i = sqrfree(*i, newargs);
1684                         ++i;
1685                 }
1686         }
1687
1688         // Done with recursion, now construct the final result
1689         ex result = _ex1;
1690         exvector::const_iterator it = factors.begin(), itend = factors.end();
1691         for (int p = 1; it!=itend; ++it, ++p)
1692                 result *= power(*it, p);
1693
1694         // Yun's algorithm does not account for constant factors.  (For univariate
1695         // polynomials it works only in the monic case.)  We can correct this by
1696         // inserting what has been lost back into the result.  For completeness
1697         // we'll also have to recurse down that factor in the remaining variables.
1698         if (newargs.nops()>0)
1699                 result *= sqrfree(quo(tmp, result, x), newargs);
1700         else
1701                 result *= quo(tmp, result, x);
1702
1703         // Put in the reational overall factor again and return
1704         return result * lcm.inverse();
1705 }
1706
1707
1708 /** Compute square-free partial fraction decomposition of rational function
1709  *  a(x).
1710  *
1711  *  @param a rational function over Z[x], treated as univariate polynomial
1712  *           in x
1713  *  @param x variable to factor in
1714  *  @return decomposed rational function */
1715 ex sqrfree_parfrac(const ex & a, const symbol & x)
1716 {
1717         // Find numerator and denominator
1718         ex nd = numer_denom(a);
1719         ex numer = nd.op(0), denom = nd.op(1);
1720 //clog << "numer = " << numer << ", denom = " << denom << endl;
1721
1722         // Convert N(x)/D(x) -> Q(x) + R(x)/D(x), so degree(R) < degree(D)
1723         ex red_poly = quo(numer, denom, x), red_numer = rem(numer, denom, x).expand();
1724 //clog << "red_poly = " << red_poly << ", red_numer = " << red_numer << endl;
1725
1726         // Factorize denominator and compute cofactors
1727         exvector yun = sqrfree_yun(denom, x);
1728 //clog << "yun factors: " << exprseq(yun) << endl;
1729         size_t num_yun = yun.size();
1730         exvector factor; factor.reserve(num_yun);
1731         exvector cofac; cofac.reserve(num_yun);
1732         for (size_t i=0; i<num_yun; i++) {
1733                 if (!yun[i].is_equal(_ex1)) {
1734                         for (size_t j=0; j<=i; j++) {
1735                                 factor.push_back(pow(yun[i], j+1));
1736                                 ex prod = _ex1;
1737                                 for (size_t k=0; k<num_yun; k++) {
1738                                         if (k == i)
1739                                                 prod *= pow(yun[k], i-j);
1740                                         else
1741                                                 prod *= pow(yun[k], k+1);
1742                                 }
1743                                 cofac.push_back(prod.expand());
1744                         }
1745                 }
1746         }
1747         size_t num_factors = factor.size();
1748 //clog << "factors  : " << exprseq(factor) << endl;
1749 //clog << "cofactors: " << exprseq(cofac) << endl;
1750
1751         // Construct coefficient matrix for decomposition
1752         int max_denom_deg = denom.degree(x);
1753         matrix sys(max_denom_deg + 1, num_factors);
1754         matrix rhs(max_denom_deg + 1, 1);
1755         for (int i=0; i<=max_denom_deg; i++) {
1756                 for (size_t j=0; j<num_factors; j++)
1757                         sys(i, j) = cofac[j].coeff(x, i);
1758                 rhs(i, 0) = red_numer.coeff(x, i);
1759         }
1760 //clog << "coeffs: " << sys << endl;
1761 //clog << "rhs   : " << rhs << endl;
1762
1763         // Solve resulting linear system
1764         matrix vars(num_factors, 1);
1765         for (size_t i=0; i<num_factors; i++)
1766                 vars(i, 0) = symbol();
1767         matrix sol = sys.solve(vars, rhs);
1768
1769         // Sum up decomposed fractions
1770         ex sum = 0;
1771         for (size_t i=0; i<num_factors; i++)
1772                 sum += sol(i, 0) / factor[i];
1773
1774         return red_poly + sum;
1775 }
1776
1777
1778 /*
1779  *  Normal form of rational functions
1780  */
1781
1782 /*
1783  *  Note: The internal normal() functions (= basic::normal() and overloaded
1784  *  functions) all return lists of the form {numerator, denominator}. This
1785  *  is to get around mul::eval()'s automatic expansion of numeric coefficients.
1786  *  E.g. (a+b)/3 is automatically converted to a/3+b/3 but we want to keep
1787  *  the information that (a+b) is the numerator and 3 is the denominator.
1788  */
1789
1790
1791 /** Create a symbol for replacing the expression "e" (or return a previously
1792  *  assigned symbol). The symbol and expression are appended to repl, for
1793  *  a later application of subs().
1794  *  @see ex::normal */
1795 static ex replace_with_symbol(const ex & e, exmap & repl, exmap & rev_lookup)
1796 {
1797         // Expression already replaced? Then return the assigned symbol
1798         exmap::const_iterator it = rev_lookup.find(e);
1799         if (it != rev_lookup.end())
1800                 return it->second;
1801         
1802         // Otherwise create new symbol and add to list, taking care that the
1803         // replacement expression doesn't itself contain symbols from repl,
1804         // because subs() is not recursive
1805         ex es = (new symbol)->setflag(status_flags::dynallocated);
1806         ex e_replaced = e.subs(repl, subs_options::no_pattern);
1807         repl.insert(std::make_pair(es, e_replaced));
1808         rev_lookup.insert(std::make_pair(e_replaced, es));
1809         return es;
1810 }
1811
1812 /** Create a symbol for replacing the expression "e" (or return a previously
1813  *  assigned symbol). The symbol and expression are appended to repl, and the
1814  *  symbol is returned.
1815  *  @see basic::to_rational
1816  *  @see basic::to_polynomial */
1817 static ex replace_with_symbol(const ex & e, exmap & repl)
1818 {
1819         // Expression already replaced? Then return the assigned symbol
1820         for (exmap::const_iterator it = repl.begin(); it != repl.end(); ++it)
1821                 if (it->second.is_equal(e))
1822                         return it->first;
1823         
1824         // Otherwise create new symbol and add to list, taking care that the
1825         // replacement expression doesn't itself contain symbols from repl,
1826         // because subs() is not recursive
1827         ex es = (new symbol)->setflag(status_flags::dynallocated);
1828         ex e_replaced = e.subs(repl, subs_options::no_pattern);
1829         repl.insert(std::make_pair(es, e_replaced));
1830         return es;
1831 }
1832
1833
1834 /** Function object to be applied by basic::normal(). */
1835 struct normal_map_function : public map_function {
1836         int level;
1837         normal_map_function(int l) : level(l) {}
1838         ex operator()(const ex & e) { return normal(e, level); }
1839 };
1840
1841 /** Default implementation of ex::normal(). It normalizes the children and
1842  *  replaces the object with a temporary symbol.
1843  *  @see ex::normal */
1844 ex basic::normal(exmap & repl, exmap & rev_lookup, int level) const
1845 {
1846         if (nops() == 0)
1847                 return (new lst(replace_with_symbol(*this, repl, rev_lookup), _ex1))->setflag(status_flags::dynallocated);
1848         else {
1849                 if (level == 1)
1850                         return (new lst(replace_with_symbol(*this, repl, rev_lookup), _ex1))->setflag(status_flags::dynallocated);
1851                 else if (level == -max_recursion_level)
1852                         throw(std::runtime_error("max recursion level reached"));
1853                 else {
1854                         normal_map_function map_normal(level - 1);
1855                         return (new lst(replace_with_symbol(map(map_normal), repl, rev_lookup), _ex1))->setflag(status_flags::dynallocated);
1856                 }
1857         }
1858 }
1859
1860
1861 /** Implementation of ex::normal() for symbols. This returns the unmodified symbol.
1862  *  @see ex::normal */
1863 ex symbol::normal(exmap & repl, exmap & rev_lookup, int level) const
1864 {
1865         return (new lst(*this, _ex1))->setflag(status_flags::dynallocated);
1866 }
1867
1868
1869 /** Implementation of ex::normal() for a numeric. It splits complex numbers
1870  *  into re+I*im and replaces I and non-rational real numbers with a temporary
1871  *  symbol.
1872  *  @see ex::normal */
1873 ex numeric::normal(exmap & repl, exmap & rev_lookup, int level) const
1874 {
1875         numeric num = numer();
1876         ex numex = num;
1877
1878         if (num.is_real()) {
1879                 if (!num.is_integer())
1880                         numex = replace_with_symbol(numex, repl, rev_lookup);
1881         } else { // complex
1882                 numeric re = num.real(), im = num.imag();
1883                 ex re_ex = re.is_rational() ? re : replace_with_symbol(re, repl, rev_lookup);
1884                 ex im_ex = im.is_rational() ? im : replace_with_symbol(im, repl, rev_lookup);
1885                 numex = re_ex + im_ex * replace_with_symbol(I, repl, rev_lookup);
1886         }
1887
1888         // Denominator is always a real integer (see numeric::denom())
1889         return (new lst(numex, denom()))->setflag(status_flags::dynallocated);
1890 }
1891
1892
1893 /** Fraction cancellation.
1894  *  @param n  numerator
1895  *  @param d  denominator
1896  *  @return cancelled fraction {n, d} as a list */
1897 static ex frac_cancel(const ex &n, const ex &d)
1898 {
1899         ex num = n;
1900         ex den = d;
1901         numeric pre_factor = _num1;
1902
1903 //std::clog << "frac_cancel num = " << num << ", den = " << den << std::endl;
1904
1905         // Handle trivial case where denominator is 1
1906         if (den.is_equal(_ex1))
1907                 return (new lst(num, den))->setflag(status_flags::dynallocated);
1908
1909         // Handle special cases where numerator or denominator is 0
1910         if (num.is_zero())
1911                 return (new lst(num, _ex1))->setflag(status_flags::dynallocated);
1912         if (den.expand().is_zero())
1913                 throw(std::overflow_error("frac_cancel: division by zero in frac_cancel"));
1914
1915         // Bring numerator and denominator to Z[X] by multiplying with
1916         // LCM of all coefficients' denominators
1917         numeric num_lcm = lcm_of_coefficients_denominators(num);
1918         numeric den_lcm = lcm_of_coefficients_denominators(den);
1919         num = multiply_lcm(num, num_lcm);
1920         den = multiply_lcm(den, den_lcm);
1921         pre_factor = den_lcm / num_lcm;
1922
1923         // Cancel GCD from numerator and denominator
1924         ex cnum, cden;
1925         if (gcd(num, den, &cnum, &cden, false) != _ex1) {
1926                 num = cnum;
1927                 den = cden;
1928         }
1929
1930         // Make denominator unit normal (i.e. coefficient of first symbol
1931         // as defined by get_first_symbol() is made positive)
1932         if (is_exactly_a<numeric>(den)) {
1933                 if (ex_to<numeric>(den).is_negative()) {
1934                         num *= _ex_1;
1935                         den *= _ex_1;
1936                 }
1937         } else {
1938                 ex x;
1939                 if (get_first_symbol(den, x)) {
1940                         GINAC_ASSERT(is_exactly_a<numeric>(den.unit(x)));
1941                         if (ex_to<numeric>(den.unit(x)).is_negative()) {
1942                                 num *= _ex_1;
1943                                 den *= _ex_1;
1944                         }
1945                 }
1946         }
1947
1948         // Return result as list
1949 //std::clog << " returns num = " << num << ", den = " << den << ", pre_factor = " << pre_factor << std::endl;
1950         return (new lst(num * pre_factor.numer(), den * pre_factor.denom()))->setflag(status_flags::dynallocated);
1951 }
1952
1953
1954 /** Implementation of ex::normal() for a sum. It expands terms and performs
1955  *  fractional addition.
1956  *  @see ex::normal */
1957 ex add::normal(exmap & repl, exmap & rev_lookup, int level) const
1958 {
1959         if (level == 1)
1960                 return (new lst(replace_with_symbol(*this, repl, rev_lookup), _ex1))->setflag(status_flags::dynallocated);
1961         else if (level == -max_recursion_level)
1962                 throw(std::runtime_error("max recursion level reached"));
1963
1964         // Normalize children and split each one into numerator and denominator
1965         exvector nums, dens;
1966         nums.reserve(seq.size()+1);
1967         dens.reserve(seq.size()+1);
1968         epvector::const_iterator it = seq.begin(), itend = seq.end();
1969         while (it != itend) {
1970                 ex n = ex_to<basic>(recombine_pair_to_ex(*it)).normal(repl, rev_lookup, level-1);
1971                 nums.push_back(n.op(0));
1972                 dens.push_back(n.op(1));
1973                 it++;
1974         }
1975         ex n = ex_to<numeric>(overall_coeff).normal(repl, rev_lookup, level-1);
1976         nums.push_back(n.op(0));
1977         dens.push_back(n.op(1));
1978         GINAC_ASSERT(nums.size() == dens.size());
1979
1980         // Now, nums is a vector of all numerators and dens is a vector of
1981         // all denominators
1982 //std::clog << "add::normal uses " << nums.size() << " summands:\n";
1983
1984         // Add fractions sequentially
1985         exvector::const_iterator num_it = nums.begin(), num_itend = nums.end();
1986         exvector::const_iterator den_it = dens.begin(), den_itend = dens.end();
1987 //std::clog << " num = " << *num_it << ", den = " << *den_it << std::endl;
1988         ex num = *num_it++, den = *den_it++;
1989         while (num_it != num_itend) {
1990 //std::clog << " num = " << *num_it << ", den = " << *den_it << std::endl;
1991                 ex next_num = *num_it++, next_den = *den_it++;
1992
1993                 // Trivially add sequences of fractions with identical denominators
1994                 while ((den_it != den_itend) && next_den.is_equal(*den_it)) {
1995                         next_num += *num_it;
1996                         num_it++; den_it++;
1997                 }
1998
1999                 // Additiion of two fractions, taking advantage of the fact that
2000                 // the heuristic GCD algorithm computes the cofactors at no extra cost
2001                 ex co_den1, co_den2;
2002                 ex g = gcd(den, next_den, &co_den1, &co_den2, false);
2003                 num = ((num * co_den2) + (next_num * co_den1)).expand();
2004                 den *= co_den2;         // this is the lcm(den, next_den)
2005         }
2006 //std::clog << " common denominator = " << den << std::endl;
2007
2008         // Cancel common factors from num/den
2009         return frac_cancel(num, den);
2010 }
2011
2012
2013 /** Implementation of ex::normal() for a product. It cancels common factors
2014  *  from fractions.
2015  *  @see ex::normal() */
2016 ex mul::normal(exmap & repl, exmap & rev_lookup, int level) const
2017 {
2018         if (level == 1)
2019                 return (new lst(replace_with_symbol(*this, repl, rev_lookup), _ex1))->setflag(status_flags::dynallocated);
2020         else if (level == -max_recursion_level)
2021                 throw(std::runtime_error("max recursion level reached"));
2022
2023         // Normalize children, separate into numerator and denominator
2024         exvector num; num.reserve(seq.size());
2025         exvector den; den.reserve(seq.size());
2026         ex n;
2027         epvector::const_iterator it = seq.begin(), itend = seq.end();
2028         while (it != itend) {
2029                 n = ex_to<basic>(recombine_pair_to_ex(*it)).normal(repl, rev_lookup, level-1);
2030                 num.push_back(n.op(0));
2031                 den.push_back(n.op(1));
2032                 it++;
2033         }
2034         n = ex_to<numeric>(overall_coeff).normal(repl, rev_lookup, level-1);
2035         num.push_back(n.op(0));
2036         den.push_back(n.op(1));
2037
2038         // Perform fraction cancellation
2039         return frac_cancel((new mul(num))->setflag(status_flags::dynallocated),
2040                            (new mul(den))->setflag(status_flags::dynallocated));
2041 }
2042
2043
2044 /** Implementation of ex::normal([B) for powers. It normalizes the basis,
2045  *  distributes integer exponents to numerator and denominator, and replaces
2046  *  non-integer powers by temporary symbols.
2047  *  @see ex::normal */
2048 ex power::normal(exmap & repl, exmap & rev_lookup, int level) const
2049 {
2050         if (level == 1)
2051                 return (new lst(replace_with_symbol(*this, repl, rev_lookup), _ex1))->setflag(status_flags::dynallocated);
2052         else if (level == -max_recursion_level)
2053                 throw(std::runtime_error("max recursion level reached"));
2054
2055         // Normalize basis and exponent (exponent gets reassembled)
2056         ex n_basis = ex_to<basic>(basis).normal(repl, rev_lookup, level-1);
2057         ex n_exponent = ex_to<basic>(exponent).normal(repl, rev_lookup, level-1);
2058         n_exponent = n_exponent.op(0) / n_exponent.op(1);
2059
2060         if (n_exponent.info(info_flags::integer)) {
2061
2062                 if (n_exponent.info(info_flags::positive)) {
2063
2064                         // (a/b)^n -> {a^n, b^n}
2065                         return (new lst(power(n_basis.op(0), n_exponent), power(n_basis.op(1), n_exponent)))->setflag(status_flags::dynallocated);
2066
2067                 } else if (n_exponent.info(info_flags::negative)) {
2068
2069                         // (a/b)^-n -> {b^n, a^n}
2070                         return (new lst(power(n_basis.op(1), -n_exponent), power(n_basis.op(0), -n_exponent)))->setflag(status_flags::dynallocated);
2071                 }
2072
2073         } else {
2074
2075                 if (n_exponent.info(info_flags::positive)) {
2076
2077                         // (a/b)^x -> {sym((a/b)^x), 1}
2078                         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);
2079
2080                 } else if (n_exponent.info(info_flags::negative)) {
2081
2082                         if (n_basis.op(1).is_equal(_ex1)) {
2083
2084                                 // a^-x -> {1, sym(a^x)}
2085                                 return (new lst(_ex1, replace_with_symbol(power(n_basis.op(0), -n_exponent), repl, rev_lookup)))->setflag(status_flags::dynallocated);
2086
2087                         } else {
2088
2089                                 // (a/b)^-x -> {sym((b/a)^x), 1}
2090                                 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);
2091                         }
2092                 }
2093         }
2094
2095         // (a/b)^x -> {sym((a/b)^x, 1}
2096         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);
2097 }
2098
2099
2100 /** Implementation of ex::normal() for pseries. It normalizes each coefficient
2101  *  and replaces the series by a temporary symbol.
2102  *  @see ex::normal */
2103 ex pseries::normal(exmap & repl, exmap & rev_lookup, int level) const
2104 {
2105         epvector newseq;
2106         epvector::const_iterator i = seq.begin(), end = seq.end();
2107         while (i != end) {
2108                 ex restexp = i->rest.normal();
2109                 if (!restexp.is_zero())
2110                         newseq.push_back(expair(restexp, i->coeff));
2111                 ++i;
2112         }
2113         ex n = pseries(relational(var,point), newseq);
2114         return (new lst(replace_with_symbol(n, repl, rev_lookup), _ex1))->setflag(status_flags::dynallocated);
2115 }
2116
2117
2118 /** Normalization of rational functions.
2119  *  This function converts an expression to its normal form
2120  *  "numerator/denominator", where numerator and denominator are (relatively
2121  *  prime) polynomials. Any subexpressions which are not rational functions
2122  *  (like non-rational numbers, non-integer powers or functions like sin(),
2123  *  cos() etc.) are replaced by temporary symbols which are re-substituted by
2124  *  the (normalized) subexpressions before normal() returns (this way, any
2125  *  expression can be treated as a rational function). normal() is applied
2126  *  recursively to arguments of functions etc.
2127  *
2128  *  @param level maximum depth of recursion
2129  *  @return normalized expression */
2130 ex ex::normal(int level) const
2131 {
2132         exmap repl, rev_lookup;
2133
2134         ex e = bp->normal(repl, rev_lookup, level);
2135         GINAC_ASSERT(is_a<lst>(e));
2136
2137         // Re-insert replaced symbols
2138         if (!repl.empty())
2139                 e = e.subs(repl, subs_options::no_pattern);
2140
2141         // Convert {numerator, denominator} form back to fraction
2142         return e.op(0) / e.op(1);
2143 }
2144
2145 /** Get numerator of an expression. If the expression is not of the normal
2146  *  form "numerator/denominator", it is first converted to this form and
2147  *  then the numerator is returned.
2148  *
2149  *  @see ex::normal
2150  *  @return numerator */
2151 ex ex::numer() const
2152 {
2153         exmap repl, rev_lookup;
2154
2155         ex e = bp->normal(repl, rev_lookup, 0);
2156         GINAC_ASSERT(is_a<lst>(e));
2157
2158         // Re-insert replaced symbols
2159         if (repl.empty())
2160                 return e.op(0);
2161         else
2162                 return e.op(0).subs(repl, subs_options::no_pattern);
2163 }
2164
2165 /** Get denominator of an expression. If the expression is not of the normal
2166  *  form "numerator/denominator", it is first converted to this form and
2167  *  then the denominator is returned.
2168  *
2169  *  @see ex::normal
2170  *  @return denominator */
2171 ex ex::denom() const
2172 {
2173         exmap repl, rev_lookup;
2174
2175         ex e = bp->normal(repl, rev_lookup, 0);
2176         GINAC_ASSERT(is_a<lst>(e));
2177
2178         // Re-insert replaced symbols
2179         if (repl.empty())
2180                 return e.op(1);
2181         else
2182                 return e.op(1).subs(repl, subs_options::no_pattern);
2183 }
2184
2185 /** Get numerator and denominator of an expression. If the expresison is not
2186  *  of the normal form "numerator/denominator", it is first converted to this
2187  *  form and then a list [numerator, denominator] is returned.
2188  *
2189  *  @see ex::normal
2190  *  @return a list [numerator, denominator] */
2191 ex ex::numer_denom() const
2192 {
2193         exmap repl, rev_lookup;
2194
2195         ex e = bp->normal(repl, rev_lookup, 0);
2196         GINAC_ASSERT(is_a<lst>(e));
2197
2198         // Re-insert replaced symbols
2199         if (repl.empty())
2200                 return e;
2201         else
2202                 return e.subs(repl, subs_options::no_pattern);
2203 }
2204
2205
2206 /** Rationalization of non-rational functions.
2207  *  This function converts a general expression to a rational function
2208  *  by replacing all non-rational subexpressions (like non-rational numbers,
2209  *  non-integer powers or functions like sin(), cos() etc.) to temporary
2210  *  symbols. This makes it possible to use functions like gcd() and divide()
2211  *  on non-rational functions by applying to_rational() on the arguments,
2212  *  calling the desired function and re-substituting the temporary symbols
2213  *  in the result. To make the last step possible, all temporary symbols and
2214  *  their associated expressions are collected in the map specified by the
2215  *  repl parameter, ready to be passed as an argument to ex::subs().
2216  *
2217  *  @param repl collects all temporary symbols and their replacements
2218  *  @return rationalized expression */
2219 ex ex::to_rational(exmap & repl) const
2220 {
2221         return bp->to_rational(repl);
2222 }
2223
2224 // GiNaC 1.1 compatibility function
2225 ex ex::to_rational(lst & repl_lst) const
2226 {
2227         // Convert lst to exmap
2228         exmap m;
2229         for (lst::const_iterator it = repl_lst.begin(); it != repl_lst.end(); ++it)
2230                 m.insert(std::make_pair(it->op(0), it->op(1)));
2231
2232         ex ret = bp->to_rational(m);
2233
2234         // Convert exmap back to lst
2235         repl_lst.remove_all();
2236         for (exmap::const_iterator it = m.begin(); it != m.end(); ++it)
2237                 repl_lst.append(it->first == it->second);
2238
2239         return ret;
2240 }
2241
2242 ex ex::to_polynomial(exmap & repl) const
2243 {
2244         return bp->to_polynomial(repl);
2245 }
2246
2247 // GiNaC 1.1 compatibility function
2248 ex ex::to_polynomial(lst & repl_lst) const
2249 {
2250         // Convert lst to exmap
2251         exmap m;
2252         for (lst::const_iterator it = repl_lst.begin(); it != repl_lst.end(); ++it)
2253                 m.insert(std::make_pair(it->op(0), it->op(1)));
2254
2255         ex ret = bp->to_polynomial(m);
2256
2257         // Convert exmap back to lst
2258         repl_lst.remove_all();
2259         for (exmap::const_iterator it = m.begin(); it != m.end(); ++it)
2260                 repl_lst.append(it->first == it->second);
2261
2262         return ret;
2263 }
2264
2265 /** Default implementation of ex::to_rational(). This replaces the object with
2266  *  a temporary symbol. */
2267 ex basic::to_rational(exmap & repl) const
2268 {
2269         return replace_with_symbol(*this, repl);
2270 }
2271
2272 ex basic::to_polynomial(exmap & repl) const
2273 {
2274         return replace_with_symbol(*this, repl);
2275 }
2276
2277
2278 /** Implementation of ex::to_rational() for symbols. This returns the
2279  *  unmodified symbol. */
2280 ex symbol::to_rational(exmap & repl) const
2281 {
2282         return *this;
2283 }
2284
2285 /** Implementation of ex::to_polynomial() for symbols. This returns the
2286  *  unmodified symbol. */
2287 ex symbol::to_polynomial(exmap & repl) const
2288 {
2289         return *this;
2290 }
2291
2292
2293 /** Implementation of ex::to_rational() for a numeric. It splits complex
2294  *  numbers into re+I*im and replaces I and non-rational real numbers with a
2295  *  temporary symbol. */
2296 ex numeric::to_rational(exmap & repl) const
2297 {
2298         if (is_real()) {
2299                 if (!is_rational())
2300                         return replace_with_symbol(*this, repl);
2301         } else { // complex
2302                 numeric re = real();
2303                 numeric im = imag();
2304                 ex re_ex = re.is_rational() ? re : replace_with_symbol(re, repl);
2305                 ex im_ex = im.is_rational() ? im : replace_with_symbol(im, repl);
2306                 return re_ex + im_ex * replace_with_symbol(I, repl);
2307         }
2308         return *this;
2309 }
2310
2311 /** Implementation of ex::to_polynomial() for a numeric. It splits complex
2312  *  numbers into re+I*im and replaces I and non-integer real numbers with a
2313  *  temporary symbol. */
2314 ex numeric::to_polynomial(exmap & repl) const
2315 {
2316         if (is_real()) {
2317                 if (!is_integer())
2318                         return replace_with_symbol(*this, repl);
2319         } else { // complex
2320                 numeric re = real();
2321                 numeric im = imag();
2322                 ex re_ex = re.is_integer() ? re : replace_with_symbol(re, repl);
2323                 ex im_ex = im.is_integer() ? im : replace_with_symbol(im, repl);
2324                 return re_ex + im_ex * replace_with_symbol(I, repl);
2325         }
2326         return *this;
2327 }
2328
2329
2330 /** Implementation of ex::to_rational() for powers. It replaces non-integer
2331  *  powers by temporary symbols. */
2332 ex power::to_rational(exmap & repl) const
2333 {
2334         if (exponent.info(info_flags::integer))
2335                 return power(basis.to_rational(repl), exponent);
2336         else
2337                 return replace_with_symbol(*this, repl);
2338 }
2339
2340 /** Implementation of ex::to_polynomial() for powers. It replaces non-posint
2341  *  powers by temporary symbols. */
2342 ex power::to_polynomial(exmap & repl) const
2343 {
2344         if (exponent.info(info_flags::posint))
2345                 return power(basis.to_rational(repl), exponent);
2346         else
2347                 return replace_with_symbol(*this, repl);
2348 }
2349
2350
2351 /** Implementation of ex::to_rational() for expairseqs. */
2352 ex expairseq::to_rational(exmap & repl) const
2353 {
2354         epvector s;
2355         s.reserve(seq.size());
2356         epvector::const_iterator i = seq.begin(), end = seq.end();
2357         while (i != end) {
2358                 s.push_back(split_ex_to_pair(recombine_pair_to_ex(*i).to_rational(repl)));
2359                 ++i;
2360         }
2361         ex oc = overall_coeff.to_rational(repl);
2362         if (oc.info(info_flags::numeric))
2363                 return thisexpairseq(s, overall_coeff);
2364         else
2365                 s.push_back(combine_ex_with_coeff_to_pair(oc, _ex1));
2366         return thisexpairseq(s, default_overall_coeff());
2367 }
2368
2369 /** Implementation of ex::to_polynomial() for expairseqs. */
2370 ex expairseq::to_polynomial(exmap & repl) const
2371 {
2372         epvector s;
2373         s.reserve(seq.size());
2374         epvector::const_iterator i = seq.begin(), end = seq.end();
2375         while (i != end) {
2376                 s.push_back(split_ex_to_pair(recombine_pair_to_ex(*i).to_polynomial(repl)));
2377                 ++i;
2378         }
2379         ex oc = overall_coeff.to_polynomial(repl);
2380         if (oc.info(info_flags::numeric))
2381                 return thisexpairseq(s, overall_coeff);
2382         else
2383                 s.push_back(combine_ex_with_coeff_to_pair(oc, _ex1));
2384         return thisexpairseq(s, default_overall_coeff());
2385 }
2386
2387
2388 /** Remove the common factor in the terms of a sum 'e' by calculating the GCD,
2389  *  and multiply it into the expression 'factor' (which needs to be initialized
2390  *  to 1, unless you're accumulating factors). */
2391 static ex find_common_factor(const ex & e, ex & factor, exmap & repl)
2392 {
2393         if (is_exactly_a<add>(e)) {
2394
2395                 size_t num = e.nops();
2396                 exvector terms; terms.reserve(num);
2397                 ex gc;
2398
2399                 // Find the common GCD
2400                 for (size_t i=0; i<num; i++) {
2401                         ex x = e.op(i).to_polynomial(repl);
2402
2403                         if (is_exactly_a<add>(x) || is_exactly_a<mul>(x)) {
2404                                 ex f = 1;
2405                                 x = find_common_factor(x, f, repl);
2406                                 x *= f;
2407                         }
2408
2409                         if (i == 0)
2410                                 gc = x;
2411                         else
2412                                 gc = gcd(gc, x);
2413
2414                         terms.push_back(x);
2415                 }
2416
2417                 if (gc.is_equal(_ex1))
2418                         return e;
2419
2420                 // The GCD is the factor we pull out
2421                 factor *= gc;
2422
2423                 // Now divide all terms by the GCD
2424                 for (size_t i=0; i<num; i++) {
2425                         ex x;
2426
2427                         // Try to avoid divide() because it expands the polynomial
2428                         ex &t = terms[i];
2429                         if (is_exactly_a<mul>(t)) {
2430                                 for (size_t j=0; j<t.nops(); j++) {
2431                                         if (t.op(j).is_equal(gc)) {
2432                                                 exvector v; v.reserve(t.nops());
2433                                                 for (size_t k=0; k<t.nops(); k++) {
2434                                                         if (k == j)
2435                                                                 v.push_back(_ex1);
2436                                                         else
2437                                                                 v.push_back(t.op(k));
2438                                                 }
2439                                                 t = (new mul(v))->setflag(status_flags::dynallocated);
2440                                                 goto term_done;
2441                                         }
2442                                 }
2443                         }
2444
2445                         divide(t, gc, x);
2446                         t = x;
2447 term_done:      ;
2448                 }
2449                 return (new add(terms))->setflag(status_flags::dynallocated);
2450
2451         } else if (is_exactly_a<mul>(e)) {
2452
2453                 size_t num = e.nops();
2454                 exvector v; v.reserve(num);
2455
2456                 for (size_t i=0; i<num; i++)
2457                         v.push_back(find_common_factor(e.op(i), factor, repl));
2458
2459                 return (new mul(v))->setflag(status_flags::dynallocated);
2460
2461         } else if (is_exactly_a<power>(e)) {
2462
2463                 return e.to_polynomial(repl);
2464
2465         } else
2466                 return e;
2467 }
2468
2469
2470 /** Collect common factors in sums. This converts expressions like
2471  *  'a*(b*x+b*y)' to 'a*b*(x+y)'. */
2472 ex collect_common_factors(const ex & e)
2473 {
2474         if (is_exactly_a<add>(e) || is_exactly_a<mul>(e)) {
2475
2476                 exmap repl;
2477                 ex factor = 1;
2478                 ex r = find_common_factor(e, factor, repl);
2479                 return factor.subs(repl, subs_options::no_pattern) * r.subs(repl, subs_options::no_pattern);
2480
2481         } else
2482                 return e;
2483 }
2484
2485
2486 /** Resultant of two expressions e1,e2 with respect to symbol s.
2487  *  Method: Compute determinant of Sylvester matrix of e1,e2,s.  */
2488 ex resultant(const ex & e1, const ex & e2, const ex & s)
2489 {
2490         const ex ee1 = e1.expand();
2491         const ex ee2 = e2.expand();
2492         if (!ee1.info(info_flags::polynomial) ||
2493             !ee2.info(info_flags::polynomial))
2494                 throw(std::runtime_error("resultant(): arguments must be polynomials"));
2495
2496         const int h1 = ee1.degree(s);
2497         const int l1 = ee1.ldegree(s);
2498         const int h2 = ee2.degree(s);
2499         const int l2 = ee2.ldegree(s);
2500
2501         const int msize = h1 + h2;
2502         matrix m(msize, msize);
2503
2504         for (int l = h1; l >= l1; --l) {
2505                 const ex e = ee1.coeff(s, l);
2506                 for (int k = 0; k < h2; ++k)
2507                         m(k, k+h1-l) = e;
2508         }
2509         for (int l = h2; l >= l2; --l) {
2510                 const ex e = ee2.coeff(s, l);
2511                 for (int k = 0; k < h1; ++k)
2512                         m(k+h2, k+h2-l) = e;
2513         }
2514
2515         return m.determinant();
2516 }
2517
2518
2519 } // namespace GiNaC