]> www.ginac.de Git - ginac.git/blob - ginac/normal.cpp
* Fix bug in ctor from string, reported by Christopher Kennedy.
[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                 std::cout << "gcd() called " << gcd_called << " times\n";
78                 std::cout << "sr_gcd() called " << sr_gcd_called << " times\n";
79                 std::cout << "heur_gcd() called " << heur_gcd_called << " times\n";
80                 std::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 = &ex_to<symbol>(e);
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(&ex_to<symbol>(e), 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         std::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_exactly_a<numeric>(it->rest));
326                 GINAC_ASSERT(is_exactly_a<numeric>(it->coeff));
327                 c = gcd(ex_to<numeric>(it->coeff), c);
328                 it++;
329         }
330         GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
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_exactly_a<numeric>(recombine_pair_to_ex(*it)));
342                 ++it;
343         }
344 #endif // def DO_GINAC_ASSERT
345         GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
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_exactly_a<numeric>(overall_coeff));
1232         numeric cur_max = abs(ex_to<numeric>(overall_coeff));
1233         while (it != itend) {
1234                 numeric a;
1235                 GINAC_ASSERT(!is_exactly_a<numeric>(it->rest));
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_exactly_a<numeric>(recombine_pair_to_ex(*it)));
1251                 it++;
1252         }
1253 #endif // def DO_GINAC_ASSERT
1254         GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
1255         return abs(ex_to<numeric>(overall_coeff));
1256 }
1257
1258
1259 /** Apply symmetric modular homomorphism to an expanded multivariate
1260  *  polynomial.  This function is usually used internally by heur_gcd().
1261  *
1262  *  @param xi  modulus
1263  *  @return mapped polynomial
1264  *  @see heur_gcd */
1265 ex basic::smod(const numeric &xi) const
1266 {
1267         return *this;
1268 }
1269
1270 ex numeric::smod(const numeric &xi) const
1271 {
1272         return GiNaC::smod(*this, xi);
1273 }
1274
1275 ex add::smod(const numeric &xi) const
1276 {
1277         epvector newseq;
1278         newseq.reserve(seq.size()+1);
1279         epvector::const_iterator it = seq.begin();
1280         epvector::const_iterator itend = seq.end();
1281         while (it != itend) {
1282                 GINAC_ASSERT(!is_exactly_a<numeric>(it->rest));
1283                 numeric coeff = GiNaC::smod(ex_to<numeric>(it->coeff), xi);
1284                 if (!coeff.is_zero())
1285                         newseq.push_back(expair(it->rest, coeff));
1286                 it++;
1287         }
1288         GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
1289         numeric coeff = GiNaC::smod(ex_to<numeric>(overall_coeff), xi);
1290         return (new add(newseq,coeff))->setflag(status_flags::dynallocated);
1291 }
1292
1293 ex mul::smod(const numeric &xi) const
1294 {
1295 #ifdef DO_GINAC_ASSERT
1296         epvector::const_iterator it = seq.begin();
1297         epvector::const_iterator itend = seq.end();
1298         while (it != itend) {
1299                 GINAC_ASSERT(!is_exactly_a<numeric>(recombine_pair_to_ex(*it)));
1300                 it++;
1301         }
1302 #endif // def DO_GINAC_ASSERT
1303         mul * mulcopyp = new mul(*this);
1304         GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
1305         mulcopyp->overall_coeff = GiNaC::smod(ex_to<numeric>(overall_coeff),xi);
1306         mulcopyp->clearflag(status_flags::evaluated);
1307         mulcopyp->clearflag(status_flags::hash_calculated);
1308         return mulcopyp->setflag(status_flags::dynallocated);
1309 }
1310
1311
1312 /** xi-adic polynomial interpolation */
1313 static ex interpolate(const ex &gamma, const numeric &xi, const symbol &x, int degree_hint = 1)
1314 {
1315         exvector g; g.reserve(degree_hint);
1316         ex e = gamma;
1317         numeric rxi = xi.inverse();
1318         for (int i=0; !e.is_zero(); i++) {
1319                 ex gi = e.smod(xi);
1320                 g.push_back(gi * power(x, i));
1321                 e = (e - gi) * rxi;
1322         }
1323         return (new add(g))->setflag(status_flags::dynallocated);
1324 }
1325
1326 /** Exception thrown by heur_gcd() to signal failure. */
1327 class gcdheu_failed {};
1328
1329 /** Compute GCD of multivariate polynomials using the heuristic GCD algorithm.
1330  *  get_symbol_stats() must have been called previously with the input
1331  *  polynomials and an iterator to the first element of the sym_desc vector
1332  *  passed in. This function is used internally by gcd().
1333  *
1334  *  @param a  first multivariate polynomial (expanded)
1335  *  @param b  second multivariate polynomial (expanded)
1336  *  @param ca  cofactor of polynomial a (returned), NULL to suppress
1337  *             calculation of cofactor
1338  *  @param cb  cofactor of polynomial b (returned), NULL to suppress
1339  *             calculation of cofactor
1340  *  @param var iterator to first element of vector of sym_desc structs
1341  *  @return the GCD as a new expression
1342  *  @see gcd
1343  *  @exception gcdheu_failed() */
1344 static ex heur_gcd(const ex &a, const ex &b, ex *ca, ex *cb, sym_desc_vec::const_iterator var)
1345 {
1346 //std::clog << "heur_gcd(" << a << "," << b << ")\n";
1347 #if STATISTICS
1348         heur_gcd_called++;
1349 #endif
1350
1351         // Algorithm only works for non-vanishing input polynomials
1352         if (a.is_zero() || b.is_zero())
1353                 return (new fail())->setflag(status_flags::dynallocated);
1354
1355         // GCD of two numeric values -> CLN
1356         if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric)) {
1357                 numeric g = gcd(ex_to<numeric>(a), ex_to<numeric>(b));
1358                 if (ca)
1359                         *ca = ex_to<numeric>(a) / g;
1360                 if (cb)
1361                         *cb = ex_to<numeric>(b) / g;
1362                 return g;
1363         }
1364
1365         // The first symbol is our main variable
1366         const symbol &x = *(var->sym);
1367
1368         // Remove integer content
1369         numeric gc = gcd(a.integer_content(), b.integer_content());
1370         numeric rgc = gc.inverse();
1371         ex p = a * rgc;
1372         ex q = b * rgc;
1373         int maxdeg =  std::max(p.degree(x), q.degree(x));
1374         
1375         // Find evaluation point
1376         numeric mp = p.max_coefficient();
1377         numeric mq = q.max_coefficient();
1378         numeric xi;
1379         if (mp > mq)
1380                 xi = mq * _num2 + _num2;
1381         else
1382                 xi = mp * _num2 + _num2;
1383
1384         // 6 tries maximum
1385         for (int t=0; t<6; t++) {
1386                 if (xi.int_length() * maxdeg > 100000) {
1387 //std::clog << "giving up heur_gcd, xi.int_length = " << xi.int_length() << ", maxdeg = " << maxdeg << std::endl;
1388                         throw gcdheu_failed();
1389                 }
1390
1391                 // Apply evaluation homomorphism and calculate GCD
1392                 ex cp, cq;
1393                 ex gamma = heur_gcd(p.subs(x == xi), q.subs(x == xi), &cp, &cq, var+1).expand();
1394                 if (!is_ex_exactly_of_type(gamma, fail)) {
1395
1396                         // Reconstruct polynomial from GCD of mapped polynomials
1397                         ex g = interpolate(gamma, xi, x, maxdeg);
1398
1399                         // Remove integer content
1400                         g /= g.integer_content();
1401
1402                         // If the calculated polynomial divides both p and q, this is the GCD
1403                         ex dummy;
1404                         if (divide_in_z(p, g, ca ? *ca : dummy, var) && divide_in_z(q, g, cb ? *cb : dummy, var)) {
1405                                 g *= gc;
1406                                 ex lc = g.lcoeff(x);
1407                                 if (is_ex_exactly_of_type(lc, numeric) && ex_to<numeric>(lc).is_negative())
1408                                         return -g;
1409                                 else
1410                                         return g;
1411                         }
1412 #if 0
1413                         cp = interpolate(cp, xi, x);
1414                         if (divide_in_z(cp, p, g, var)) {
1415                                 if (divide_in_z(g, q, cb ? *cb : dummy, var)) {
1416                                         g *= gc;
1417                                         if (ca)
1418                                                 *ca = cp;
1419                                         ex lc = g.lcoeff(x);
1420                                         if (is_ex_exactly_of_type(lc, numeric) && ex_to<numeric>(lc).is_negative())
1421                                                 return -g;
1422                                         else
1423                                                 return g;
1424                                 }
1425                         }
1426                         cq = interpolate(cq, xi, x);
1427                         if (divide_in_z(cq, q, g, var)) {
1428                                 if (divide_in_z(g, p, ca ? *ca : dummy, var)) {
1429                                         g *= gc;
1430                                         if (cb)
1431                                                 *cb = cq;
1432                                         ex lc = g.lcoeff(x);
1433                                         if (is_ex_exactly_of_type(lc, numeric) && ex_to<numeric>(lc).is_negative())
1434                                                 return -g;
1435                                         else
1436                                                 return g;
1437                                 }
1438                         }
1439 #endif
1440                 }
1441
1442                 // Next evaluation point
1443                 xi = iquo(xi * isqrt(isqrt(xi)) * numeric(73794), numeric(27011));
1444         }
1445         return (new fail())->setflag(status_flags::dynallocated);
1446 }
1447
1448
1449 /** Compute GCD (Greatest Common Divisor) of multivariate polynomials a(X)
1450  *  and b(X) in Z[X].
1451  *
1452  *  @param a  first multivariate polynomial
1453  *  @param b  second multivariate polynomial
1454  *  @param check_args  check whether a and b are polynomials with rational
1455  *         coefficients (defaults to "true")
1456  *  @return the GCD as a new expression */
1457 ex gcd(const ex &a, const ex &b, ex *ca, ex *cb, bool check_args)
1458 {
1459 //std::clog << "gcd(" << a << "," << b << ")\n";
1460 #if STATISTICS
1461         gcd_called++;
1462 #endif
1463
1464         // GCD of numerics -> CLN
1465         if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric)) {
1466                 numeric g = gcd(ex_to<numeric>(a), ex_to<numeric>(b));
1467                 if (ca || cb) {
1468                         if (g.is_zero()) {
1469                                 if (ca)
1470                                         *ca = _ex0;
1471                                 if (cb)
1472                                         *cb = _ex0;
1473                         } else {
1474                                 if (ca)
1475                                         *ca = ex_to<numeric>(a) / g;
1476                                 if (cb)
1477                                         *cb = ex_to<numeric>(b) / g;
1478                         }
1479                 }
1480                 return g;
1481         }
1482
1483         // Check arguments
1484         if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial))) {
1485                 throw(std::invalid_argument("gcd: arguments must be polynomials over the rationals"));
1486         }
1487
1488         // Partially factored cases (to avoid expanding large expressions)
1489         if (is_ex_exactly_of_type(a, mul)) {
1490                 if (is_ex_exactly_of_type(b, mul) && b.nops() > a.nops())
1491                         goto factored_b;
1492 factored_a:
1493                 unsigned num = a.nops();
1494                 exvector g; g.reserve(num);
1495                 exvector acc_ca; acc_ca.reserve(num);
1496                 ex part_b = b;
1497                 for (unsigned i=0; i<num; i++) {
1498                         ex part_ca, part_cb;
1499                         g.push_back(gcd(a.op(i), part_b, &part_ca, &part_cb, check_args));
1500                         acc_ca.push_back(part_ca);
1501                         part_b = part_cb;
1502                 }
1503                 if (ca)
1504                         *ca = (new mul(acc_ca))->setflag(status_flags::dynallocated);
1505                 if (cb)
1506                         *cb = part_b;
1507                 return (new mul(g))->setflag(status_flags::dynallocated);
1508         } else if (is_ex_exactly_of_type(b, mul)) {
1509                 if (is_ex_exactly_of_type(a, mul) && a.nops() > b.nops())
1510                         goto factored_a;
1511 factored_b:
1512                 unsigned num = b.nops();
1513                 exvector g; g.reserve(num);
1514                 exvector acc_cb; acc_cb.reserve(num);
1515                 ex part_a = a;
1516                 for (unsigned i=0; i<num; i++) {
1517                         ex part_ca, part_cb;
1518                         g.push_back(gcd(part_a, b.op(i), &part_ca, &part_cb, check_args));
1519                         acc_cb.push_back(part_cb);
1520                         part_a = part_ca;
1521                 }
1522                 if (ca)
1523                         *ca = part_a;
1524                 if (cb)
1525                         *cb = (new mul(acc_cb))->setflag(status_flags::dynallocated);
1526                 return (new mul(g))->setflag(status_flags::dynallocated);
1527         }
1528
1529 #if FAST_COMPARE
1530         // Input polynomials of the form poly^n are sometimes also trivial
1531         if (is_ex_exactly_of_type(a, power)) {
1532                 ex p = a.op(0);
1533                 if (is_ex_exactly_of_type(b, power)) {
1534                         if (p.is_equal(b.op(0))) {
1535                                 // a = p^n, b = p^m, gcd = p^min(n, m)
1536                                 ex exp_a = a.op(1), exp_b = b.op(1);
1537                                 if (exp_a < exp_b) {
1538                                         if (ca)
1539                                                 *ca = _ex1;
1540                                         if (cb)
1541                                                 *cb = power(p, exp_b - exp_a);
1542                                         return power(p, exp_a);
1543                                 } else {
1544                                         if (ca)
1545                                                 *ca = power(p, exp_a - exp_b);
1546                                         if (cb)
1547                                                 *cb = _ex1;
1548                                         return power(p, exp_b);
1549                                 }
1550                         }
1551                 } else {
1552                         if (p.is_equal(b)) {
1553                                 // a = p^n, b = p, gcd = p
1554                                 if (ca)
1555                                         *ca = power(p, a.op(1) - 1);
1556                                 if (cb)
1557                                         *cb = _ex1;
1558                                 return p;
1559                         }
1560                 }
1561         } else if (is_ex_exactly_of_type(b, power)) {
1562                 ex p = b.op(0);
1563                 if (p.is_equal(a)) {
1564                         // a = p, b = p^n, gcd = p
1565                         if (ca)
1566                                 *ca = _ex1;
1567                         if (cb)
1568                                 *cb = power(p, b.op(1) - 1);
1569                         return p;
1570                 }
1571         }
1572 #endif
1573
1574         // Some trivial cases
1575         ex aex = a.expand(), bex = b.expand();
1576         if (aex.is_zero()) {
1577                 if (ca)
1578                         *ca = _ex0;
1579                 if (cb)
1580                         *cb = _ex1;
1581                 return b;
1582         }
1583         if (bex.is_zero()) {
1584                 if (ca)
1585                         *ca = _ex1;
1586                 if (cb)
1587                         *cb = _ex0;
1588                 return a;
1589         }
1590         if (aex.is_equal(_ex1) || bex.is_equal(_ex1)) {
1591                 if (ca)
1592                         *ca = a;
1593                 if (cb)
1594                         *cb = b;
1595                 return _ex1;
1596         }
1597 #if FAST_COMPARE
1598         if (a.is_equal(b)) {
1599                 if (ca)
1600                         *ca = _ex1;
1601                 if (cb)
1602                         *cb = _ex1;
1603                 return a;
1604         }
1605 #endif
1606
1607         // Gather symbol statistics
1608         sym_desc_vec sym_stats;
1609         get_symbol_stats(a, b, sym_stats);
1610
1611         // The symbol with least degree is our main variable
1612         sym_desc_vec::const_iterator var = sym_stats.begin();
1613         const symbol &x = *(var->sym);
1614
1615         // Cancel trivial common factor
1616         int ldeg_a = var->ldeg_a;
1617         int ldeg_b = var->ldeg_b;
1618         int min_ldeg = std::min(ldeg_a,ldeg_b);
1619         if (min_ldeg > 0) {
1620                 ex common = power(x, min_ldeg);
1621 //std::clog << "trivial common factor " << common << std::endl;
1622                 return gcd((aex / common).expand(), (bex / common).expand(), ca, cb, false) * common;
1623         }
1624
1625         // Try to eliminate variables
1626         if (var->deg_a == 0) {
1627 //std::clog << "eliminating variable " << x << " from b" << std::endl;
1628                 ex c = bex.content(x);
1629                 ex g = gcd(aex, c, ca, cb, false);
1630                 if (cb)
1631                         *cb *= bex.unit(x) * bex.primpart(x, c);
1632                 return g;
1633         } else if (var->deg_b == 0) {
1634 //std::clog << "eliminating variable " << x << " from a" << std::endl;
1635                 ex c = aex.content(x);
1636                 ex g = gcd(c, bex, ca, cb, false);
1637                 if (ca)
1638                         *ca *= aex.unit(x) * aex.primpart(x, c);
1639                 return g;
1640         }
1641
1642         ex g;
1643 #if 1
1644         // Try heuristic algorithm first, fall back to PRS if that failed
1645         try {
1646                 g = heur_gcd(aex, bex, ca, cb, var);
1647         } catch (gcdheu_failed) {
1648                 g = fail();
1649         }
1650         if (is_ex_exactly_of_type(g, fail)) {
1651 //std::clog << "heuristics failed" << std::endl;
1652 #if STATISTICS
1653                 heur_gcd_failed++;
1654 #endif
1655 #endif
1656 //              g = heur_gcd(aex, bex, ca, cb, var);
1657 //              g = eu_gcd(aex, bex, &x);
1658 //              g = euprem_gcd(aex, bex, &x);
1659 //              g = peu_gcd(aex, bex, &x);
1660 //              g = red_gcd(aex, bex, &x);
1661                 g = sr_gcd(aex, bex, var);
1662                 if (g.is_equal(_ex1)) {
1663                         // Keep cofactors factored if possible
1664                         if (ca)
1665                                 *ca = a;
1666                         if (cb)
1667                                 *cb = b;
1668                 } else {
1669                         if (ca)
1670                                 divide(aex, g, *ca, false);
1671                         if (cb)
1672                                 divide(bex, g, *cb, false);
1673                 }
1674 #if 1
1675         } else {
1676                 if (g.is_equal(_ex1)) {
1677                         // Keep cofactors factored if possible
1678                         if (ca)
1679                                 *ca = a;
1680                         if (cb)
1681                                 *cb = b;
1682                 }
1683         }
1684 #endif
1685         return g;
1686 }
1687
1688
1689 /** Compute LCM (Least Common Multiple) of multivariate polynomials in Z[X].
1690  *
1691  *  @param a  first multivariate polynomial
1692  *  @param b  second multivariate polynomial
1693  *  @param check_args  check whether a and b are polynomials with rational
1694  *         coefficients (defaults to "true")
1695  *  @return the LCM as a new expression */
1696 ex lcm(const ex &a, const ex &b, bool check_args)
1697 {
1698         if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric))
1699                 return lcm(ex_to<numeric>(a), ex_to<numeric>(b));
1700         if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
1701                 throw(std::invalid_argument("lcm: arguments must be polynomials over the rationals"));
1702         
1703         ex ca, cb;
1704         ex g = gcd(a, b, &ca, &cb, false);
1705         return ca * cb * g;
1706 }
1707
1708
1709 /*
1710  *  Square-free factorization
1711  */
1712
1713 /** Compute square-free factorization of multivariate polynomial a(x) using
1714  *  YunĀ“s algorithm.  Used internally by sqrfree().
1715  *
1716  *  @param a  multivariate polynomial over Z[X], treated here as univariate
1717  *            polynomial in x.
1718  *  @param x  variable to factor in
1719  *  @return   vector of factors sorted in ascending degree */
1720 static exvector sqrfree_yun(const ex &a, const symbol &x)
1721 {
1722         exvector res;
1723         ex w = a;
1724         ex z = w.diff(x);
1725         ex g = gcd(w, z);
1726         if (g.is_equal(_ex1)) {
1727                 res.push_back(a);
1728                 return res;
1729         }
1730         ex y;
1731         do {
1732                 w = quo(w, g, x);
1733                 y = quo(z, g, x);
1734                 z = y - w.diff(x);
1735                 g = gcd(w, z);
1736                 res.push_back(g);
1737         } while (!z.is_zero());
1738         return res;
1739 }
1740
1741 /** Compute square-free factorization of multivariate polynomial in Q[X].
1742  *
1743  *  @param a  multivariate polynomial over Q[X]
1744  *  @param x  lst of variables to factor in, may be left empty for autodetection
1745  *  @return   polynomail a in square-free factored form. */
1746 ex sqrfree(const ex &a, const lst &l)
1747 {
1748         if (is_ex_of_type(a,numeric) ||     // algorithm does not trap a==0
1749             is_ex_of_type(a,symbol))        // shortcut
1750                 return a;
1751
1752         // If no lst of variables to factorize in was specified we have to
1753         // invent one now.  Maybe one can optimize here by reversing the order
1754         // or so, I don't know.
1755         lst args;
1756         if (l.nops()==0) {
1757                 sym_desc_vec sdv;
1758                 get_symbol_stats(a, _ex0, sdv);
1759                 sym_desc_vec::const_iterator it = sdv.begin(), itend = sdv.end();
1760                 while (it != itend) {
1761                         args.append(*it->sym);
1762                         ++it;
1763                 }
1764         } else {
1765                 args = l;
1766         }
1767
1768         // Find the symbol to factor in at this stage
1769         if (!is_ex_of_type(args.op(0), symbol))
1770                 throw (std::runtime_error("sqrfree(): invalid factorization variable"));
1771         const symbol x = ex_to<symbol>(args.op(0));
1772
1773         // convert the argument from something in Q[X] to something in Z[X]
1774         numeric lcm = lcm_of_coefficients_denominators(a);
1775         ex tmp = multiply_lcm(a,lcm);
1776
1777         // find the factors
1778         exvector factors = sqrfree_yun(tmp,x);
1779
1780         // construct the next list of symbols with the first element popped
1781         lst newargs = args;
1782         newargs.remove_first();
1783
1784         // recurse down the factors in remaining vars
1785         if (newargs.nops()>0) {
1786                 exvector::iterator i = factors.begin(), end = factors.end();
1787                 while (i != end) {
1788                         *i = sqrfree(*i, newargs);
1789                         ++i;
1790                 }
1791         }
1792
1793         // Done with recursion, now construct the final result
1794         ex result = _ex1;
1795         exvector::const_iterator it = factors.begin(), itend = factors.end();
1796         for (int p = 1; it!=itend; ++it, ++p)
1797                 result *= power(*it, p);
1798
1799         // Yun's algorithm does not account for constant factors.  (For
1800         // univariate polynomials it works only in the monic case.)  We can
1801         // correct this by inserting what has been lost back into the result:
1802         result = result * quo(tmp, result, x);
1803         return result * lcm.inverse();
1804 }
1805
1806 /** Compute square-free partial fraction decomposition of rational function
1807  *  a(x).
1808  *
1809  *  @param a rational function over Z[x], treated as univariate polynomial
1810  *           in x
1811  *  @param x variable to factor in
1812  *  @return decomposed rational function */
1813 ex sqrfree_parfrac(const ex & a, const symbol & x)
1814 {
1815         // Find numerator and denominator
1816         ex nd = numer_denom(a);
1817         ex numer = nd.op(0), denom = nd.op(1);
1818 //clog << "numer = " << numer << ", denom = " << denom << endl;
1819
1820         // Convert N(x)/D(x) -> Q(x) + R(x)/D(x), so degree(R) < degree(D)
1821         ex red_poly = quo(numer, denom, x), red_numer = rem(numer, denom, x).expand();
1822 //clog << "red_poly = " << red_poly << ", red_numer = " << red_numer << endl;
1823
1824         // Factorize denominator and compute cofactors
1825         exvector yun = sqrfree_yun(denom, x);
1826 //clog << "yun factors: " << exprseq(yun) << endl;
1827         unsigned num_yun = yun.size();
1828         exvector factor; factor.reserve(num_yun);
1829         exvector cofac; cofac.reserve(num_yun);
1830         for (unsigned i=0; i<num_yun; i++) {
1831                 if (!yun[i].is_equal(_ex1)) {
1832                         for (unsigned j=0; j<=i; j++) {
1833                                 factor.push_back(pow(yun[i], j+1));
1834                                 ex prod = _ex1;
1835                                 for (unsigned k=0; k<num_yun; k++) {
1836                                         if (k == i)
1837                                                 prod *= pow(yun[k], i-j);
1838                                         else
1839                                                 prod *= pow(yun[k], k+1);
1840                                 }
1841                                 cofac.push_back(prod.expand());
1842                         }
1843                 }
1844         }
1845         unsigned num_factors = factor.size();
1846 //clog << "factors  : " << exprseq(factor) << endl;
1847 //clog << "cofactors: " << exprseq(cofac) << endl;
1848
1849         // Construct coefficient matrix for decomposition
1850         int max_denom_deg = denom.degree(x);
1851         matrix sys(max_denom_deg + 1, num_factors);
1852         matrix rhs(max_denom_deg + 1, 1);
1853         for (int i=0; i<=max_denom_deg; i++) {
1854                 for (unsigned j=0; j<num_factors; j++)
1855                         sys(i, j) = cofac[j].coeff(x, i);
1856                 rhs(i, 0) = red_numer.coeff(x, i);
1857         }
1858 //clog << "coeffs: " << sys << endl;
1859 //clog << "rhs   : " << rhs << endl;
1860
1861         // Solve resulting linear system
1862         matrix vars(num_factors, 1);
1863         for (unsigned i=0; i<num_factors; i++)
1864                 vars(i, 0) = symbol();
1865         matrix sol = sys.solve(vars, rhs);
1866
1867         // Sum up decomposed fractions
1868         ex sum = 0;
1869         for (unsigned i=0; i<num_factors; i++)
1870                 sum += sol(i, 0) / factor[i];
1871
1872         return red_poly + sum;
1873 }
1874
1875
1876 /*
1877  *  Normal form of rational functions
1878  */
1879
1880 /*
1881  *  Note: The internal normal() functions (= basic::normal() and overloaded
1882  *  functions) all return lists of the form {numerator, denominator}. This
1883  *  is to get around mul::eval()'s automatic expansion of numeric coefficients.
1884  *  E.g. (a+b)/3 is automatically converted to a/3+b/3 but we want to keep
1885  *  the information that (a+b) is the numerator and 3 is the denominator.
1886  */
1887
1888
1889 /** Create a symbol for replacing the expression "e" (or return a previously
1890  *  assigned symbol). The symbol is appended to sym_lst and returned, the
1891  *  expression is appended to repl_lst.
1892  *  @see ex::normal */
1893 static ex replace_with_symbol(const ex &e, lst &sym_lst, lst &repl_lst)
1894 {
1895         // Expression already in repl_lst? Then return the assigned symbol
1896         for (unsigned i=0; i<repl_lst.nops(); i++)
1897                 if (repl_lst.op(i).is_equal(e))
1898                         return sym_lst.op(i);
1899         
1900         // Otherwise create new symbol and add to list, taking care that the
1901         // replacement expression doesn't contain symbols from the sym_lst
1902         // because subs() is not recursive
1903         symbol s;
1904         ex es(s);
1905         ex e_replaced = e.subs(sym_lst, repl_lst);
1906         sym_lst.append(es);
1907         repl_lst.append(e_replaced);
1908         return es;
1909 }
1910
1911 /** Create a symbol for replacing the expression "e" (or return a previously
1912  *  assigned symbol). An expression of the form "symbol == expression" is added
1913  *  to repl_lst and the symbol is returned.
1914  *  @see basic::to_rational */
1915 static ex replace_with_symbol(const ex &e, lst &repl_lst)
1916 {
1917         // Expression already in repl_lst? Then return the assigned symbol
1918         for (unsigned i=0; i<repl_lst.nops(); i++)
1919                 if (repl_lst.op(i).op(1).is_equal(e))
1920                         return repl_lst.op(i).op(0);
1921         
1922         // Otherwise create new symbol and add to list, taking care that the
1923         // replacement expression doesn't contain symbols from the sym_lst
1924         // because subs() is not recursive
1925         symbol s;
1926         ex es(s);
1927         ex e_replaced = e.subs(repl_lst);
1928         repl_lst.append(es == e_replaced);
1929         return es;
1930 }
1931
1932
1933 /** Function object to be applied by basic::normal(). */
1934 struct normal_map_function : public map_function {
1935         int level;
1936         normal_map_function(int l) : level(l) {}
1937         ex operator()(const ex & e) { return normal(e, level); }
1938 };
1939
1940 /** Default implementation of ex::normal(). It normalizes the children and
1941  *  replaces the object with a temporary symbol.
1942  *  @see ex::normal */
1943 ex basic::normal(lst &sym_lst, lst &repl_lst, int level) const
1944 {
1945         if (nops() == 0)
1946                 return (new lst(replace_with_symbol(*this, sym_lst, repl_lst), _ex1))->setflag(status_flags::dynallocated);
1947         else {
1948                 if (level == 1)
1949                         return (new lst(replace_with_symbol(*this, sym_lst, repl_lst), _ex1))->setflag(status_flags::dynallocated);
1950                 else if (level == -max_recursion_level)
1951                         throw(std::runtime_error("max recursion level reached"));
1952                 else {
1953                         normal_map_function map_normal(level - 1);
1954                         return (new lst(replace_with_symbol(map(map_normal), sym_lst, repl_lst), _ex1))->setflag(status_flags::dynallocated);
1955                 }
1956         }
1957 }
1958
1959
1960 /** Implementation of ex::normal() for symbols. This returns the unmodified symbol.
1961  *  @see ex::normal */
1962 ex symbol::normal(lst &sym_lst, lst &repl_lst, int level) const
1963 {
1964         return (new lst(*this, _ex1))->setflag(status_flags::dynallocated);
1965 }
1966
1967
1968 /** Implementation of ex::normal() for a numeric. It splits complex numbers
1969  *  into re+I*im and replaces I and non-rational real numbers with a temporary
1970  *  symbol.
1971  *  @see ex::normal */
1972 ex numeric::normal(lst &sym_lst, lst &repl_lst, int level) const
1973 {
1974         numeric num = numer();
1975         ex numex = num;
1976
1977         if (num.is_real()) {
1978                 if (!num.is_integer())
1979                         numex = replace_with_symbol(numex, sym_lst, repl_lst);
1980         } else { // complex
1981                 numeric re = num.real(), im = num.imag();
1982                 ex re_ex = re.is_rational() ? re : replace_with_symbol(re, sym_lst, repl_lst);
1983                 ex im_ex = im.is_rational() ? im : replace_with_symbol(im, sym_lst, repl_lst);
1984                 numex = re_ex + im_ex * replace_with_symbol(I, sym_lst, repl_lst);
1985         }
1986
1987         // Denominator is always a real integer (see numeric::denom())
1988         return (new lst(numex, denom()))->setflag(status_flags::dynallocated);
1989 }
1990
1991
1992 /** Fraction cancellation.
1993  *  @param n  numerator
1994  *  @param d  denominator
1995  *  @return cancelled fraction {n, d} as a list */
1996 static ex frac_cancel(const ex &n, const ex &d)
1997 {
1998         ex num = n;
1999         ex den = d;
2000         numeric pre_factor = _num1;
2001
2002 //std::clog << "frac_cancel num = " << num << ", den = " << den << std::endl;
2003
2004         // Handle trivial case where denominator is 1
2005         if (den.is_equal(_ex1))
2006                 return (new lst(num, den))->setflag(status_flags::dynallocated);
2007
2008         // Handle special cases where numerator or denominator is 0
2009         if (num.is_zero())
2010                 return (new lst(num, _ex1))->setflag(status_flags::dynallocated);
2011         if (den.expand().is_zero())
2012                 throw(std::overflow_error("frac_cancel: division by zero in frac_cancel"));
2013
2014         // Bring numerator and denominator to Z[X] by multiplying with
2015         // LCM of all coefficients' denominators
2016         numeric num_lcm = lcm_of_coefficients_denominators(num);
2017         numeric den_lcm = lcm_of_coefficients_denominators(den);
2018         num = multiply_lcm(num, num_lcm);
2019         den = multiply_lcm(den, den_lcm);
2020         pre_factor = den_lcm / num_lcm;
2021
2022         // Cancel GCD from numerator and denominator
2023         ex cnum, cden;
2024         if (gcd(num, den, &cnum, &cden, false) != _ex1) {
2025                 num = cnum;
2026                 den = cden;
2027         }
2028
2029         // Make denominator unit normal (i.e. coefficient of first symbol
2030         // as defined by get_first_symbol() is made positive)
2031         const symbol *x;
2032         if (get_first_symbol(den, x)) {
2033                 GINAC_ASSERT(is_exactly_a<numeric>(den.unit(*x)));
2034                 if (ex_to<numeric>(den.unit(*x)).is_negative()) {
2035                         num *= _ex_1;
2036                         den *= _ex_1;
2037                 }
2038         }
2039
2040         // Return result as list
2041 //std::clog << " returns num = " << num << ", den = " << den << ", pre_factor = " << pre_factor << std::endl;
2042         return (new lst(num * pre_factor.numer(), den * pre_factor.denom()))->setflag(status_flags::dynallocated);
2043 }
2044
2045
2046 /** Implementation of ex::normal() for a sum. It expands terms and performs
2047  *  fractional addition.
2048  *  @see ex::normal */
2049 ex add::normal(lst &sym_lst, lst &repl_lst, int level) const
2050 {
2051         if (level == 1)
2052                 return (new lst(replace_with_symbol(*this, sym_lst, repl_lst), _ex1))->setflag(status_flags::dynallocated);
2053         else if (level == -max_recursion_level)
2054                 throw(std::runtime_error("max recursion level reached"));
2055
2056         // Normalize children and split each one into numerator and denominator
2057         exvector nums, dens;
2058         nums.reserve(seq.size()+1);
2059         dens.reserve(seq.size()+1);
2060         epvector::const_iterator it = seq.begin(), itend = seq.end();
2061         while (it != itend) {
2062                 ex n = ex_to<basic>(recombine_pair_to_ex(*it)).normal(sym_lst, repl_lst, level-1);
2063                 nums.push_back(n.op(0));
2064                 dens.push_back(n.op(1));
2065                 it++;
2066         }
2067         ex n = ex_to<numeric>(overall_coeff).normal(sym_lst, repl_lst, level-1);
2068         nums.push_back(n.op(0));
2069         dens.push_back(n.op(1));
2070         GINAC_ASSERT(nums.size() == dens.size());
2071
2072         // Now, nums is a vector of all numerators and dens is a vector of
2073         // all denominators
2074 //std::clog << "add::normal uses " << nums.size() << " summands:\n";
2075
2076         // Add fractions sequentially
2077         exvector::const_iterator num_it = nums.begin(), num_itend = nums.end();
2078         exvector::const_iterator den_it = dens.begin(), den_itend = dens.end();
2079 //std::clog << " num = " << *num_it << ", den = " << *den_it << std::endl;
2080         ex num = *num_it++, den = *den_it++;
2081         while (num_it != num_itend) {
2082 //std::clog << " num = " << *num_it << ", den = " << *den_it << std::endl;
2083                 ex next_num = *num_it++, next_den = *den_it++;
2084
2085                 // Trivially add sequences of fractions with identical denominators
2086                 while ((den_it != den_itend) && next_den.is_equal(*den_it)) {
2087                         next_num += *num_it;
2088                         num_it++; den_it++;
2089                 }
2090
2091                 // Additiion of two fractions, taking advantage of the fact that
2092                 // the heuristic GCD algorithm computes the cofactors at no extra cost
2093                 ex co_den1, co_den2;
2094                 ex g = gcd(den, next_den, &co_den1, &co_den2, false);
2095                 num = ((num * co_den2) + (next_num * co_den1)).expand();
2096                 den *= co_den2;         // this is the lcm(den, next_den)
2097         }
2098 //std::clog << " common denominator = " << den << std::endl;
2099
2100         // Cancel common factors from num/den
2101         return frac_cancel(num, den);
2102 }
2103
2104
2105 /** Implementation of ex::normal() for a product. It cancels common factors
2106  *  from fractions.
2107  *  @see ex::normal() */
2108 ex mul::normal(lst &sym_lst, lst &repl_lst, int level) const
2109 {
2110         if (level == 1)
2111                 return (new lst(replace_with_symbol(*this, sym_lst, repl_lst), _ex1))->setflag(status_flags::dynallocated);
2112         else if (level == -max_recursion_level)
2113                 throw(std::runtime_error("max recursion level reached"));
2114
2115         // Normalize children, separate into numerator and denominator
2116         exvector num; num.reserve(seq.size());
2117         exvector den; den.reserve(seq.size());
2118         ex n;
2119         epvector::const_iterator it = seq.begin(), itend = seq.end();
2120         while (it != itend) {
2121                 n = ex_to<basic>(recombine_pair_to_ex(*it)).normal(sym_lst, repl_lst, level-1);
2122                 num.push_back(n.op(0));
2123                 den.push_back(n.op(1));
2124                 it++;
2125         }
2126         n = ex_to<numeric>(overall_coeff).normal(sym_lst, repl_lst, level-1);
2127         num.push_back(n.op(0));
2128         den.push_back(n.op(1));
2129
2130         // Perform fraction cancellation
2131         return frac_cancel((new mul(num))->setflag(status_flags::dynallocated),
2132                            (new mul(den))->setflag(status_flags::dynallocated));
2133 }
2134
2135
2136 /** Implementation of ex::normal() for powers. It normalizes the basis,
2137  *  distributes integer exponents to numerator and denominator, and replaces
2138  *  non-integer powers by temporary symbols.
2139  *  @see ex::normal */
2140 ex power::normal(lst &sym_lst, lst &repl_lst, int level) const
2141 {
2142         if (level == 1)
2143                 return (new lst(replace_with_symbol(*this, sym_lst, repl_lst), _ex1))->setflag(status_flags::dynallocated);
2144         else if (level == -max_recursion_level)
2145                 throw(std::runtime_error("max recursion level reached"));
2146
2147         // Normalize basis and exponent (exponent gets reassembled)
2148         ex n_basis = ex_to<basic>(basis).normal(sym_lst, repl_lst, level-1);
2149         ex n_exponent = ex_to<basic>(exponent).normal(sym_lst, repl_lst, level-1);
2150         n_exponent = n_exponent.op(0) / n_exponent.op(1);
2151
2152         if (n_exponent.info(info_flags::integer)) {
2153
2154                 if (n_exponent.info(info_flags::positive)) {
2155
2156                         // (a/b)^n -> {a^n, b^n}
2157                         return (new lst(power(n_basis.op(0), n_exponent), power(n_basis.op(1), n_exponent)))->setflag(status_flags::dynallocated);
2158
2159                 } else if (n_exponent.info(info_flags::negative)) {
2160
2161                         // (a/b)^-n -> {b^n, a^n}
2162                         return (new lst(power(n_basis.op(1), -n_exponent), power(n_basis.op(0), -n_exponent)))->setflag(status_flags::dynallocated);
2163                 }
2164
2165         } else {
2166
2167                 if (n_exponent.info(info_flags::positive)) {
2168
2169                         // (a/b)^x -> {sym((a/b)^x), 1}
2170                         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);
2171
2172                 } else if (n_exponent.info(info_flags::negative)) {
2173
2174                         if (n_basis.op(1).is_equal(_ex1)) {
2175
2176                                 // a^-x -> {1, sym(a^x)}
2177                                 return (new lst(_ex1, replace_with_symbol(power(n_basis.op(0), -n_exponent), sym_lst, repl_lst)))->setflag(status_flags::dynallocated);
2178
2179                         } else {
2180
2181                                 // (a/b)^-x -> {sym((b/a)^x), 1}
2182                                 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);
2183                         }
2184
2185                 } else {        // n_exponent not numeric
2186
2187                         // (a/b)^x -> {sym((a/b)^x, 1}
2188                         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);
2189                 }
2190         }
2191 }
2192
2193
2194 /** Implementation of ex::normal() for pseries. It normalizes each coefficient
2195  *  and replaces the series by a temporary symbol.
2196  *  @see ex::normal */
2197 ex pseries::normal(lst &sym_lst, lst &repl_lst, int level) const
2198 {
2199         epvector newseq;
2200         epvector::const_iterator i = seq.begin(), end = seq.end();
2201         while (i != end) {
2202                 ex restexp = i->rest.normal();
2203                 if (!restexp.is_zero())
2204                         newseq.push_back(expair(restexp, i->coeff));
2205                 ++i;
2206         }
2207         ex n = pseries(relational(var,point), newseq);
2208         return (new lst(replace_with_symbol(n, sym_lst, repl_lst), _ex1))->setflag(status_flags::dynallocated);
2209 }
2210
2211
2212 /** Normalization of rational functions.
2213  *  This function converts an expression to its normal form
2214  *  "numerator/denominator", where numerator and denominator are (relatively
2215  *  prime) polynomials. Any subexpressions which are not rational functions
2216  *  (like non-rational numbers, non-integer powers or functions like sin(),
2217  *  cos() etc.) are replaced by temporary symbols which are re-substituted by
2218  *  the (normalized) subexpressions before normal() returns (this way, any
2219  *  expression can be treated as a rational function). normal() is applied
2220  *  recursively to arguments of functions etc.
2221  *
2222  *  @param level maximum depth of recursion
2223  *  @return normalized expression */
2224 ex ex::normal(int level) const
2225 {
2226         lst sym_lst, repl_lst;
2227
2228         ex e = bp->normal(sym_lst, repl_lst, level);
2229         GINAC_ASSERT(is_a<lst>(e));
2230
2231         // Re-insert replaced symbols
2232         if (sym_lst.nops() > 0)
2233                 e = e.subs(sym_lst, repl_lst);
2234
2235         // Convert {numerator, denominator} form back to fraction
2236         return e.op(0) / e.op(1);
2237 }
2238
2239 /** Get numerator of an expression. If the expression is not of the normal
2240  *  form "numerator/denominator", it is first converted to this form and
2241  *  then the numerator is returned.
2242  *
2243  *  @see ex::normal
2244  *  @return numerator */
2245 ex ex::numer(void) const
2246 {
2247         lst sym_lst, repl_lst;
2248
2249         ex e = bp->normal(sym_lst, repl_lst, 0);
2250         GINAC_ASSERT(is_a<lst>(e));
2251
2252         // Re-insert replaced symbols
2253         if (sym_lst.nops() > 0)
2254                 return e.op(0).subs(sym_lst, repl_lst);
2255         else
2256                 return e.op(0);
2257 }
2258
2259 /** Get denominator of an expression. If the expression is not of the normal
2260  *  form "numerator/denominator", it is first converted to this form and
2261  *  then the denominator is returned.
2262  *
2263  *  @see ex::normal
2264  *  @return denominator */
2265 ex ex::denom(void) const
2266 {
2267         lst sym_lst, repl_lst;
2268
2269         ex e = bp->normal(sym_lst, repl_lst, 0);
2270         GINAC_ASSERT(is_a<lst>(e));
2271
2272         // Re-insert replaced symbols
2273         if (sym_lst.nops() > 0)
2274                 return e.op(1).subs(sym_lst, repl_lst);
2275         else
2276                 return e.op(1);
2277 }
2278
2279 /** Get numerator and denominator of an expression. If the expresison is not
2280  *  of the normal form "numerator/denominator", it is first converted to this
2281  *  form and then a list [numerator, denominator] is returned.
2282  *
2283  *  @see ex::normal
2284  *  @return a list [numerator, denominator] */
2285 ex ex::numer_denom(void) const
2286 {
2287         lst sym_lst, repl_lst;
2288
2289         ex e = bp->normal(sym_lst, repl_lst, 0);
2290         GINAC_ASSERT(is_a<lst>(e));
2291
2292         // Re-insert replaced symbols
2293         if (sym_lst.nops() > 0)
2294                 return e.subs(sym_lst, repl_lst);
2295         else
2296                 return e;
2297 }
2298
2299
2300 /** Rationalization of non-rational functions.
2301  *  This function converts a general expression to a rational polynomial
2302  *  by replacing all non-rational subexpressions (like non-rational numbers,
2303  *  non-integer powers or functions like sin(), cos() etc.) to temporary
2304  *  symbols. This makes it possible to use functions like gcd() and divide()
2305  *  on non-rational functions by applying to_rational() on the arguments,
2306  *  calling the desired function and re-substituting the temporary symbols
2307  *  in the result. To make the last step possible, all temporary symbols and
2308  *  their associated expressions are collected in the list specified by the
2309  *  repl_lst parameter in the form {symbol == expression}, ready to be passed
2310  *  as an argument to ex::subs().
2311  *
2312  *  @param repl_lst collects a list of all temporary symbols and their replacements
2313  *  @return rationalized expression */
2314 ex basic::to_rational(lst &repl_lst) const
2315 {
2316         return replace_with_symbol(*this, repl_lst);
2317 }
2318
2319
2320 /** Implementation of ex::to_rational() for symbols. This returns the
2321  *  unmodified symbol. */
2322 ex symbol::to_rational(lst &repl_lst) const
2323 {
2324         return *this;
2325 }
2326
2327
2328 /** Implementation of ex::to_rational() for a numeric. It splits complex
2329  *  numbers into re+I*im and replaces I and non-rational real numbers with a
2330  *  temporary symbol. */
2331 ex numeric::to_rational(lst &repl_lst) const
2332 {
2333         if (is_real()) {
2334                 if (!is_rational())
2335                         return replace_with_symbol(*this, repl_lst);
2336         } else { // complex
2337                 numeric re = real();
2338                 numeric im = imag();
2339                 ex re_ex = re.is_rational() ? re : replace_with_symbol(re, repl_lst);
2340                 ex im_ex = im.is_rational() ? im : replace_with_symbol(im, repl_lst);
2341                 return re_ex + im_ex * replace_with_symbol(I, repl_lst);
2342         }
2343         return *this;
2344 }
2345
2346
2347 /** Implementation of ex::to_rational() for powers. It replaces non-integer
2348  *  powers by temporary symbols. */
2349 ex power::to_rational(lst &repl_lst) const
2350 {
2351         if (exponent.info(info_flags::integer))
2352                 return power(basis.to_rational(repl_lst), exponent);
2353         else
2354                 return replace_with_symbol(*this, repl_lst);
2355 }
2356
2357
2358 /** Implementation of ex::to_rational() for expairseqs. */
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 } // namespace GiNaC