]> www.ginac.de Git - ginac.git/blob - ginac/normal.cpp
lst now provides (read-only) iterator types, the use of which makes iterating
[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-2003 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  pointer to first symbol found (returned)
93  *  @return "false" if no symbol was found, "true" otherwise */
94 static bool get_first_symbol(const ex &e, const symbol *&x)
95 {
96         if (is_a<symbol>(e)) {
97                 x = &ex_to<symbol>(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         /** Pointer to symbol */
123         const symbol *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 symbol *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->compare(*s) == 0)  // 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(&ex_to<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.
302  *
303  *  @param e  expanded polynomial
304  *  @return integer content */
305 numeric ex::integer_content(void) const
306 {
307         GINAC_ASSERT(bp!=0);
308         return bp->integer_content();
309 }
310
311 numeric basic::integer_content(void) const
312 {
313         return _num1;
314 }
315
316 numeric numeric::integer_content(void) const
317 {
318         return abs(*this);
319 }
320
321 numeric add::integer_content(void) const
322 {
323         epvector::const_iterator it = seq.begin();
324         epvector::const_iterator itend = seq.end();
325         numeric c = _num0;
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), c);
330                 it++;
331         }
332         GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
333         c = gcd(ex_to<numeric>(overall_coeff),c);
334         return c;
335 }
336
337 numeric mul::integer_content(void) const
338 {
339 #ifdef DO_GINAC_ASSERT
340         epvector::const_iterator it = seq.begin();
341         epvector::const_iterator itend = seq.end();
342         while (it != itend) {
343                 GINAC_ASSERT(!is_exactly_a<numeric>(recombine_pair_to_ex(*it)));
344                 ++it;
345         }
346 #endif // def DO_GINAC_ASSERT
347         GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
348         return abs(ex_to<numeric>(overall_coeff));
349 }
350
351
352 /*
353  *  Polynomial quotients and remainders
354  */
355
356 /** Quotient q(x) of polynomials a(x) and b(x) in Q[x].
357  *  It satisfies a(x)=b(x)*q(x)+r(x).
358  *
359  *  @param a  first polynomial in x (dividend)
360  *  @param b  second polynomial in x (divisor)
361  *  @param x  a and b are polynomials in x
362  *  @param check_args  check whether a and b are polynomials with rational
363  *         coefficients (defaults to "true")
364  *  @return quotient of a and b in Q[x] */
365 ex quo(const ex &a, const ex &b, const symbol &x, bool check_args)
366 {
367         if (b.is_zero())
368                 throw(std::overflow_error("quo: division by zero"));
369         if (is_exactly_a<numeric>(a) && is_exactly_a<numeric>(b))
370                 return a / b;
371 #if FAST_COMPARE
372         if (a.is_equal(b))
373                 return _ex1;
374 #endif
375         if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
376                 throw(std::invalid_argument("quo: arguments must be polynomials over the rationals"));
377
378         // Polynomial long division
379         ex r = a.expand();
380         if (r.is_zero())
381                 return r;
382         int bdeg = b.degree(x);
383         int rdeg = r.degree(x);
384         ex blcoeff = b.expand().coeff(x, bdeg);
385         bool blcoeff_is_numeric = is_exactly_a<numeric>(blcoeff);
386         exvector v; v.reserve(std::max(rdeg - bdeg + 1, 0));
387         while (rdeg >= bdeg) {
388                 ex term, rcoeff = r.coeff(x, rdeg);
389                 if (blcoeff_is_numeric)
390                         term = rcoeff / blcoeff;
391                 else {
392                         if (!divide(rcoeff, blcoeff, term, false))
393                                 return (new fail())->setflag(status_flags::dynallocated);
394                 }
395                 term *= power(x, rdeg - bdeg);
396                 v.push_back(term);
397                 r -= (term * b).expand();
398                 if (r.is_zero())
399                         break;
400                 rdeg = r.degree(x);
401         }
402         return (new add(v))->setflag(status_flags::dynallocated);
403 }
404
405
406 /** Remainder r(x) of polynomials a(x) and b(x) in Q[x].
407  *  It satisfies a(x)=b(x)*q(x)+r(x).
408  *
409  *  @param a  first polynomial in x (dividend)
410  *  @param b  second polynomial in x (divisor)
411  *  @param x  a and b are polynomials in x
412  *  @param check_args  check whether a and b are polynomials with rational
413  *         coefficients (defaults to "true")
414  *  @return remainder of a(x) and b(x) in Q[x] */
415 ex rem(const ex &a, const ex &b, const symbol &x, bool check_args)
416 {
417         if (b.is_zero())
418                 throw(std::overflow_error("rem: division by zero"));
419         if (is_exactly_a<numeric>(a)) {
420                 if  (is_exactly_a<numeric>(b))
421                         return _ex0;
422                 else
423                         return a;
424         }
425 #if FAST_COMPARE
426         if (a.is_equal(b))
427                 return _ex0;
428 #endif
429         if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
430                 throw(std::invalid_argument("rem: arguments must be polynomials over the rationals"));
431
432         // Polynomial long division
433         ex r = a.expand();
434         if (r.is_zero())
435                 return r;
436         int bdeg = b.degree(x);
437         int rdeg = r.degree(x);
438         ex blcoeff = b.expand().coeff(x, bdeg);
439         bool blcoeff_is_numeric = is_exactly_a<numeric>(blcoeff);
440         while (rdeg >= bdeg) {
441                 ex term, rcoeff = r.coeff(x, rdeg);
442                 if (blcoeff_is_numeric)
443                         term = rcoeff / blcoeff;
444                 else {
445                         if (!divide(rcoeff, blcoeff, term, false))
446                                 return (new fail())->setflag(status_flags::dynallocated);
447                 }
448                 term *= power(x, rdeg - bdeg);
449                 r -= (term * b).expand();
450                 if (r.is_zero())
451                         break;
452                 rdeg = r.degree(x);
453         }
454         return r;
455 }
456
457
458 /** Decompose rational function a(x)=N(x)/D(x) into P(x)+n(x)/D(x)
459  *  with degree(n, x) < degree(D, x).
460  *
461  *  @param a rational function in x
462  *  @param x a is a function of x
463  *  @return decomposed function. */
464 ex decomp_rational(const ex &a, const symbol &x)
465 {
466         ex nd = numer_denom(a);
467         ex numer = nd.op(0), denom = nd.op(1);
468         ex q = quo(numer, denom, x);
469         if (is_exactly_a<fail>(q))
470                 return a;
471         else
472                 return q + rem(numer, denom, x) / denom;
473 }
474
475
476 /** Pseudo-remainder of polynomials a(x) and b(x) in Q[x].
477  *
478  *  @param a  first polynomial in x (dividend)
479  *  @param b  second polynomial in x (divisor)
480  *  @param x  a and b are polynomials in x
481  *  @param check_args  check whether a and b are polynomials with rational
482  *         coefficients (defaults to "true")
483  *  @return pseudo-remainder of a(x) and b(x) in Q[x] */
484 ex prem(const ex &a, const ex &b, const symbol &x, bool check_args)
485 {
486         if (b.is_zero())
487                 throw(std::overflow_error("prem: division by zero"));
488         if (is_exactly_a<numeric>(a)) {
489                 if (is_exactly_a<numeric>(b))
490                         return _ex0;
491                 else
492                         return b;
493         }
494         if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
495                 throw(std::invalid_argument("prem: arguments must be polynomials over the rationals"));
496
497         // Polynomial long division
498         ex r = a.expand();
499         ex eb = b.expand();
500         int rdeg = r.degree(x);
501         int bdeg = eb.degree(x);
502         ex blcoeff;
503         if (bdeg <= rdeg) {
504                 blcoeff = eb.coeff(x, bdeg);
505                 if (bdeg == 0)
506                         eb = _ex0;
507                 else
508                         eb -= blcoeff * power(x, bdeg);
509         } else
510                 blcoeff = _ex1;
511
512         int delta = rdeg - bdeg + 1, i = 0;
513         while (rdeg >= bdeg && !r.is_zero()) {
514                 ex rlcoeff = r.coeff(x, rdeg);
515                 ex term = (power(x, rdeg - bdeg) * eb * rlcoeff).expand();
516                 if (rdeg == 0)
517                         r = _ex0;
518                 else
519                         r -= rlcoeff * power(x, rdeg);
520                 r = (blcoeff * r).expand() - term;
521                 rdeg = r.degree(x);
522                 i++;
523         }
524         return power(blcoeff, delta - i) * r;
525 }
526
527
528 /** Sparse pseudo-remainder of polynomials a(x) and b(x) in Q[x].
529  *
530  *  @param a  first polynomial in x (dividend)
531  *  @param b  second polynomial in x (divisor)
532  *  @param x  a and b are polynomials in x
533  *  @param check_args  check whether a and b are polynomials with rational
534  *         coefficients (defaults to "true")
535  *  @return sparse pseudo-remainder of a(x) and b(x) in Q[x] */
536 ex sprem(const ex &a, const ex &b, const symbol &x, bool check_args)
537 {
538         if (b.is_zero())
539                 throw(std::overflow_error("prem: division by zero"));
540         if (is_exactly_a<numeric>(a)) {
541                 if (is_exactly_a<numeric>(b))
542                         return _ex0;
543                 else
544                         return b;
545         }
546         if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
547                 throw(std::invalid_argument("prem: arguments must be polynomials over the rationals"));
548
549         // Polynomial long division
550         ex r = a.expand();
551         ex eb = b.expand();
552         int rdeg = r.degree(x);
553         int bdeg = eb.degree(x);
554         ex blcoeff;
555         if (bdeg <= rdeg) {
556                 blcoeff = eb.coeff(x, bdeg);
557                 if (bdeg == 0)
558                         eb = _ex0;
559                 else
560                         eb -= blcoeff * power(x, bdeg);
561         } else
562                 blcoeff = _ex1;
563
564         while (rdeg >= bdeg && !r.is_zero()) {
565                 ex rlcoeff = r.coeff(x, rdeg);
566                 ex term = (power(x, rdeg - bdeg) * eb * rlcoeff).expand();
567                 if (rdeg == 0)
568                         r = _ex0;
569                 else
570                         r -= rlcoeff * power(x, rdeg);
571                 r = (blcoeff * r).expand() - term;
572                 rdeg = r.degree(x);
573         }
574         return r;
575 }
576
577
578 /** Exact polynomial division of a(X) by b(X) in Q[X].
579  *  
580  *  @param a  first multivariate polynomial (dividend)
581  *  @param b  second multivariate polynomial (divisor)
582  *  @param q  quotient (returned)
583  *  @param check_args  check whether a and b are polynomials with rational
584  *         coefficients (defaults to "true")
585  *  @return "true" when exact division succeeds (quotient returned in q),
586  *          "false" otherwise (q left untouched) */
587 bool divide(const ex &a, const ex &b, ex &q, bool check_args)
588 {
589         if (b.is_zero())
590                 throw(std::overflow_error("divide: division by zero"));
591         if (a.is_zero()) {
592                 q = _ex0;
593                 return true;
594         }
595         if (is_exactly_a<numeric>(b)) {
596                 q = a / b;
597                 return true;
598         } else if (is_exactly_a<numeric>(a))
599                 return false;
600 #if FAST_COMPARE
601         if (a.is_equal(b)) {
602                 q = _ex1;
603                 return true;
604         }
605 #endif
606         if (check_args && (!a.info(info_flags::rational_polynomial) ||
607                            !b.info(info_flags::rational_polynomial)))
608                 throw(std::invalid_argument("divide: arguments must be polynomials over the rationals"));
609
610         // Find first symbol
611         const symbol *x;
612         if (!get_first_symbol(a, x) && !get_first_symbol(b, x))
613                 throw(std::invalid_argument("invalid expression in divide()"));
614
615         // Polynomial long division (recursive)
616         ex r = a.expand();
617         if (r.is_zero()) {
618                 q = _ex0;
619                 return true;
620         }
621         int bdeg = b.degree(*x);
622         int rdeg = r.degree(*x);
623         ex blcoeff = b.expand().coeff(*x, bdeg);
624         bool blcoeff_is_numeric = is_exactly_a<numeric>(blcoeff);
625         exvector v; v.reserve(std::max(rdeg - bdeg + 1, 0));
626         while (rdeg >= bdeg) {
627                 ex term, rcoeff = r.coeff(*x, rdeg);
628                 if (blcoeff_is_numeric)
629                         term = rcoeff / blcoeff;
630                 else
631                         if (!divide(rcoeff, blcoeff, term, false))
632                                 return false;
633                 term *= power(*x, rdeg - bdeg);
634                 v.push_back(term);
635                 r -= (term * b).expand();
636                 if (r.is_zero()) {
637                         q = (new add(v))->setflag(status_flags::dynallocated);
638                         return true;
639                 }
640                 rdeg = r.degree(*x);
641         }
642         return false;
643 }
644
645
646 #if USE_REMEMBER
647 /*
648  *  Remembering
649  */
650
651 typedef std::pair<ex, ex> ex2;
652 typedef std::pair<ex, bool> exbool;
653
654 struct ex2_less {
655         bool operator() (const ex2 &p, const ex2 &q) const 
656         {
657                 int cmp = p.first.compare(q.first);
658                 return ((cmp<0) || (!(cmp>0) && p.second.compare(q.second)<0));
659         }
660 };
661
662 typedef std::map<ex2, exbool, ex2_less> ex2_exbool_remember;
663 #endif
664
665
666 /** Exact polynomial division of a(X) by b(X) in Z[X].
667  *  This functions works like divide() but the input and output polynomials are
668  *  in Z[X] instead of Q[X] (i.e. they have integer coefficients). Unlike
669  *  divide(), it doesnĀ“t check whether the input polynomials really are integer
670  *  polynomials, so be careful of what you pass in. Also, you have to run
671  *  get_symbol_stats() over the input polynomials before calling this function
672  *  and pass an iterator to the first element of the sym_desc vector. This
673  *  function is used internally by the heur_gcd().
674  *  
675  *  @param a  first multivariate polynomial (dividend)
676  *  @param b  second multivariate polynomial (divisor)
677  *  @param q  quotient (returned)
678  *  @param var  iterator to first element of vector of sym_desc structs
679  *  @return "true" when exact division succeeds (the quotient is returned in
680  *          q), "false" otherwise.
681  *  @see get_symbol_stats, heur_gcd */
682 static bool divide_in_z(const ex &a, const ex &b, ex &q, sym_desc_vec::const_iterator var)
683 {
684         q = _ex0;
685         if (b.is_zero())
686                 throw(std::overflow_error("divide_in_z: division by zero"));
687         if (b.is_equal(_ex1)) {
688                 q = a;
689                 return true;
690         }
691         if (is_exactly_a<numeric>(a)) {
692                 if (is_exactly_a<numeric>(b)) {
693                         q = a / b;
694                         return q.info(info_flags::integer);
695                 } else
696                         return false;
697         }
698 #if FAST_COMPARE
699         if (a.is_equal(b)) {
700                 q = _ex1;
701                 return true;
702         }
703 #endif
704
705 #if USE_REMEMBER
706         // Remembering
707         static ex2_exbool_remember dr_remember;
708         ex2_exbool_remember::const_iterator remembered = dr_remember.find(ex2(a, b));
709         if (remembered != dr_remember.end()) {
710                 q = remembered->second.first;
711                 return remembered->second.second;
712         }
713 #endif
714
715         // Main symbol
716         const symbol *x = var->sym;
717
718         // Compare degrees
719         int adeg = a.degree(*x), bdeg = b.degree(*x);
720         if (bdeg > adeg)
721                 return false;
722
723 #if USE_TRIAL_DIVISION
724
725         // Trial division with polynomial interpolation
726         int i, k;
727
728         // Compute values at evaluation points 0..adeg
729         vector<numeric> alpha; alpha.reserve(adeg + 1);
730         exvector u; u.reserve(adeg + 1);
731         numeric point = _num0;
732         ex c;
733         for (i=0; i<=adeg; i++) {
734                 ex bs = b.subs(*x == point);
735                 while (bs.is_zero()) {
736                         point += _num1;
737                         bs = b.subs(*x == point);
738                 }
739                 if (!divide_in_z(a.subs(*x == point), bs, c, var+1))
740                         return false;
741                 alpha.push_back(point);
742                 u.push_back(c);
743                 point += _num1;
744         }
745
746         // Compute inverses
747         vector<numeric> rcp; rcp.reserve(adeg + 1);
748         rcp.push_back(_num0);
749         for (k=1; k<=adeg; k++) {
750                 numeric product = alpha[k] - alpha[0];
751                 for (i=1; i<k; i++)
752                         product *= alpha[k] - alpha[i];
753                 rcp.push_back(product.inverse());
754         }
755
756         // Compute Newton coefficients
757         exvector v; v.reserve(adeg + 1);
758         v.push_back(u[0]);
759         for (k=1; k<=adeg; k++) {
760                 ex temp = v[k - 1];
761                 for (i=k-2; i>=0; i--)
762                         temp = temp * (alpha[k] - alpha[i]) + v[i];
763                 v.push_back((u[k] - temp) * rcp[k]);
764         }
765
766         // Convert from Newton form to standard form
767         c = v[adeg];
768         for (k=adeg-1; k>=0; k--)
769                 c = c * (*x - alpha[k]) + v[k];
770
771         if (c.degree(*x) == (adeg - bdeg)) {
772                 q = c.expand();
773                 return true;
774         } else
775                 return false;
776
777 #else
778
779         // Polynomial long division (recursive)
780         ex r = a.expand();
781         if (r.is_zero())
782                 return true;
783         int rdeg = adeg;
784         ex eb = b.expand();
785         ex blcoeff = eb.coeff(*x, bdeg);
786         exvector v; v.reserve(std::max(rdeg - bdeg + 1, 0));
787         while (rdeg >= bdeg) {
788                 ex term, rcoeff = r.coeff(*x, rdeg);
789                 if (!divide_in_z(rcoeff, blcoeff, term, var+1))
790                         break;
791                 term = (term * power(*x, rdeg - bdeg)).expand();
792                 v.push_back(term);
793                 r -= (term * eb).expand();
794                 if (r.is_zero()) {
795                         q = (new add(v))->setflag(status_flags::dynallocated);
796 #if USE_REMEMBER
797                         dr_remember[ex2(a, b)] = exbool(q, true);
798 #endif
799                         return true;
800                 }
801                 rdeg = r.degree(*x);
802         }
803 #if USE_REMEMBER
804         dr_remember[ex2(a, b)] = exbool(q, false);
805 #endif
806         return false;
807
808 #endif
809 }
810
811
812 /*
813  *  Separation of unit part, content part and primitive part of polynomials
814  */
815
816 /** Compute unit part (= sign of leading coefficient) of a multivariate
817  *  polynomial in Z[x]. The product of unit part, content part, and primitive
818  *  part is the polynomial itself.
819  *
820  *  @param x  variable in which to compute the unit part
821  *  @return unit part
822  *  @see ex::content, ex::primpart */
823 ex ex::unit(const symbol &x) const
824 {
825         ex c = expand().lcoeff(x);
826         if (is_exactly_a<numeric>(c))
827                 return c < _ex0 ? _ex_1 : _ex1;
828         else {
829                 const symbol *y;
830                 if (get_first_symbol(c, y))
831                         return c.unit(*y);
832                 else
833                         throw(std::invalid_argument("invalid expression in unit()"));
834         }
835 }
836
837
838 /** Compute content part (= unit normal GCD of all coefficients) of a
839  *  multivariate polynomial in Z[x].  The product of unit part, content part,
840  *  and primitive part is the polynomial itself.
841  *
842  *  @param x  variable in which to compute the content part
843  *  @return content part
844  *  @see ex::unit, ex::primpart */
845 ex ex::content(const symbol &x) const
846 {
847         if (is_zero())
848                 return _ex0;
849         if (is_exactly_a<numeric>(*this))
850                 return info(info_flags::negative) ? -*this : *this;
851         ex e = expand();
852         if (e.is_zero())
853                 return _ex0;
854
855         // First, try the integer content
856         ex c = e.integer_content();
857         ex r = e / c;
858         ex lcoeff = r.lcoeff(x);
859         if (lcoeff.info(info_flags::integer))
860                 return c;
861
862         // GCD of all coefficients
863         int deg = e.degree(x);
864         int ldeg = e.ldegree(x);
865         if (deg == ldeg)
866                 return e.lcoeff(x) / e.unit(x);
867         c = _ex0;
868         for (int i=ldeg; i<=deg; i++)
869                 c = gcd(e.coeff(x, i), c, NULL, NULL, false);
870         return c;
871 }
872
873
874 /** Compute primitive part of a multivariate polynomial in Z[x].
875  *  The product of unit part, content part, and primitive part is the
876  *  polynomial itself.
877  *
878  *  @param x  variable in which to compute the primitive part
879  *  @return primitive part
880  *  @see ex::unit, ex::content */
881 ex ex::primpart(const symbol &x) const
882 {
883         if (is_zero())
884                 return _ex0;
885         if (is_exactly_a<numeric>(*this))
886                 return _ex1;
887
888         ex c = content(x);
889         if (c.is_zero())
890                 return _ex0;
891         ex u = unit(x);
892         if (is_exactly_a<numeric>(c))
893                 return *this / (c * u);
894         else
895                 return quo(*this, c * u, x, false);
896 }
897
898
899 /** Compute primitive part of a multivariate polynomial in Z[x] when the
900  *  content part is already known. This function is faster in computing the
901  *  primitive part than the previous function.
902  *
903  *  @param x  variable in which to compute the primitive part
904  *  @param c  previously computed content part
905  *  @return primitive part */
906 ex ex::primpart(const symbol &x, const ex &c) const
907 {
908         if (is_zero())
909                 return _ex0;
910         if (c.is_zero())
911                 return _ex0;
912         if (is_exactly_a<numeric>(*this))
913                 return _ex1;
914
915         ex u = unit(x);
916         if (is_exactly_a<numeric>(c))
917                 return *this / (c * u);
918         else
919                 return quo(*this, c * u, x, false);
920 }
921
922
923 /*
924  *  GCD of multivariate polynomials
925  */
926
927 /** Compute GCD of multivariate polynomials using the subresultant PRS
928  *  algorithm. This function is used internally by gcd().
929  *
930  *  @param a   first multivariate polynomial
931  *  @param b   second multivariate polynomial
932  *  @param var iterator to first element of vector of sym_desc structs
933  *  @return the GCD as a new expression
934  *  @see gcd */
935
936 static ex sr_gcd(const ex &a, const ex &b, sym_desc_vec::const_iterator var)
937 {
938 #if STATISTICS
939         sr_gcd_called++;
940 #endif
941
942         // The first symbol is our main variable
943         const symbol &x = *(var->sym);
944
945         // Sort c and d so that c has higher degree
946         ex c, d;
947         int adeg = a.degree(x), bdeg = b.degree(x);
948         int cdeg, ddeg;
949         if (adeg >= bdeg) {
950                 c = a;
951                 d = b;
952                 cdeg = adeg;
953                 ddeg = bdeg;
954         } else {
955                 c = b;
956                 d = a;
957                 cdeg = bdeg;
958                 ddeg = adeg;
959         }
960
961         // Remove content from c and d, to be attached to GCD later
962         ex cont_c = c.content(x);
963         ex cont_d = d.content(x);
964         ex gamma = gcd(cont_c, cont_d, NULL, NULL, false);
965         if (ddeg == 0)
966                 return gamma;
967         c = c.primpart(x, cont_c);
968         d = d.primpart(x, cont_d);
969
970         // First element of subresultant sequence
971         ex r = _ex0, ri = _ex1, psi = _ex1;
972         int delta = cdeg - ddeg;
973
974         for (;;) {
975
976                 // Calculate polynomial pseudo-remainder
977                 r = prem(c, d, x, false);
978                 if (r.is_zero())
979                         return gamma * d.primpart(x);
980
981                 c = d;
982                 cdeg = ddeg;
983                 if (!divide_in_z(r, ri * pow(psi, delta), d, var))
984                         throw(std::runtime_error("invalid expression in sr_gcd(), division failed"));
985                 ddeg = d.degree(x);
986                 if (ddeg == 0) {
987                         if (is_exactly_a<numeric>(r))
988                                 return gamma;
989                         else
990                                 return gamma * r.primpart(x);
991                 }
992
993                 // Next element of subresultant sequence
994                 ri = c.expand().lcoeff(x);
995                 if (delta == 1)
996                         psi = ri;
997                 else if (delta)
998                         divide_in_z(pow(ri, delta), pow(psi, delta-1), psi, var+1);
999                 delta = cdeg - ddeg;
1000         }
1001 }
1002
1003
1004 /** Return maximum (absolute value) coefficient of a polynomial.
1005  *  This function is used internally by heur_gcd().
1006  *
1007  *  @param e  expanded multivariate polynomial
1008  *  @return maximum coefficient
1009  *  @see heur_gcd */
1010 numeric ex::max_coefficient(void) const
1011 {
1012         GINAC_ASSERT(bp!=0);
1013         return bp->max_coefficient();
1014 }
1015
1016 /** Implementation ex::max_coefficient().
1017  *  @see heur_gcd */
1018 numeric basic::max_coefficient(void) const
1019 {
1020         return _num1;
1021 }
1022
1023 numeric numeric::max_coefficient(void) const
1024 {
1025         return abs(*this);
1026 }
1027
1028 numeric add::max_coefficient(void) const
1029 {
1030         epvector::const_iterator it = seq.begin();
1031         epvector::const_iterator itend = seq.end();
1032         GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
1033         numeric cur_max = abs(ex_to<numeric>(overall_coeff));
1034         while (it != itend) {
1035                 numeric a;
1036                 GINAC_ASSERT(!is_exactly_a<numeric>(it->rest));
1037                 a = abs(ex_to<numeric>(it->coeff));
1038                 if (a > cur_max)
1039                         cur_max = a;
1040                 it++;
1041         }
1042         return cur_max;
1043 }
1044
1045 numeric mul::max_coefficient(void) const
1046 {
1047 #ifdef DO_GINAC_ASSERT
1048         epvector::const_iterator it = seq.begin();
1049         epvector::const_iterator itend = seq.end();
1050         while (it != itend) {
1051                 GINAC_ASSERT(!is_exactly_a<numeric>(recombine_pair_to_ex(*it)));
1052                 it++;
1053         }
1054 #endif // def DO_GINAC_ASSERT
1055         GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
1056         return abs(ex_to<numeric>(overall_coeff));
1057 }
1058
1059
1060 /** Apply symmetric modular homomorphism to an expanded multivariate
1061  *  polynomial.  This function is usually used internally by heur_gcd().
1062  *
1063  *  @param xi  modulus
1064  *  @return mapped polynomial
1065  *  @see heur_gcd */
1066 ex basic::smod(const numeric &xi) const
1067 {
1068         return *this;
1069 }
1070
1071 ex numeric::smod(const numeric &xi) const
1072 {
1073         return GiNaC::smod(*this, xi);
1074 }
1075
1076 ex add::smod(const numeric &xi) const
1077 {
1078         epvector newseq;
1079         newseq.reserve(seq.size()+1);
1080         epvector::const_iterator it = seq.begin();
1081         epvector::const_iterator itend = seq.end();
1082         while (it != itend) {
1083                 GINAC_ASSERT(!is_exactly_a<numeric>(it->rest));
1084                 numeric coeff = GiNaC::smod(ex_to<numeric>(it->coeff), xi);
1085                 if (!coeff.is_zero())
1086                         newseq.push_back(expair(it->rest, coeff));
1087                 it++;
1088         }
1089         GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
1090         numeric coeff = GiNaC::smod(ex_to<numeric>(overall_coeff), xi);
1091         return (new add(newseq,coeff))->setflag(status_flags::dynallocated);
1092 }
1093
1094 ex mul::smod(const numeric &xi) const
1095 {
1096 #ifdef DO_GINAC_ASSERT
1097         epvector::const_iterator it = seq.begin();
1098         epvector::const_iterator itend = seq.end();
1099         while (it != itend) {
1100                 GINAC_ASSERT(!is_exactly_a<numeric>(recombine_pair_to_ex(*it)));
1101                 it++;
1102         }
1103 #endif // def DO_GINAC_ASSERT
1104         mul * mulcopyp = new mul(*this);
1105         GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
1106         mulcopyp->overall_coeff = GiNaC::smod(ex_to<numeric>(overall_coeff),xi);
1107         mulcopyp->clearflag(status_flags::evaluated);
1108         mulcopyp->clearflag(status_flags::hash_calculated);
1109         return mulcopyp->setflag(status_flags::dynallocated);
1110 }
1111
1112
1113 /** xi-adic polynomial interpolation */
1114 static ex interpolate(const ex &gamma, const numeric &xi, const symbol &x, int degree_hint = 1)
1115 {
1116         exvector g; g.reserve(degree_hint);
1117         ex e = gamma;
1118         numeric rxi = xi.inverse();
1119         for (int i=0; !e.is_zero(); i++) {
1120                 ex gi = e.smod(xi);
1121                 g.push_back(gi * power(x, i));
1122                 e = (e - gi) * rxi;
1123         }
1124         return (new add(g))->setflag(status_flags::dynallocated);
1125 }
1126
1127 /** Exception thrown by heur_gcd() to signal failure. */
1128 class gcdheu_failed {};
1129
1130 /** Compute GCD of multivariate polynomials using the heuristic GCD algorithm.
1131  *  get_symbol_stats() must have been called previously with the input
1132  *  polynomials and an iterator to the first element of the sym_desc vector
1133  *  passed in. This function is used internally by gcd().
1134  *
1135  *  @param a  first multivariate polynomial (expanded)
1136  *  @param b  second multivariate polynomial (expanded)
1137  *  @param ca  cofactor of polynomial a (returned), NULL to suppress
1138  *             calculation of cofactor
1139  *  @param cb  cofactor of polynomial b (returned), NULL to suppress
1140  *             calculation of cofactor
1141  *  @param var iterator to first element of vector of sym_desc structs
1142  *  @return the GCD as a new expression
1143  *  @see gcd
1144  *  @exception gcdheu_failed() */
1145 static ex heur_gcd(const ex &a, const ex &b, ex *ca, ex *cb, sym_desc_vec::const_iterator var)
1146 {
1147 #if STATISTICS
1148         heur_gcd_called++;
1149 #endif
1150
1151         // Algorithm only works for non-vanishing input polynomials
1152         if (a.is_zero() || b.is_zero())
1153                 return (new fail())->setflag(status_flags::dynallocated);
1154
1155         // GCD of two numeric values -> CLN
1156         if (is_exactly_a<numeric>(a) && is_exactly_a<numeric>(b)) {
1157                 numeric g = gcd(ex_to<numeric>(a), ex_to<numeric>(b));
1158                 if (ca)
1159                         *ca = ex_to<numeric>(a) / g;
1160                 if (cb)
1161                         *cb = ex_to<numeric>(b) / g;
1162                 return g;
1163         }
1164
1165         // The first symbol is our main variable
1166         const symbol &x = *(var->sym);
1167
1168         // Remove integer content
1169         numeric gc = gcd(a.integer_content(), b.integer_content());
1170         numeric rgc = gc.inverse();
1171         ex p = a * rgc;
1172         ex q = b * rgc;
1173         int maxdeg =  std::max(p.degree(x), q.degree(x));
1174         
1175         // Find evaluation point
1176         numeric mp = p.max_coefficient();
1177         numeric mq = q.max_coefficient();
1178         numeric xi;
1179         if (mp > mq)
1180                 xi = mq * _num2 + _num2;
1181         else
1182                 xi = mp * _num2 + _num2;
1183
1184         // 6 tries maximum
1185         for (int t=0; t<6; t++) {
1186                 if (xi.int_length() * maxdeg > 100000) {
1187                         throw gcdheu_failed();
1188                 }
1189
1190                 // Apply evaluation homomorphism and calculate GCD
1191                 ex cp, cq;
1192                 ex gamma = heur_gcd(p.subs(x == xi), q.subs(x == xi), &cp, &cq, var+1).expand();
1193                 if (!is_exactly_a<fail>(gamma)) {
1194
1195                         // Reconstruct polynomial from GCD of mapped polynomials
1196                         ex g = interpolate(gamma, xi, x, maxdeg);
1197
1198                         // Remove integer content
1199                         g /= g.integer_content();
1200
1201                         // If the calculated polynomial divides both p and q, this is the GCD
1202                         ex dummy;
1203                         if (divide_in_z(p, g, ca ? *ca : dummy, var) && divide_in_z(q, g, cb ? *cb : dummy, var)) {
1204                                 g *= gc;
1205                                 ex lc = g.lcoeff(x);
1206                                 if (is_exactly_a<numeric>(lc) && ex_to<numeric>(lc).is_negative())
1207                                         return -g;
1208                                 else
1209                                         return g;
1210                         }
1211                 }
1212
1213                 // Next evaluation point
1214                 xi = iquo(xi * isqrt(isqrt(xi)) * numeric(73794), numeric(27011));
1215         }
1216         return (new fail())->setflag(status_flags::dynallocated);
1217 }
1218
1219
1220 /** Compute GCD (Greatest Common Divisor) of multivariate polynomials a(X)
1221  *  and b(X) in Z[X].
1222  *
1223  *  @param a  first multivariate polynomial
1224  *  @param b  second multivariate polynomial
1225  *  @param check_args  check whether a and b are polynomials with rational
1226  *         coefficients (defaults to "true")
1227  *  @return the GCD as a new expression */
1228 ex gcd(const ex &a, const ex &b, ex *ca, ex *cb, bool check_args)
1229 {
1230 #if STATISTICS
1231         gcd_called++;
1232 #endif
1233
1234         // GCD of numerics -> CLN
1235         if (is_exactly_a<numeric>(a) && is_exactly_a<numeric>(b)) {
1236                 numeric g = gcd(ex_to<numeric>(a), ex_to<numeric>(b));
1237                 if (ca || cb) {
1238                         if (g.is_zero()) {
1239                                 if (ca)
1240                                         *ca = _ex0;
1241                                 if (cb)
1242                                         *cb = _ex0;
1243                         } else {
1244                                 if (ca)
1245                                         *ca = ex_to<numeric>(a) / g;
1246                                 if (cb)
1247                                         *cb = ex_to<numeric>(b) / g;
1248                         }
1249                 }
1250                 return g;
1251         }
1252
1253         // Check arguments
1254         if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial))) {
1255                 throw(std::invalid_argument("gcd: arguments must be polynomials over the rationals"));
1256         }
1257
1258         // Partially factored cases (to avoid expanding large expressions)
1259         if (is_exactly_a<mul>(a)) {
1260                 if (is_exactly_a<mul>(b) && b.nops() > a.nops())
1261                         goto factored_b;
1262 factored_a:
1263                 size_t num = a.nops();
1264                 exvector g; g.reserve(num);
1265                 exvector acc_ca; acc_ca.reserve(num);
1266                 ex part_b = b;
1267                 for (size_t i=0; i<num; i++) {
1268                         ex part_ca, part_cb;
1269                         g.push_back(gcd(a.op(i), part_b, &part_ca, &part_cb, check_args));
1270                         acc_ca.push_back(part_ca);
1271                         part_b = part_cb;
1272                 }
1273                 if (ca)
1274                         *ca = (new mul(acc_ca))->setflag(status_flags::dynallocated);
1275                 if (cb)
1276                         *cb = part_b;
1277                 return (new mul(g))->setflag(status_flags::dynallocated);
1278         } else if (is_exactly_a<mul>(b)) {
1279                 if (is_exactly_a<mul>(a) && a.nops() > b.nops())
1280                         goto factored_a;
1281 factored_b:
1282                 size_t num = b.nops();
1283                 exvector g; g.reserve(num);
1284                 exvector acc_cb; acc_cb.reserve(num);
1285                 ex part_a = a;
1286                 for (size_t i=0; i<num; i++) {
1287                         ex part_ca, part_cb;
1288                         g.push_back(gcd(part_a, b.op(i), &part_ca, &part_cb, check_args));
1289                         acc_cb.push_back(part_cb);
1290                         part_a = part_ca;
1291                 }
1292                 if (ca)
1293                         *ca = part_a;
1294                 if (cb)
1295                         *cb = (new mul(acc_cb))->setflag(status_flags::dynallocated);
1296                 return (new mul(g))->setflag(status_flags::dynallocated);
1297         }
1298
1299 #if FAST_COMPARE
1300         // Input polynomials of the form poly^n are sometimes also trivial
1301         if (is_exactly_a<power>(a)) {
1302                 ex p = a.op(0);
1303                 if (is_exactly_a<power>(b)) {
1304                         if (p.is_equal(b.op(0))) {
1305                                 // a = p^n, b = p^m, gcd = p^min(n, m)
1306                                 ex exp_a = a.op(1), exp_b = b.op(1);
1307                                 if (exp_a < exp_b) {
1308                                         if (ca)
1309                                                 *ca = _ex1;
1310                                         if (cb)
1311                                                 *cb = power(p, exp_b - exp_a);
1312                                         return power(p, exp_a);
1313                                 } else {
1314                                         if (ca)
1315                                                 *ca = power(p, exp_a - exp_b);
1316                                         if (cb)
1317                                                 *cb = _ex1;
1318                                         return power(p, exp_b);
1319                                 }
1320                         }
1321                 } else {
1322                         if (p.is_equal(b)) {
1323                                 // a = p^n, b = p, gcd = p
1324                                 if (ca)
1325                                         *ca = power(p, a.op(1) - 1);
1326                                 if (cb)
1327                                         *cb = _ex1;
1328                                 return p;
1329                         }
1330                 }
1331         } else if (is_exactly_a<power>(b)) {
1332                 ex p = b.op(0);
1333                 if (p.is_equal(a)) {
1334                         // a = p, b = p^n, gcd = p
1335                         if (ca)
1336                                 *ca = _ex1;
1337                         if (cb)
1338                                 *cb = power(p, b.op(1) - 1);
1339                         return p;
1340                 }
1341         }
1342 #endif
1343
1344         // Some trivial cases
1345         ex aex = a.expand(), bex = b.expand();
1346         if (aex.is_zero()) {
1347                 if (ca)
1348                         *ca = _ex0;
1349                 if (cb)
1350                         *cb = _ex1;
1351                 return b;
1352         }
1353         if (bex.is_zero()) {
1354                 if (ca)
1355                         *ca = _ex1;
1356                 if (cb)
1357                         *cb = _ex0;
1358                 return a;
1359         }
1360         if (aex.is_equal(_ex1) || bex.is_equal(_ex1)) {
1361                 if (ca)
1362                         *ca = a;
1363                 if (cb)
1364                         *cb = b;
1365                 return _ex1;
1366         }
1367 #if FAST_COMPARE
1368         if (a.is_equal(b)) {
1369                 if (ca)
1370                         *ca = _ex1;
1371                 if (cb)
1372                         *cb = _ex1;
1373                 return a;
1374         }
1375 #endif
1376
1377         // Gather symbol statistics
1378         sym_desc_vec sym_stats;
1379         get_symbol_stats(a, b, sym_stats);
1380
1381         // The symbol with least degree is our main variable
1382         sym_desc_vec::const_iterator var = sym_stats.begin();
1383         const symbol &x = *(var->sym);
1384
1385         // Cancel trivial common factor
1386         int ldeg_a = var->ldeg_a;
1387         int ldeg_b = var->ldeg_b;
1388         int min_ldeg = std::min(ldeg_a,ldeg_b);
1389         if (min_ldeg > 0) {
1390                 ex common = power(x, min_ldeg);
1391                 return gcd((aex / common).expand(), (bex / common).expand(), ca, cb, false) * common;
1392         }
1393
1394         // Try to eliminate variables
1395         if (var->deg_a == 0) {
1396                 ex c = bex.content(x);
1397                 ex g = gcd(aex, c, ca, cb, false);
1398                 if (cb)
1399                         *cb *= bex.unit(x) * bex.primpart(x, c);
1400                 return g;
1401         } else if (var->deg_b == 0) {
1402                 ex c = aex.content(x);
1403                 ex g = gcd(c, bex, ca, cb, false);
1404                 if (ca)
1405                         *ca *= aex.unit(x) * aex.primpart(x, c);
1406                 return g;
1407         }
1408
1409         // Try heuristic algorithm first, fall back to PRS if that failed
1410         ex g;
1411         try {
1412                 g = heur_gcd(aex, bex, ca, cb, var);
1413         } catch (gcdheu_failed) {
1414                 g = fail();
1415         }
1416         if (is_exactly_a<fail>(g)) {
1417 #if STATISTICS
1418                 heur_gcd_failed++;
1419 #endif
1420                 g = sr_gcd(aex, bex, var);
1421                 if (g.is_equal(_ex1)) {
1422                         // Keep cofactors factored if possible
1423                         if (ca)
1424                                 *ca = a;
1425                         if (cb)
1426                                 *cb = b;
1427                 } else {
1428                         if (ca)
1429                                 divide(aex, g, *ca, false);
1430                         if (cb)
1431                                 divide(bex, g, *cb, false);
1432                 }
1433         } else {
1434                 if (g.is_equal(_ex1)) {
1435                         // Keep cofactors factored if possible
1436                         if (ca)
1437                                 *ca = a;
1438                         if (cb)
1439                                 *cb = b;
1440                 }
1441         }
1442
1443         return g;
1444 }
1445
1446
1447 /** Compute LCM (Least Common Multiple) of multivariate polynomials in Z[X].
1448  *
1449  *  @param a  first multivariate polynomial
1450  *  @param b  second multivariate polynomial
1451  *  @param check_args  check whether a and b are polynomials with rational
1452  *         coefficients (defaults to "true")
1453  *  @return the LCM as a new expression */
1454 ex lcm(const ex &a, const ex &b, bool check_args)
1455 {
1456         if (is_exactly_a<numeric>(a) && is_exactly_a<numeric>(b))
1457                 return lcm(ex_to<numeric>(a), ex_to<numeric>(b));
1458         if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
1459                 throw(std::invalid_argument("lcm: arguments must be polynomials over the rationals"));
1460         
1461         ex ca, cb;
1462         ex g = gcd(a, b, &ca, &cb, false);
1463         return ca * cb * g;
1464 }
1465
1466
1467 /*
1468  *  Square-free factorization
1469  */
1470
1471 /** Compute square-free factorization of multivariate polynomial a(x) using
1472  *  YunĀ“s algorithm.  Used internally by sqrfree().
1473  *
1474  *  @param a  multivariate polynomial over Z[X], treated here as univariate
1475  *            polynomial in x.
1476  *  @param x  variable to factor in
1477  *  @return   vector of factors sorted in ascending degree */
1478 static exvector sqrfree_yun(const ex &a, const symbol &x)
1479 {
1480         exvector res;
1481         ex w = a;
1482         ex z = w.diff(x);
1483         ex g = gcd(w, z);
1484         if (g.is_equal(_ex1)) {
1485                 res.push_back(a);
1486                 return res;
1487         }
1488         ex y;
1489         do {
1490                 w = quo(w, g, x);
1491                 y = quo(z, g, x);
1492                 z = y - w.diff(x);
1493                 g = gcd(w, z);
1494                 res.push_back(g);
1495         } while (!z.is_zero());
1496         return res;
1497 }
1498
1499
1500 /** Compute a square-free factorization of a multivariate polynomial in Q[X].
1501  *
1502  *  @param a  multivariate polynomial over Q[X]
1503  *  @param x  lst of variables to factor in, may be left empty for autodetection
1504  *  @return   a square-free factorization of \p a.
1505  *
1506  * \note
1507  * A polynomial \f$p(X) \in C[X]\f$ is said <EM>square-free</EM>
1508  * if, whenever any two polynomials \f$q(X)\f$ and \f$r(X)\f$
1509  * are such that
1510  * \f[
1511  *     p(X) = q(X)^2 r(X),
1512  * \f]
1513  * we have \f$q(X) \in C\f$.
1514  * This means that \f$p(X)\f$ has no repeated factors, apart
1515  * eventually from constants.
1516  * Given a polynomial \f$p(X) \in C[X]\f$, we say that the
1517  * decomposition
1518  * \f[
1519  *   p(X) = b \cdot p_1(X)^{a_1} \cdot p_2(X)^{a_2} \cdots p_r(X)^{a_r}
1520  * \f]
1521  * is a <EM>square-free factorization</EM> of \f$p(X)\f$ if the
1522  * following conditions hold:
1523  * -#  \f$b \in C\f$ and \f$b \neq 0\f$;
1524  * -#  \f$a_i\f$ is a positive integer for \f$i = 1, \ldots, r\f$;
1525  * -#  the degree of the polynomial \f$p_i\f$ is strictly positive
1526  *     for \f$i = 1, \ldots, r\f$;
1527  * -#  the polynomial \f$\Pi_{i=1}^r p_i(X)\f$ is square-free.
1528  *
1529  * Square-free factorizations need not be unique.  For example, if
1530  * \f$a_i\f$ is even, we could change the polynomial \f$p_i(X)\f$
1531  * into \f$-p_i(X)\f$.
1532  * Observe also that the factors \f$p_i(X)\f$ need not be irreducible
1533  * polynomials.
1534  */
1535 ex sqrfree(const ex &a, const lst &l)
1536 {
1537         if (is_exactly_a<numeric>(a) ||     // algorithm does not trap a==0
1538             is_a<symbol>(a))        // shortcut
1539                 return a;
1540
1541         // If no lst of variables to factorize in was specified we have to
1542         // invent one now.  Maybe one can optimize here by reversing the order
1543         // or so, I don't know.
1544         lst args;
1545         if (l.nops()==0) {
1546                 sym_desc_vec sdv;
1547                 get_symbol_stats(a, _ex0, sdv);
1548                 sym_desc_vec::const_iterator it = sdv.begin(), itend = sdv.end();
1549                 while (it != itend) {
1550                         args.append(*it->sym);
1551                         ++it;
1552                 }
1553         } else {
1554                 args = l;
1555         }
1556
1557         // Find the symbol to factor in at this stage
1558         if (!is_a<symbol>(args.op(0)))
1559                 throw (std::runtime_error("sqrfree(): invalid factorization variable"));
1560         const symbol &x = ex_to<symbol>(args.op(0));
1561
1562         // convert the argument from something in Q[X] to something in Z[X]
1563         const numeric lcm = lcm_of_coefficients_denominators(a);
1564         const ex tmp = multiply_lcm(a,lcm);
1565
1566         // find the factors
1567         exvector factors = sqrfree_yun(tmp,x);
1568
1569         // construct the next list of symbols with the first element popped
1570         lst newargs = args;
1571         newargs.remove_first();
1572
1573         // recurse down the factors in remaining variables
1574         if (newargs.nops()>0) {
1575                 exvector::iterator i = factors.begin();
1576                 while (i != factors.end()) {
1577                         *i = sqrfree(*i, newargs);
1578                         ++i;
1579                 }
1580         }
1581
1582         // Done with recursion, now construct the final result
1583         ex result = _ex1;
1584         exvector::const_iterator it = factors.begin(), itend = factors.end();
1585         for (int p = 1; it!=itend; ++it, ++p)
1586                 result *= power(*it, p);
1587
1588         // Yun's algorithm does not account for constant factors.  (For univariate
1589         // polynomials it works only in the monic case.)  We can correct this by
1590         // inserting what has been lost back into the result.  For completeness
1591         // we'll also have to recurse down that factor in the remaining variables.
1592         if (newargs.nops()>0)
1593                 result *= sqrfree(quo(tmp, result, x), newargs);
1594         else
1595                 result *= quo(tmp, result, x);
1596
1597         // Put in the reational overall factor again and return
1598         return result * lcm.inverse();
1599 }
1600
1601
1602 /** Compute square-free partial fraction decomposition of rational function
1603  *  a(x).
1604  *
1605  *  @param a rational function over Z[x], treated as univariate polynomial
1606  *           in x
1607  *  @param x variable to factor in
1608  *  @return decomposed rational function */
1609 ex sqrfree_parfrac(const ex & a, const symbol & x)
1610 {
1611         // Find numerator and denominator
1612         ex nd = numer_denom(a);
1613         ex numer = nd.op(0), denom = nd.op(1);
1614 //clog << "numer = " << numer << ", denom = " << denom << endl;
1615
1616         // Convert N(x)/D(x) -> Q(x) + R(x)/D(x), so degree(R) < degree(D)
1617         ex red_poly = quo(numer, denom, x), red_numer = rem(numer, denom, x).expand();
1618 //clog << "red_poly = " << red_poly << ", red_numer = " << red_numer << endl;
1619
1620         // Factorize denominator and compute cofactors
1621         exvector yun = sqrfree_yun(denom, x);
1622 //clog << "yun factors: " << exprseq(yun) << endl;
1623         size_t num_yun = yun.size();
1624         exvector factor; factor.reserve(num_yun);
1625         exvector cofac; cofac.reserve(num_yun);
1626         for (size_t i=0; i<num_yun; i++) {
1627                 if (!yun[i].is_equal(_ex1)) {
1628                         for (size_t j=0; j<=i; j++) {
1629                                 factor.push_back(pow(yun[i], j+1));
1630                                 ex prod = _ex1;
1631                                 for (size_t k=0; k<num_yun; k++) {
1632                                         if (k == i)
1633                                                 prod *= pow(yun[k], i-j);
1634                                         else
1635                                                 prod *= pow(yun[k], k+1);
1636                                 }
1637                                 cofac.push_back(prod.expand());
1638                         }
1639                 }
1640         }
1641         size_t num_factors = factor.size();
1642 //clog << "factors  : " << exprseq(factor) << endl;
1643 //clog << "cofactors: " << exprseq(cofac) << endl;
1644
1645         // Construct coefficient matrix for decomposition
1646         int max_denom_deg = denom.degree(x);
1647         matrix sys(max_denom_deg + 1, num_factors);
1648         matrix rhs(max_denom_deg + 1, 1);
1649         for (int i=0; i<=max_denom_deg; i++) {
1650                 for (size_t j=0; j<num_factors; j++)
1651                         sys(i, j) = cofac[j].coeff(x, i);
1652                 rhs(i, 0) = red_numer.coeff(x, i);
1653         }
1654 //clog << "coeffs: " << sys << endl;
1655 //clog << "rhs   : " << rhs << endl;
1656
1657         // Solve resulting linear system
1658         matrix vars(num_factors, 1);
1659         for (size_t i=0; i<num_factors; i++)
1660                 vars(i, 0) = symbol();
1661         matrix sol = sys.solve(vars, rhs);
1662
1663         // Sum up decomposed fractions
1664         ex sum = 0;
1665         for (size_t i=0; i<num_factors; i++)
1666                 sum += sol(i, 0) / factor[i];
1667
1668         return red_poly + sum;
1669 }
1670
1671
1672 /*
1673  *  Normal form of rational functions
1674  */
1675
1676 /*
1677  *  Note: The internal normal() functions (= basic::normal() and overloaded
1678  *  functions) all return lists of the form {numerator, denominator}. This
1679  *  is to get around mul::eval()'s automatic expansion of numeric coefficients.
1680  *  E.g. (a+b)/3 is automatically converted to a/3+b/3 but we want to keep
1681  *  the information that (a+b) is the numerator and 3 is the denominator.
1682  */
1683
1684
1685 /** Create a symbol for replacing the expression "e" (or return a previously
1686  *  assigned symbol). The symbol is appended to sym_lst and returned, the
1687  *  expression is appended to repl_lst.
1688  *  @see ex::normal */
1689 static ex replace_with_symbol(const ex &e, lst &sym_lst, lst &repl_lst)
1690 {
1691         // Expression already in repl_lst? Then return the assigned symbol
1692         lst::const_iterator its, itr;
1693         for (its = sym_lst.begin(), itr = repl_lst.begin(); itr != repl_lst.end(); ++its, ++itr)
1694                 if (itr->is_equal(e))
1695                         return *its;
1696         
1697         // Otherwise create new symbol and add to list, taking care that the
1698         // replacement expression doesn't contain symbols from the sym_lst
1699         // because subs() is not recursive
1700         symbol s;
1701         ex es(s);
1702         ex e_replaced = e.subs(sym_lst, repl_lst);
1703         sym_lst.append(es);
1704         repl_lst.append(e_replaced);
1705         return es;
1706 }
1707
1708 /** Create a symbol for replacing the expression "e" (or return a previously
1709  *  assigned symbol). An expression of the form "symbol == expression" is added
1710  *  to repl_lst and the symbol is returned.
1711  *  @see basic::to_rational
1712  *  @see basic::to_polynomial */
1713 static ex replace_with_symbol(const ex &e, lst &repl_lst)
1714 {
1715         // Expression already in repl_lst? Then return the assigned symbol
1716         for (lst::const_iterator it = repl_lst.begin(); it != repl_lst.end(); ++it)
1717                 if (it->op(1).is_equal(e))
1718                         return it->op(0);
1719         
1720         // Otherwise create new symbol and add to list, taking care that the
1721         // replacement expression doesn't contain symbols from the sym_lst
1722         // because subs() is not recursive
1723         symbol s;
1724         ex es(s);
1725         ex e_replaced = e.subs(repl_lst);
1726         repl_lst.append(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(lst &sym_lst, lst &repl_lst, int level) const
1742 {
1743         if (nops() == 0)
1744                 return (new lst(replace_with_symbol(*this, sym_lst, repl_lst), _ex1))->setflag(status_flags::dynallocated);
1745         else {
1746                 if (level == 1)
1747                         return (new lst(replace_with_symbol(*this, sym_lst, repl_lst), _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), sym_lst, repl_lst), _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(lst &sym_lst, lst &repl_lst, 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(lst &sym_lst, lst &repl_lst, 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, sym_lst, repl_lst);
1778         } else { // complex
1779                 numeric re = num.real(), im = num.imag();
1780                 ex re_ex = re.is_rational() ? re : replace_with_symbol(re, sym_lst, repl_lst);
1781                 ex im_ex = im.is_rational() ? im : replace_with_symbol(im, sym_lst, repl_lst);
1782                 numex = re_ex + im_ex * replace_with_symbol(I, sym_lst, repl_lst);
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         const symbol *x;
1830         if (get_first_symbol(den, x)) {
1831                 GINAC_ASSERT(is_exactly_a<numeric>(den.unit(*x)));
1832                 if (ex_to<numeric>(den.unit(*x)).is_negative()) {
1833                         num *= _ex_1;
1834                         den *= _ex_1;
1835                 }
1836         }
1837
1838         // Return result as list
1839 //std::clog << " returns num = " << num << ", den = " << den << ", pre_factor = " << pre_factor << std::endl;
1840         return (new lst(num * pre_factor.numer(), den * pre_factor.denom()))->setflag(status_flags::dynallocated);
1841 }
1842
1843
1844 /** Implementation of ex::normal() for a sum. It expands terms and performs
1845  *  fractional addition.
1846  *  @see ex::normal */
1847 ex add::normal(lst &sym_lst, lst &repl_lst, int level) const
1848 {
1849         if (level == 1)
1850                 return (new lst(replace_with_symbol(*this, sym_lst, repl_lst), _ex1))->setflag(status_flags::dynallocated);
1851         else if (level == -max_recursion_level)
1852                 throw(std::runtime_error("max recursion level reached"));
1853
1854         // Normalize children and split each one into numerator and denominator
1855         exvector nums, dens;
1856         nums.reserve(seq.size()+1);
1857         dens.reserve(seq.size()+1);
1858         epvector::const_iterator it = seq.begin(), itend = seq.end();
1859         while (it != itend) {
1860                 ex n = ex_to<basic>(recombine_pair_to_ex(*it)).normal(sym_lst, repl_lst, level-1);
1861                 nums.push_back(n.op(0));
1862                 dens.push_back(n.op(1));
1863                 it++;
1864         }
1865         ex n = ex_to<numeric>(overall_coeff).normal(sym_lst, repl_lst, level-1);
1866         nums.push_back(n.op(0));
1867         dens.push_back(n.op(1));
1868         GINAC_ASSERT(nums.size() == dens.size());
1869
1870         // Now, nums is a vector of all numerators and dens is a vector of
1871         // all denominators
1872 //std::clog << "add::normal uses " << nums.size() << " summands:\n";
1873
1874         // Add fractions sequentially
1875         exvector::const_iterator num_it = nums.begin(), num_itend = nums.end();
1876         exvector::const_iterator den_it = dens.begin(), den_itend = dens.end();
1877 //std::clog << " num = " << *num_it << ", den = " << *den_it << std::endl;
1878         ex num = *num_it++, den = *den_it++;
1879         while (num_it != num_itend) {
1880 //std::clog << " num = " << *num_it << ", den = " << *den_it << std::endl;
1881                 ex next_num = *num_it++, next_den = *den_it++;
1882
1883                 // Trivially add sequences of fractions with identical denominators
1884                 while ((den_it != den_itend) && next_den.is_equal(*den_it)) {
1885                         next_num += *num_it;
1886                         num_it++; den_it++;
1887                 }
1888
1889                 // Additiion of two fractions, taking advantage of the fact that
1890                 // the heuristic GCD algorithm computes the cofactors at no extra cost
1891                 ex co_den1, co_den2;
1892                 ex g = gcd(den, next_den, &co_den1, &co_den2, false);
1893                 num = ((num * co_den2) + (next_num * co_den1)).expand();
1894                 den *= co_den2;         // this is the lcm(den, next_den)
1895         }
1896 //std::clog << " common denominator = " << den << std::endl;
1897
1898         // Cancel common factors from num/den
1899         return frac_cancel(num, den);
1900 }
1901
1902
1903 /** Implementation of ex::normal() for a product. It cancels common factors
1904  *  from fractions.
1905  *  @see ex::normal() */
1906 ex mul::normal(lst &sym_lst, lst &repl_lst, int level) const
1907 {
1908         if (level == 1)
1909                 return (new lst(replace_with_symbol(*this, sym_lst, repl_lst), _ex1))->setflag(status_flags::dynallocated);
1910         else if (level == -max_recursion_level)
1911                 throw(std::runtime_error("max recursion level reached"));
1912
1913         // Normalize children, separate into numerator and denominator
1914         exvector num; num.reserve(seq.size());
1915         exvector den; den.reserve(seq.size());
1916         ex n;
1917         epvector::const_iterator it = seq.begin(), itend = seq.end();
1918         while (it != itend) {
1919                 n = ex_to<basic>(recombine_pair_to_ex(*it)).normal(sym_lst, repl_lst, level-1);
1920                 num.push_back(n.op(0));
1921                 den.push_back(n.op(1));
1922                 it++;
1923         }
1924         n = ex_to<numeric>(overall_coeff).normal(sym_lst, repl_lst, level-1);
1925         num.push_back(n.op(0));
1926         den.push_back(n.op(1));
1927
1928         // Perform fraction cancellation
1929         return frac_cancel((new mul(num))->setflag(status_flags::dynallocated),
1930                            (new mul(den))->setflag(status_flags::dynallocated));
1931 }
1932
1933
1934 /** Implementation of ex::normal() for powers. It normalizes the basis,
1935  *  distributes integer exponents to numerator and denominator, and replaces
1936  *  non-integer powers by temporary symbols.
1937  *  @see ex::normal */
1938 ex power::normal(lst &sym_lst, lst &repl_lst, int level) const
1939 {
1940         if (level == 1)
1941                 return (new lst(replace_with_symbol(*this, sym_lst, repl_lst), _ex1))->setflag(status_flags::dynallocated);
1942         else if (level == -max_recursion_level)
1943                 throw(std::runtime_error("max recursion level reached"));
1944
1945         // Normalize basis and exponent (exponent gets reassembled)
1946         ex n_basis = ex_to<basic>(basis).normal(sym_lst, repl_lst, level-1);
1947         ex n_exponent = ex_to<basic>(exponent).normal(sym_lst, repl_lst, level-1);
1948         n_exponent = n_exponent.op(0) / n_exponent.op(1);
1949
1950         if (n_exponent.info(info_flags::integer)) {
1951
1952                 if (n_exponent.info(info_flags::positive)) {
1953
1954                         // (a/b)^n -> {a^n, b^n}
1955                         return (new lst(power(n_basis.op(0), n_exponent), power(n_basis.op(1), n_exponent)))->setflag(status_flags::dynallocated);
1956
1957                 } else if (n_exponent.info(info_flags::negative)) {
1958
1959                         // (a/b)^-n -> {b^n, a^n}
1960                         return (new lst(power(n_basis.op(1), -n_exponent), power(n_basis.op(0), -n_exponent)))->setflag(status_flags::dynallocated);
1961                 }
1962
1963         } else {
1964
1965                 if (n_exponent.info(info_flags::positive)) {
1966
1967                         // (a/b)^x -> {sym((a/b)^x), 1}
1968                         return (new lst(replace_with_symbol(power(n_basis.op(0) / n_basis.op(1), n_exponent), sym_lst, repl_lst), _ex1))->setflag(status_flags::dynallocated);
1969
1970                 } else if (n_exponent.info(info_flags::negative)) {
1971
1972                         if (n_basis.op(1).is_equal(_ex1)) {
1973
1974                                 // a^-x -> {1, sym(a^x)}
1975                                 return (new lst(_ex1, replace_with_symbol(power(n_basis.op(0), -n_exponent), sym_lst, repl_lst)))->setflag(status_flags::dynallocated);
1976
1977                         } else {
1978
1979                                 // (a/b)^-x -> {sym((b/a)^x), 1}
1980                                 return (new lst(replace_with_symbol(power(n_basis.op(1) / n_basis.op(0), -n_exponent), sym_lst, repl_lst), _ex1))->setflag(status_flags::dynallocated);
1981                         }
1982                 }
1983         }
1984
1985         // (a/b)^x -> {sym((a/b)^x, 1}
1986         return (new lst(replace_with_symbol(power(n_basis.op(0) / n_basis.op(1), n_exponent), sym_lst, repl_lst), _ex1))->setflag(status_flags::dynallocated);
1987 }
1988
1989
1990 /** Implementation of ex::normal() for pseries. It normalizes each coefficient
1991  *  and replaces the series by a temporary symbol.
1992  *  @see ex::normal */
1993 ex pseries::normal(lst &sym_lst, lst &repl_lst, int level) const
1994 {
1995         epvector newseq;
1996         epvector::const_iterator i = seq.begin(), end = seq.end();
1997         while (i != end) {
1998                 ex restexp = i->rest.normal();
1999                 if (!restexp.is_zero())
2000                         newseq.push_back(expair(restexp, i->coeff));
2001                 ++i;
2002         }
2003         ex n = pseries(relational(var,point), newseq);
2004         return (new lst(replace_with_symbol(n, sym_lst, repl_lst), _ex1))->setflag(status_flags::dynallocated);
2005 }
2006
2007
2008 /** Normalization of rational functions.
2009  *  This function converts an expression to its normal form
2010  *  "numerator/denominator", where numerator and denominator are (relatively
2011  *  prime) polynomials. Any subexpressions which are not rational functions
2012  *  (like non-rational numbers, non-integer powers or functions like sin(),
2013  *  cos() etc.) are replaced by temporary symbols which are re-substituted by
2014  *  the (normalized) subexpressions before normal() returns (this way, any
2015  *  expression can be treated as a rational function). normal() is applied
2016  *  recursively to arguments of functions etc.
2017  *
2018  *  @param level maximum depth of recursion
2019  *  @return normalized expression */
2020 ex ex::normal(int level) const
2021 {
2022         lst sym_lst, repl_lst;
2023
2024         ex e = bp->normal(sym_lst, repl_lst, level);
2025         GINAC_ASSERT(is_a<lst>(e));
2026
2027         // Re-insert replaced symbols
2028         if (sym_lst.nops() > 0)
2029                 e = e.subs(sym_lst, repl_lst);
2030
2031         // Convert {numerator, denominator} form back to fraction
2032         return e.op(0) / e.op(1);
2033 }
2034
2035 /** Get numerator of an expression. If the expression is not of the normal
2036  *  form "numerator/denominator", it is first converted to this form and
2037  *  then the numerator is returned.
2038  *
2039  *  @see ex::normal
2040  *  @return numerator */
2041 ex ex::numer(void) const
2042 {
2043         lst sym_lst, repl_lst;
2044
2045         ex e = bp->normal(sym_lst, repl_lst, 0);
2046         GINAC_ASSERT(is_a<lst>(e));
2047
2048         // Re-insert replaced symbols
2049         if (sym_lst.nops() > 0)
2050                 return e.op(0).subs(sym_lst, repl_lst);
2051         else
2052                 return e.op(0);
2053 }
2054
2055 /** Get denominator of an expression. If the expression is not of the normal
2056  *  form "numerator/denominator", it is first converted to this form and
2057  *  then the denominator is returned.
2058  *
2059  *  @see ex::normal
2060  *  @return denominator */
2061 ex ex::denom(void) const
2062 {
2063         lst sym_lst, repl_lst;
2064
2065         ex e = bp->normal(sym_lst, repl_lst, 0);
2066         GINAC_ASSERT(is_a<lst>(e));
2067
2068         // Re-insert replaced symbols
2069         if (sym_lst.nops() > 0)
2070                 return e.op(1).subs(sym_lst, repl_lst);
2071         else
2072                 return e.op(1);
2073 }
2074
2075 /** Get numerator and denominator of an expression. If the expresison is not
2076  *  of the normal form "numerator/denominator", it is first converted to this
2077  *  form and then a list [numerator, denominator] is returned.
2078  *
2079  *  @see ex::normal
2080  *  @return a list [numerator, denominator] */
2081 ex ex::numer_denom(void) const
2082 {
2083         lst sym_lst, repl_lst;
2084
2085         ex e = bp->normal(sym_lst, repl_lst, 0);
2086         GINAC_ASSERT(is_a<lst>(e));
2087
2088         // Re-insert replaced symbols
2089         if (sym_lst.nops() > 0)
2090                 return e.subs(sym_lst, repl_lst);
2091         else
2092                 return e;
2093 }
2094
2095
2096 /** Rationalization of non-rational functions.
2097  *  This function converts a general expression to a rational function
2098  *  by replacing all non-rational subexpressions (like non-rational numbers,
2099  *  non-integer powers or functions like sin(), cos() etc.) to temporary
2100  *  symbols. This makes it possible to use functions like gcd() and divide()
2101  *  on non-rational functions by applying to_rational() on the arguments,
2102  *  calling the desired function and re-substituting the temporary symbols
2103  *  in the result. To make the last step possible, all temporary symbols and
2104  *  their associated expressions are collected in the list specified by the
2105  *  repl_lst parameter in the form {symbol == expression}, ready to be passed
2106  *  as an argument to ex::subs().
2107  *
2108  *  @param repl_lst collects a list of all temporary symbols and their replacements
2109  *  @return rationalized expression */
2110 ex ex::to_rational(lst &repl_lst) const
2111 {
2112         return bp->to_rational(repl_lst);
2113 }
2114
2115 ex ex::to_polynomial(lst &repl_lst) const
2116 {
2117         return bp->to_polynomial(repl_lst);
2118 }
2119
2120
2121 /** Default implementation of ex::to_rational(). This replaces the object with
2122  *  a temporary symbol. */
2123 ex basic::to_rational(lst &repl_lst) const
2124 {
2125         return replace_with_symbol(*this, repl_lst);
2126 }
2127
2128 ex basic::to_polynomial(lst &repl_lst) const
2129 {
2130         return replace_with_symbol(*this, repl_lst);
2131 }
2132
2133
2134 /** Implementation of ex::to_rational() for symbols. This returns the
2135  *  unmodified symbol. */
2136 ex symbol::to_rational(lst &repl_lst) const
2137 {
2138         return *this;
2139 }
2140
2141 /** Implementation of ex::to_polynomial() for symbols. This returns the
2142  *  unmodified symbol. */
2143 ex symbol::to_polynomial(lst &repl_lst) const
2144 {
2145         return *this;
2146 }
2147
2148
2149 /** Implementation of ex::to_rational() for a numeric. It splits complex
2150  *  numbers into re+I*im and replaces I and non-rational real numbers with a
2151  *  temporary symbol. */
2152 ex numeric::to_rational(lst &repl_lst) const
2153 {
2154         if (is_real()) {
2155                 if (!is_rational())
2156                         return replace_with_symbol(*this, repl_lst);
2157         } else { // complex
2158                 numeric re = real();
2159                 numeric im = imag();
2160                 ex re_ex = re.is_rational() ? re : replace_with_symbol(re, repl_lst);
2161                 ex im_ex = im.is_rational() ? im : replace_with_symbol(im, repl_lst);
2162                 return re_ex + im_ex * replace_with_symbol(I, repl_lst);
2163         }
2164         return *this;
2165 }
2166
2167 /** Implementation of ex::to_polynomial() for a numeric. It splits complex
2168  *  numbers into re+I*im and replaces I and non-integer real numbers with a
2169  *  temporary symbol. */
2170 ex numeric::to_polynomial(lst &repl_lst) const
2171 {
2172         if (is_real()) {
2173                 if (!is_integer())
2174                         return replace_with_symbol(*this, repl_lst);
2175         } else { // complex
2176                 numeric re = real();
2177                 numeric im = imag();
2178                 ex re_ex = re.is_integer() ? re : replace_with_symbol(re, repl_lst);
2179                 ex im_ex = im.is_integer() ? im : replace_with_symbol(im, repl_lst);
2180                 return re_ex + im_ex * replace_with_symbol(I, repl_lst);
2181         }
2182         return *this;
2183 }
2184
2185
2186 /** Implementation of ex::to_rational() for powers. It replaces non-integer
2187  *  powers by temporary symbols. */
2188 ex power::to_rational(lst &repl_lst) const
2189 {
2190         if (exponent.info(info_flags::integer))
2191                 return power(basis.to_rational(repl_lst), exponent);
2192         else
2193                 return replace_with_symbol(*this, repl_lst);
2194 }
2195
2196 /** Implementation of ex::to_polynomial() for powers. It replaces non-posint
2197  *  powers by temporary symbols. */
2198 ex power::to_polynomial(lst &repl_lst) const
2199 {
2200         if (exponent.info(info_flags::posint))
2201                 return power(basis.to_rational(repl_lst), exponent);
2202         else
2203                 return replace_with_symbol(*this, repl_lst);
2204 }
2205
2206
2207 /** Implementation of ex::to_rational() for expairseqs. */
2208 ex expairseq::to_rational(lst &repl_lst) const
2209 {
2210         epvector s;
2211         s.reserve(seq.size());
2212         epvector::const_iterator i = seq.begin(), end = seq.end();
2213         while (i != end) {
2214                 s.push_back(split_ex_to_pair(recombine_pair_to_ex(*i).to_rational(repl_lst)));
2215                 ++i;
2216         }
2217         ex oc = overall_coeff.to_rational(repl_lst);
2218         if (oc.info(info_flags::numeric))
2219                 return thisexpairseq(s, overall_coeff);
2220         else
2221                 s.push_back(combine_ex_with_coeff_to_pair(oc, _ex1));
2222         return thisexpairseq(s, default_overall_coeff());
2223 }
2224
2225 /** Implementation of ex::to_polynomial() for expairseqs. */
2226 ex expairseq::to_polynomial(lst &repl_lst) const
2227 {
2228         epvector s;
2229         s.reserve(seq.size());
2230         epvector::const_iterator i = seq.begin(), end = seq.end();
2231         while (i != end) {
2232                 s.push_back(split_ex_to_pair(recombine_pair_to_ex(*i).to_polynomial(repl_lst)));
2233                 ++i;
2234         }
2235         ex oc = overall_coeff.to_polynomial(repl_lst);
2236         if (oc.info(info_flags::numeric))
2237                 return thisexpairseq(s, overall_coeff);
2238         else
2239                 s.push_back(combine_ex_with_coeff_to_pair(oc, _ex1));
2240         return thisexpairseq(s, default_overall_coeff());
2241 }
2242
2243
2244 /** Remove the common factor in the terms of a sum 'e' by calculating the GCD,
2245  *  and multiply it into the expression 'factor' (which needs to be initialized
2246  *  to 1, unless you're accumulating factors). */
2247 static ex find_common_factor(const ex & e, ex & factor, lst & repl)
2248 {
2249         if (is_exactly_a<add>(e)) {
2250
2251                 size_t num = e.nops();
2252                 exvector terms; terms.reserve(num);
2253                 ex gc;
2254
2255                 // Find the common GCD
2256                 for (size_t i=0; i<num; i++) {
2257                         ex x = e.op(i).to_polynomial(repl);
2258
2259                         if (is_exactly_a<add>(x) || is_exactly_a<mul>(x)) {
2260                                 ex f = 1;
2261                                 x = find_common_factor(x, f, repl);
2262                                 x *= f;
2263                         }
2264
2265                         if (i == 0)
2266                                 gc = x;
2267                         else
2268                                 gc = gcd(gc, x);
2269
2270                         terms.push_back(x);
2271                 }
2272
2273                 if (gc.is_equal(_ex1))
2274                         return e;
2275
2276                 // The GCD is the factor we pull out
2277                 factor *= gc;
2278
2279                 // Now divide all terms by the GCD
2280                 for (size_t i=0; i<num; i++) {
2281                         ex x;
2282
2283                         // Try to avoid divide() because it expands the polynomial
2284                         ex &t = terms[i];
2285                         if (is_exactly_a<mul>(t)) {
2286                                 for (size_t j=0; j<t.nops(); j++) {
2287                                         if (t.op(j).is_equal(gc)) {
2288                                                 exvector v; v.reserve(t.nops());
2289                                                 for (size_t k=0; k<t.nops(); k++) {
2290                                                         if (k == j)
2291                                                                 v.push_back(_ex1);
2292                                                         else
2293                                                                 v.push_back(t.op(k));
2294                                                 }
2295                                                 t = (new mul(v))->setflag(status_flags::dynallocated);
2296                                                 goto term_done;
2297                                         }
2298                                 }
2299                         }
2300
2301                         divide(t, gc, x);
2302                         t = x;
2303 term_done:      ;
2304                 }
2305                 return (new add(terms))->setflag(status_flags::dynallocated);
2306
2307         } else if (is_exactly_a<mul>(e)) {
2308
2309                 size_t num = e.nops();
2310                 exvector v; v.reserve(num);
2311
2312                 for (size_t i=0; i<num; i++)
2313                         v.push_back(find_common_factor(e.op(i), factor, repl));
2314
2315                 return (new mul(v))->setflag(status_flags::dynallocated);
2316
2317         } else if (is_exactly_a<power>(e)) {
2318
2319                 return e.to_polynomial(repl);
2320
2321         } else
2322                 return e;
2323 }
2324
2325
2326 /** Collect common factors in sums. This converts expressions like
2327  *  'a*(b*x+b*y)' to 'a*b*(x+y)'. */
2328 ex collect_common_factors(const ex & e)
2329 {
2330         if (is_exactly_a<add>(e) || is_exactly_a<mul>(e)) {
2331
2332                 lst repl;
2333                 ex factor = 1;
2334                 ex r = find_common_factor(e, factor, repl);
2335                 return factor.subs(repl) * r.subs(repl);
2336
2337         } else
2338                 return e;
2339 }
2340
2341
2342 } // namespace GiNaC