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