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