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