]> www.ginac.de Git - ginac.git/blob - ginac/normal.cpp
- modified printcsrc() example
[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-2000 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 <stdexcept>
27 #include <algorithm>
28 #include <map>
29
30 #include "normal.h"
31 #include "basic.h"
32 #include "ex.h"
33 #include "add.h"
34 #include "constant.h"
35 #include "expairseq.h"
36 #include "fail.h"
37 #include "indexed.h"
38 #include "inifcns.h"
39 #include "lst.h"
40 #include "mul.h"
41 #include "ncmul.h"
42 #include "numeric.h"
43 #include "power.h"
44 #include "relational.h"
45 #include "pseries.h"
46 #include "symbol.h"
47 #include "utils.h"
48
49 #ifndef NO_NAMESPACE_GINAC
50 namespace GiNaC {
51 #endif // ndef NO_NAMESPACE_GINAC
52
53 // If comparing expressions (ex::compare()) is fast, you can set this to 1.
54 // Some routines like quo(), rem() and gcd() will then return a quick answer
55 // when they are called with two identical arguments.
56 #define FAST_COMPARE 1
57
58 // Set this if you want divide_in_z() to use remembering
59 #define USE_REMEMBER 0
60
61 // Set this if you want divide_in_z() to use trial division followed by
62 // polynomial interpolation (usually slower except for very large problems)
63 #define USE_TRIAL_DIVISION 0
64
65 // Set this to enable some statistical output for the GCD routines
66 #define STATISTICS 0
67
68
69 #if STATISTICS
70 // Statistics variables
71 static int gcd_called = 0;
72 static int sr_gcd_called = 0;
73 static int heur_gcd_called = 0;
74 static int heur_gcd_failed = 0;
75
76 // Print statistics at end of program
77 static struct _stat_print {
78         _stat_print() {}
79         ~_stat_print() {
80                 cout << "gcd() called " << gcd_called << " times\n";
81                 cout << "sr_gcd() called " << sr_gcd_called << " times\n";
82                 cout << "heur_gcd() called " << heur_gcd_called << " times\n";
83                 cout << "heur_gcd() failed " << heur_gcd_failed << " times\n";
84         }
85 } stat_print;
86 #endif
87
88
89 /** Return pointer to first symbol found in expression.  Due to GiNaCĀ“s
90  *  internal ordering of terms, it may not be obvious which symbol this
91  *  function returns for a given expression.
92  *
93  *  @param e  expression to search
94  *  @param x  pointer to first symbol found (returned)
95  *  @return "false" if no symbol was found, "true" otherwise */
96
97 static bool get_first_symbol(const ex &e, const symbol *&x)
98 {
99     if (is_ex_exactly_of_type(e, symbol)) {
100         x = static_cast<symbol *>(e.bp);
101         return true;
102     } else if (is_ex_exactly_of_type(e, add) || is_ex_exactly_of_type(e, mul)) {
103         for (unsigned i=0; i<e.nops(); i++)
104             if (get_first_symbol(e.op(i), x))
105                 return true;
106     } else if (is_ex_exactly_of_type(e, power)) {
107         if (get_first_symbol(e.op(0), x))
108             return true;
109     }
110     return false;
111 }
112
113
114 /*
115  *  Statistical information about symbols in polynomials
116  */
117
118 /** This structure holds information about the highest and lowest degrees
119  *  in which a symbol appears in two multivariate polynomials "a" and "b".
120  *  A vector of these structures with information about all symbols in
121  *  two polynomials can be created with the function get_symbol_stats().
122  *
123  *  @see get_symbol_stats */
124 struct sym_desc {
125     /** Pointer to symbol */
126     const symbol *sym;
127
128     /** Highest degree of symbol in polynomial "a" */
129     int deg_a;
130
131     /** Highest degree of symbol in polynomial "b" */
132     int deg_b;
133
134     /** Lowest degree of symbol in polynomial "a" */
135     int ldeg_a;
136
137     /** Lowest degree of symbol in polynomial "b" */
138     int ldeg_b;
139
140     /** Minimum of ldeg_a and ldeg_b (Used for sorting) */
141     int min_deg;
142
143     /** Commparison operator for sorting */
144     bool operator<(const sym_desc &x) const {return min_deg < x.min_deg;}
145 };
146
147 // Vector of sym_desc structures
148 typedef vector<sym_desc> sym_desc_vec;
149
150 // Add symbol the sym_desc_vec (used internally by get_symbol_stats())
151 static void add_symbol(const symbol *s, sym_desc_vec &v)
152 {
153     sym_desc_vec::iterator it = v.begin(), itend = v.end();
154     while (it != itend) {
155         if (it->sym->compare(*s) == 0)  // If it's already in there, don't add it a second time
156             return;
157         it++;
158     }
159     sym_desc d;
160     d.sym = s;
161     v.push_back(d);
162 }
163
164 // Collect all symbols of an expression (used internally by get_symbol_stats())
165 static void collect_symbols(const ex &e, sym_desc_vec &v)
166 {
167     if (is_ex_exactly_of_type(e, symbol)) {
168         add_symbol(static_cast<symbol *>(e.bp), v);
169     } else if (is_ex_exactly_of_type(e, add) || is_ex_exactly_of_type(e, mul)) {
170         for (unsigned i=0; i<e.nops(); i++)
171             collect_symbols(e.op(i), v);
172     } else if (is_ex_exactly_of_type(e, power)) {
173         collect_symbols(e.op(0), v);
174     }
175 }
176
177 /** Collect statistical information about symbols in polynomials.
178  *  This function fills in a vector of "sym_desc" structs which contain
179  *  information about the highest and lowest degrees of all symbols that
180  *  appear in two polynomials. The vector is then sorted by minimum
181  *  degree (lowest to highest). The information gathered by this
182  *  function is used by the GCD routines to identify trivial factors
183  *  and to determine which variable to choose as the main variable
184  *  for GCD computation.
185  *
186  *  @param a  first multivariate polynomial
187  *  @param b  second multivariate polynomial
188  *  @param v  vector of sym_desc structs (filled in) */
189
190 static void get_symbol_stats(const ex &a, const ex &b, sym_desc_vec &v)
191 {
192     collect_symbols(a.eval(), v);   // eval() to expand assigned symbols
193     collect_symbols(b.eval(), v);
194     sym_desc_vec::iterator it = v.begin(), itend = v.end();
195     while (it != itend) {
196         int deg_a = a.degree(*(it->sym));
197         int deg_b = b.degree(*(it->sym));
198         it->deg_a = deg_a;
199         it->deg_b = deg_b;
200         it->min_deg = min(deg_a, deg_b);
201         it->ldeg_a = a.ldegree(*(it->sym));
202         it->ldeg_b = b.ldegree(*(it->sym));
203         it++;
204     }
205     sort(v.begin(), v.end());
206 }
207
208
209 /*
210  *  Computation of LCM of denominators of coefficients of a polynomial
211  */
212
213 // Compute LCM of denominators of coefficients by going through the
214 // expression recursively (used internally by lcm_of_coefficients_denominators())
215 static numeric lcmcoeff(const ex &e, const numeric &l)
216 {
217     if (e.info(info_flags::rational))
218         return lcm(ex_to_numeric(e).denom(), l);
219     else if (is_ex_exactly_of_type(e, add)) {
220         numeric c = _num1();
221         for (unsigned i=0; i<e.nops(); i++)
222             c = lcmcoeff(e.op(i), c);
223         return lcm(c, l);
224     } else if (is_ex_exactly_of_type(e, mul)) {
225         numeric c = _num1();
226         for (unsigned i=0; i<e.nops(); i++)
227             c *= lcmcoeff(e.op(i), _num1());
228         return lcm(c, l);
229     } else if (is_ex_exactly_of_type(e, power))
230         return pow(lcmcoeff(e.op(0), l), ex_to_numeric(e.op(1)));
231     return l;
232 }
233
234 /** Compute LCM of denominators of coefficients of a polynomial.
235  *  Given a polynomial with rational coefficients, this function computes
236  *  the LCM of the denominators of all coefficients. This can be used
237  *  to bring a polynomial from Q[X] to Z[X].
238  *
239  *  @param e  multivariate polynomial (need not be expanded)
240  *  @return LCM of denominators of coefficients */
241
242 static numeric lcm_of_coefficients_denominators(const ex &e)
243 {
244     return lcmcoeff(e, _num1());
245 }
246
247 /** Bring polynomial from Q[X] to Z[X] by multiplying in the previously
248  *  determined LCM of the coefficient's denominators.
249  *
250  *  @param e  multivariate polynomial (need not be expanded)
251  *  @param lcm  LCM to multiply in */
252
253 static ex multiply_lcm(const ex &e, const numeric &lcm)
254 {
255         if (is_ex_exactly_of_type(e, mul)) {
256                 ex c = _ex1();
257                 numeric lcm_accum = _num1();
258                 for (unsigned i=0; i<e.nops(); i++) {
259                         numeric op_lcm = lcmcoeff(e.op(i), _num1());
260                         c *= multiply_lcm(e.op(i), op_lcm);
261                         lcm_accum *= op_lcm;
262                 }
263                 c *= lcm / lcm_accum;
264                 return c;
265         } else if (is_ex_exactly_of_type(e, add)) {
266                 ex c = _ex0();
267                 for (unsigned i=0; i<e.nops(); i++)
268                         c += multiply_lcm(e.op(i), lcm);
269                 return c;
270         } else if (is_ex_exactly_of_type(e, power)) {
271                 return pow(multiply_lcm(e.op(0), lcm.power(ex_to_numeric(e.op(1)).inverse())), e.op(1));
272         } else
273                 return e * lcm;
274 }
275
276
277 /** Compute the integer content (= GCD of all numeric coefficients) of an
278  *  expanded polynomial.
279  *
280  *  @param e  expanded polynomial
281  *  @return integer content */
282
283 numeric ex::integer_content(void) const
284 {
285     GINAC_ASSERT(bp!=0);
286     return bp->integer_content();
287 }
288
289 numeric basic::integer_content(void) const
290 {
291     return _num1();
292 }
293
294 numeric numeric::integer_content(void) const
295 {
296     return abs(*this);
297 }
298
299 numeric add::integer_content(void) const
300 {
301     epvector::const_iterator it = seq.begin();
302     epvector::const_iterator itend = seq.end();
303     numeric c = _num0();
304     while (it != itend) {
305         GINAC_ASSERT(!is_ex_exactly_of_type(it->rest,numeric));
306         GINAC_ASSERT(is_ex_exactly_of_type(it->coeff,numeric));
307         c = gcd(ex_to_numeric(it->coeff), c);
308         it++;
309     }
310     GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
311     c = gcd(ex_to_numeric(overall_coeff),c);
312     return c;
313 }
314
315 numeric mul::integer_content(void) const
316 {
317 #ifdef DO_GINAC_ASSERT
318     epvector::const_iterator it = seq.begin();
319     epvector::const_iterator itend = seq.end();
320     while (it != itend) {
321         GINAC_ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*it),numeric));
322         ++it;
323     }
324 #endif // def DO_GINAC_ASSERT
325     GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
326     return abs(ex_to_numeric(overall_coeff));
327 }
328
329
330 /*
331  *  Polynomial quotients and remainders
332  */
333
334 /** Quotient q(x) of polynomials a(x) and b(x) in Q[x].
335  *  It satisfies a(x)=b(x)*q(x)+r(x).
336  *
337  *  @param a  first polynomial in x (dividend)
338  *  @param b  second polynomial in x (divisor)
339  *  @param x  a and b are polynomials in x
340  *  @param check_args  check whether a and b are polynomials with rational
341  *         coefficients (defaults to "true")
342  *  @return quotient of a and b in Q[x] */
343
344 ex quo(const ex &a, const ex &b, const symbol &x, bool check_args)
345 {
346     if (b.is_zero())
347         throw(std::overflow_error("quo: division by zero"));
348     if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric))
349         return a / b;
350 #if FAST_COMPARE
351     if (a.is_equal(b))
352         return _ex1();
353 #endif
354     if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
355         throw(std::invalid_argument("quo: arguments must be polynomials over the rationals"));
356
357     // Polynomial long division
358     ex q = _ex0();
359     ex r = a.expand();
360     if (r.is_zero())
361         return r;
362     int bdeg = b.degree(x);
363     int rdeg = r.degree(x);
364     ex blcoeff = b.expand().coeff(x, bdeg);
365     bool blcoeff_is_numeric = is_ex_exactly_of_type(blcoeff, numeric);
366     while (rdeg >= bdeg) {
367         ex term, rcoeff = r.coeff(x, rdeg);
368         if (blcoeff_is_numeric)
369             term = rcoeff / blcoeff;
370         else {
371             if (!divide(rcoeff, blcoeff, term, false))
372                 return *new ex(fail());
373         }
374         term *= power(x, rdeg - bdeg);
375         q += term;
376         r -= (term * b).expand();
377         if (r.is_zero())
378             break;
379         rdeg = r.degree(x);
380     }
381     return q;
382 }
383
384
385 /** Remainder r(x) of polynomials a(x) and b(x) in Q[x].
386  *  It satisfies a(x)=b(x)*q(x)+r(x).
387  *
388  *  @param a  first polynomial in x (dividend)
389  *  @param b  second polynomial in x (divisor)
390  *  @param x  a and b are polynomials in x
391  *  @param check_args  check whether a and b are polynomials with rational
392  *         coefficients (defaults to "true")
393  *  @return remainder of a(x) and b(x) in Q[x] */
394
395 ex rem(const ex &a, const ex &b, const symbol &x, bool check_args)
396 {
397     if (b.is_zero())
398         throw(std::overflow_error("rem: division by zero"));
399     if (is_ex_exactly_of_type(a, numeric)) {
400         if  (is_ex_exactly_of_type(b, numeric))
401             return _ex0();
402         else
403             return b;
404     }
405 #if FAST_COMPARE
406     if (a.is_equal(b))
407         return _ex0();
408 #endif
409     if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
410         throw(std::invalid_argument("rem: arguments must be polynomials over the rationals"));
411
412     // Polynomial long division
413     ex r = a.expand();
414     if (r.is_zero())
415         return r;
416     int bdeg = b.degree(x);
417     int rdeg = r.degree(x);
418     ex blcoeff = b.expand().coeff(x, bdeg);
419     bool blcoeff_is_numeric = is_ex_exactly_of_type(blcoeff, numeric);
420     while (rdeg >= bdeg) {
421         ex term, rcoeff = r.coeff(x, rdeg);
422         if (blcoeff_is_numeric)
423             term = rcoeff / blcoeff;
424         else {
425             if (!divide(rcoeff, blcoeff, term, false))
426                 return *new ex(fail());
427         }
428         term *= power(x, rdeg - bdeg);
429         r -= (term * b).expand();
430         if (r.is_zero())
431             break;
432         rdeg = r.degree(x);
433     }
434     return r;
435 }
436
437
438 /** Pseudo-remainder of polynomials a(x) and b(x) in Z[x].
439  *
440  *  @param a  first polynomial in x (dividend)
441  *  @param b  second polynomial in x (divisor)
442  *  @param x  a and b are polynomials in x
443  *  @param check_args  check whether a and b are polynomials with rational
444  *         coefficients (defaults to "true")
445  *  @return pseudo-remainder of a(x) and b(x) in Z[x] */
446
447 ex prem(const ex &a, const ex &b, const symbol &x, bool check_args)
448 {
449     if (b.is_zero())
450         throw(std::overflow_error("prem: division by zero"));
451     if (is_ex_exactly_of_type(a, numeric)) {
452         if (is_ex_exactly_of_type(b, numeric))
453             return _ex0();
454         else
455             return b;
456     }
457     if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
458         throw(std::invalid_argument("prem: arguments must be polynomials over the rationals"));
459
460     // Polynomial long division
461     ex r = a.expand();
462     ex eb = b.expand();
463     int rdeg = r.degree(x);
464     int bdeg = eb.degree(x);
465     ex blcoeff;
466     if (bdeg <= rdeg) {
467         blcoeff = eb.coeff(x, bdeg);
468         if (bdeg == 0)
469             eb = _ex0();
470         else
471             eb -= blcoeff * power(x, bdeg);
472     } else
473         blcoeff = _ex1();
474
475     int delta = rdeg - bdeg + 1, i = 0;
476     while (rdeg >= bdeg && !r.is_zero()) {
477         ex rlcoeff = r.coeff(x, rdeg);
478         ex term = (power(x, rdeg - bdeg) * eb * rlcoeff).expand();
479         if (rdeg == 0)
480             r = _ex0();
481         else
482             r -= rlcoeff * power(x, rdeg);
483         r = (blcoeff * r).expand() - term;
484         rdeg = r.degree(x);
485         i++;
486     }
487     return power(blcoeff, delta - i) * r;
488 }
489
490
491 /** Exact polynomial division of a(X) by b(X) in Q[X].
492  *  
493  *  @param a  first multivariate polynomial (dividend)
494  *  @param b  second multivariate polynomial (divisor)
495  *  @param q  quotient (returned)
496  *  @param check_args  check whether a and b are polynomials with rational
497  *         coefficients (defaults to "true")
498  *  @return "true" when exact division succeeds (quotient returned in q),
499  *          "false" otherwise */
500
501 bool divide(const ex &a, const ex &b, ex &q, bool check_args)
502 {
503     q = _ex0();
504     if (b.is_zero())
505         throw(std::overflow_error("divide: division by zero"));
506     if (is_ex_exactly_of_type(b, numeric)) {
507         q = a / b;
508         return true;
509     } else if (is_ex_exactly_of_type(a, numeric))
510         return false;
511 #if FAST_COMPARE
512     if (a.is_equal(b)) {
513         q = _ex1();
514         return true;
515     }
516 #endif
517     if (check_args && (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)))
518         throw(std::invalid_argument("divide: arguments must be polynomials over the rationals"));
519
520     // Find first symbol
521     const symbol *x;
522     if (!get_first_symbol(a, x) && !get_first_symbol(b, x))
523         throw(std::invalid_argument("invalid expression in divide()"));
524
525     // Polynomial long division (recursive)
526     ex r = a.expand();
527     if (r.is_zero())
528         return true;
529     int bdeg = b.degree(*x);
530     int rdeg = r.degree(*x);
531     ex blcoeff = b.expand().coeff(*x, bdeg);
532     bool blcoeff_is_numeric = is_ex_exactly_of_type(blcoeff, numeric);
533     while (rdeg >= bdeg) {
534         ex term, rcoeff = r.coeff(*x, rdeg);
535         if (blcoeff_is_numeric)
536             term = rcoeff / blcoeff;
537         else
538             if (!divide(rcoeff, blcoeff, term, false))
539                 return false;
540         term *= power(*x, rdeg - bdeg);
541         q += term;
542         r -= (term * b).expand();
543         if (r.is_zero())
544             return true;
545         rdeg = r.degree(*x);
546     }
547     return false;
548 }
549
550
551 #if USE_REMEMBER
552 /*
553  *  Remembering
554  */
555
556 typedef pair<ex, ex> ex2;
557 typedef pair<ex, bool> exbool;
558
559 struct ex2_less {
560     bool operator() (const ex2 p, const ex2 q) const 
561     {
562         return p.first.compare(q.first) < 0 || (!(q.first.compare(p.first) < 0) && p.second.compare(q.second) < 0);        
563     }
564 };
565
566 typedef map<ex2, exbool, ex2_less> ex2_exbool_remember;
567 #endif
568
569
570 /** Exact polynomial division of a(X) by b(X) in Z[X].
571  *  This functions works like divide() but the input and output polynomials are
572  *  in Z[X] instead of Q[X] (i.e. they have integer coefficients). Unlike
573  *  divide(), it doesnĀ“t check whether the input polynomials really are integer
574  *  polynomials, so be careful of what you pass in. Also, you have to run
575  *  get_symbol_stats() over the input polynomials before calling this function
576  *  and pass an iterator to the first element of the sym_desc vector. This
577  *  function is used internally by the heur_gcd().
578  *  
579  *  @param a  first multivariate polynomial (dividend)
580  *  @param b  second multivariate polynomial (divisor)
581  *  @param q  quotient (returned)
582  *  @param var  iterator to first element of vector of sym_desc structs
583  *  @return "true" when exact division succeeds (the quotient is returned in
584  *          q), "false" otherwise.
585  *  @see get_symbol_stats, heur_gcd */
586 static bool divide_in_z(const ex &a, const ex &b, ex &q, sym_desc_vec::const_iterator var)
587 {
588     q = _ex0();
589     if (b.is_zero())
590         throw(std::overflow_error("divide_in_z: division by zero"));
591     if (b.is_equal(_ex1())) {
592         q = a;
593         return true;
594     }
595     if (is_ex_exactly_of_type(a, numeric)) {
596         if (is_ex_exactly_of_type(b, numeric)) {
597             q = a / b;
598             return q.info(info_flags::integer);
599         } else
600             return false;
601     }
602 #if FAST_COMPARE
603     if (a.is_equal(b)) {
604         q = _ex1();
605         return true;
606     }
607 #endif
608
609 #if USE_REMEMBER
610     // Remembering
611     static ex2_exbool_remember dr_remember;
612     ex2_exbool_remember::const_iterator remembered = dr_remember.find(ex2(a, b));
613     if (remembered != dr_remember.end()) {
614         q = remembered->second.first;
615         return remembered->second.second;
616     }
617 #endif
618
619     // Main symbol
620     const symbol *x = var->sym;
621
622     // Compare degrees
623     int adeg = a.degree(*x), bdeg = b.degree(*x);
624     if (bdeg > adeg)
625         return false;
626
627 #if USE_TRIAL_DIVISION
628
629     // Trial division with polynomial interpolation
630     int i, k;
631
632     // Compute values at evaluation points 0..adeg
633     vector<numeric> alpha; alpha.reserve(adeg + 1);
634     exvector u; u.reserve(adeg + 1);
635     numeric point = _num0();
636     ex c;
637     for (i=0; i<=adeg; i++) {
638         ex bs = b.subs(*x == point);
639         while (bs.is_zero()) {
640             point += _num1();
641             bs = b.subs(*x == point);
642         }
643         if (!divide_in_z(a.subs(*x == point), bs, c, var+1))
644             return false;
645         alpha.push_back(point);
646         u.push_back(c);
647         point += _num1();
648     }
649
650     // Compute inverses
651     vector<numeric> rcp; rcp.reserve(adeg + 1);
652     rcp.push_back(_num0());
653     for (k=1; k<=adeg; k++) {
654         numeric product = alpha[k] - alpha[0];
655         for (i=1; i<k; i++)
656             product *= alpha[k] - alpha[i];
657         rcp.push_back(product.inverse());
658     }
659
660     // Compute Newton coefficients
661     exvector v; v.reserve(adeg + 1);
662     v.push_back(u[0]);
663     for (k=1; k<=adeg; k++) {
664         ex temp = v[k - 1];
665         for (i=k-2; i>=0; i--)
666             temp = temp * (alpha[k] - alpha[i]) + v[i];
667         v.push_back((u[k] - temp) * rcp[k]);
668     }
669
670     // Convert from Newton form to standard form
671     c = v[adeg];
672     for (k=adeg-1; k>=0; k--)
673         c = c * (*x - alpha[k]) + v[k];
674
675     if (c.degree(*x) == (adeg - bdeg)) {
676         q = c.expand();
677         return true;
678     } else
679         return false;
680
681 #else
682
683     // Polynomial long division (recursive)
684     ex r = a.expand();
685     if (r.is_zero())
686         return true;
687     int rdeg = adeg;
688     ex eb = b.expand();
689     ex blcoeff = eb.coeff(*x, bdeg);
690     while (rdeg >= bdeg) {
691         ex term, rcoeff = r.coeff(*x, rdeg);
692         if (!divide_in_z(rcoeff, blcoeff, term, var+1))
693             break;
694         term = (term * power(*x, rdeg - bdeg)).expand();
695         q += term;
696         r -= (term * eb).expand();
697         if (r.is_zero()) {
698 #if USE_REMEMBER
699             dr_remember[ex2(a, b)] = exbool(q, true);
700 #endif
701             return true;
702         }
703         rdeg = r.degree(*x);
704     }
705 #if USE_REMEMBER
706     dr_remember[ex2(a, b)] = exbool(q, false);
707 #endif
708     return false;
709
710 #endif
711 }
712
713
714 /*
715  *  Separation of unit part, content part and primitive part of polynomials
716  */
717
718 /** Compute unit part (= sign of leading coefficient) of a multivariate
719  *  polynomial in Z[x]. The product of unit part, content part, and primitive
720  *  part is the polynomial itself.
721  *
722  *  @param x  variable in which to compute the unit part
723  *  @return unit part
724  *  @see ex::content, ex::primpart */
725 ex ex::unit(const symbol &x) const
726 {
727     ex c = expand().lcoeff(x);
728     if (is_ex_exactly_of_type(c, numeric))
729         return c < _ex0() ? _ex_1() : _ex1();
730     else {
731         const symbol *y;
732         if (get_first_symbol(c, y))
733             return c.unit(*y);
734         else
735             throw(std::invalid_argument("invalid expression in unit()"));
736     }
737 }
738
739
740 /** Compute content part (= unit normal GCD of all coefficients) of a
741  *  multivariate polynomial in Z[x].  The product of unit part, content part,
742  *  and primitive part is the polynomial itself.
743  *
744  *  @param x  variable in which to compute the content part
745  *  @return content part
746  *  @see ex::unit, ex::primpart */
747 ex ex::content(const symbol &x) const
748 {
749     if (is_zero())
750         return _ex0();
751     if (is_ex_exactly_of_type(*this, numeric))
752         return info(info_flags::negative) ? -*this : *this;
753     ex e = expand();
754     if (e.is_zero())
755         return _ex0();
756
757     // First, try the integer content
758     ex c = e.integer_content();
759     ex r = e / c;
760     ex lcoeff = r.lcoeff(x);
761     if (lcoeff.info(info_flags::integer))
762         return c;
763
764     // GCD of all coefficients
765     int deg = e.degree(x);
766     int ldeg = e.ldegree(x);
767     if (deg == ldeg)
768         return e.lcoeff(x) / e.unit(x);
769     c = _ex0();
770     for (int i=ldeg; i<=deg; i++)
771         c = gcd(e.coeff(x, i), c, NULL, NULL, false);
772     return c;
773 }
774
775
776 /** Compute primitive part of a multivariate polynomial in Z[x].
777  *  The product of unit part, content part, and primitive part is the
778  *  polynomial itself.
779  *
780  *  @param x  variable in which to compute the primitive part
781  *  @return primitive part
782  *  @see ex::unit, ex::content */
783 ex ex::primpart(const symbol &x) const
784 {
785     if (is_zero())
786         return _ex0();
787     if (is_ex_exactly_of_type(*this, numeric))
788         return _ex1();
789
790     ex c = content(x);
791     if (c.is_zero())
792         return _ex0();
793     ex u = unit(x);
794     if (is_ex_exactly_of_type(c, numeric))
795         return *this / (c * u);
796     else
797         return quo(*this, c * u, x, false);
798 }
799
800
801 /** Compute primitive part of a multivariate polynomial in Z[x] when the
802  *  content part is already known. This function is faster in computing the
803  *  primitive part than the previous function.
804  *
805  *  @param x  variable in which to compute the primitive part
806  *  @param c  previously computed content part
807  *  @return primitive part */
808
809 ex ex::primpart(const symbol &x, const ex &c) const
810 {
811     if (is_zero())
812         return _ex0();
813     if (c.is_zero())
814         return _ex0();
815     if (is_ex_exactly_of_type(*this, numeric))
816         return _ex1();
817
818     ex u = unit(x);
819     if (is_ex_exactly_of_type(c, numeric))
820         return *this / (c * u);
821     else
822         return quo(*this, c * u, x, false);
823 }
824
825
826 /*
827  *  GCD of multivariate polynomials
828  */
829
830 /** Compute GCD of multivariate polynomials using the subresultant PRS
831  *  algorithm. This function is used internally gy gcd().
832  *
833  *  @param a  first multivariate polynomial
834  *  @param b  second multivariate polynomial
835  *  @param x  pointer to symbol (main variable) in which to compute the GCD in
836  *  @return the GCD as a new expression
837  *  @see gcd */
838
839 static ex sr_gcd(const ex &a, const ex &b, const symbol *x)
840 {
841 //clog << "sr_gcd(" << a << "," << b << ")\n";
842 #if STATISTICS
843         sr_gcd_called++;
844 #endif
845
846     // Sort c and d so that c has higher degree
847     ex c, d;
848     int adeg = a.degree(*x), bdeg = b.degree(*x);
849     int cdeg, ddeg;
850     if (adeg >= bdeg) {
851         c = a;
852         d = b;
853         cdeg = adeg;
854         ddeg = bdeg;
855     } else {
856         c = b;
857         d = a;
858         cdeg = bdeg;
859         ddeg = adeg;
860     }
861
862     // Remove content from c and d, to be attached to GCD later
863     ex cont_c = c.content(*x);
864     ex cont_d = d.content(*x);
865     ex gamma = gcd(cont_c, cont_d, NULL, NULL, false);
866     if (ddeg == 0)
867         return gamma;
868     c = c.primpart(*x, cont_c);
869     d = d.primpart(*x, cont_d);
870 //clog << " content " << gamma << " removed, continuing with sr_gcd(" << c << "," << d << ")\n";
871
872     // First element of subresultant sequence
873     ex r = _ex0(), ri = _ex1(), psi = _ex1();
874     int delta = cdeg - ddeg;
875
876     for (;;) {
877         // Calculate polynomial pseudo-remainder
878 //clog << " start of loop, psi = " << psi << ", calculating pseudo-remainder...\n";
879         r = prem(c, d, *x, false);
880         if (r.is_zero())
881             return gamma * d.primpart(*x);
882         c = d;
883         cdeg = ddeg;
884 //clog << " dividing...\n";
885         if (!divide(r, ri * power(psi, delta), d, false))
886             throw(std::runtime_error("invalid expression in sr_gcd(), division failed"));
887         ddeg = d.degree(*x);
888         if (ddeg == 0) {
889             if (is_ex_exactly_of_type(r, numeric))
890                 return gamma;
891             else
892                 return gamma * r.primpart(*x);
893         }
894
895         // Next element of subresultant sequence
896 //clog << " calculating next subresultant...\n";
897         ri = c.expand().lcoeff(*x);
898         if (delta == 1)
899             psi = ri;
900         else if (delta)
901             divide(power(ri, delta), power(psi, delta-1), psi, false);
902         delta = cdeg - ddeg;
903     }
904 }
905
906
907 /** Return maximum (absolute value) coefficient of a polynomial.
908  *  This function is used internally by heur_gcd().
909  *
910  *  @param e  expanded multivariate polynomial
911  *  @return maximum coefficient
912  *  @see heur_gcd */
913
914 numeric ex::max_coefficient(void) const
915 {
916     GINAC_ASSERT(bp!=0);
917     return bp->max_coefficient();
918 }
919
920 numeric basic::max_coefficient(void) const
921 {
922     return _num1();
923 }
924
925 numeric numeric::max_coefficient(void) const
926 {
927     return abs(*this);
928 }
929
930 numeric add::max_coefficient(void) const
931 {
932     epvector::const_iterator it = seq.begin();
933     epvector::const_iterator itend = seq.end();
934     GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
935     numeric cur_max = abs(ex_to_numeric(overall_coeff));
936     while (it != itend) {
937         numeric a;
938         GINAC_ASSERT(!is_ex_exactly_of_type(it->rest,numeric));
939         a = abs(ex_to_numeric(it->coeff));
940         if (a > cur_max)
941             cur_max = a;
942         it++;
943     }
944     return cur_max;
945 }
946
947 numeric mul::max_coefficient(void) const
948 {
949 #ifdef DO_GINAC_ASSERT
950     epvector::const_iterator it = seq.begin();
951     epvector::const_iterator itend = seq.end();
952     while (it != itend) {
953         GINAC_ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*it),numeric));
954         it++;
955     }
956 #endif // def DO_GINAC_ASSERT
957     GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
958     return abs(ex_to_numeric(overall_coeff));
959 }
960
961
962 /** Apply symmetric modular homomorphism to a multivariate polynomial.
963  *  This function is used internally by heur_gcd().
964  *
965  *  @param e  expanded multivariate polynomial
966  *  @param xi  modulus
967  *  @return mapped polynomial
968  *  @see heur_gcd */
969
970 ex ex::smod(const numeric &xi) const
971 {
972     GINAC_ASSERT(bp!=0);
973     return bp->smod(xi);
974 }
975
976 ex basic::smod(const numeric &xi) const
977 {
978     return *this;
979 }
980
981 ex numeric::smod(const numeric &xi) const
982 {
983 #ifndef NO_NAMESPACE_GINAC
984     return GiNaC::smod(*this, xi);
985 #else // ndef NO_NAMESPACE_GINAC
986     return ::smod(*this, xi);
987 #endif // ndef NO_NAMESPACE_GINAC
988 }
989
990 ex add::smod(const numeric &xi) const
991 {
992     epvector newseq;
993     newseq.reserve(seq.size()+1);
994     epvector::const_iterator it = seq.begin();
995     epvector::const_iterator itend = seq.end();
996     while (it != itend) {
997         GINAC_ASSERT(!is_ex_exactly_of_type(it->rest,numeric));
998 #ifndef NO_NAMESPACE_GINAC
999         numeric coeff = GiNaC::smod(ex_to_numeric(it->coeff), xi);
1000 #else // ndef NO_NAMESPACE_GINAC
1001         numeric coeff = ::smod(ex_to_numeric(it->coeff), xi);
1002 #endif // ndef NO_NAMESPACE_GINAC
1003         if (!coeff.is_zero())
1004             newseq.push_back(expair(it->rest, coeff));
1005         it++;
1006     }
1007     GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
1008 #ifndef NO_NAMESPACE_GINAC
1009     numeric coeff = GiNaC::smod(ex_to_numeric(overall_coeff), xi);
1010 #else // ndef NO_NAMESPACE_GINAC
1011     numeric coeff = ::smod(ex_to_numeric(overall_coeff), xi);
1012 #endif // ndef NO_NAMESPACE_GINAC
1013     return (new add(newseq,coeff))->setflag(status_flags::dynallocated);
1014 }
1015
1016 ex mul::smod(const numeric &xi) const
1017 {
1018 #ifdef DO_GINAC_ASSERT
1019     epvector::const_iterator it = seq.begin();
1020     epvector::const_iterator itend = seq.end();
1021     while (it != itend) {
1022         GINAC_ASSERT(!is_ex_exactly_of_type(recombine_pair_to_ex(*it),numeric));
1023         it++;
1024     }
1025 #endif // def DO_GINAC_ASSERT
1026     mul * mulcopyp=new mul(*this);
1027     GINAC_ASSERT(is_ex_exactly_of_type(overall_coeff,numeric));
1028 #ifndef NO_NAMESPACE_GINAC
1029     mulcopyp->overall_coeff = GiNaC::smod(ex_to_numeric(overall_coeff),xi);
1030 #else // ndef NO_NAMESPACE_GINAC
1031     mulcopyp->overall_coeff = ::smod(ex_to_numeric(overall_coeff),xi);
1032 #endif // ndef NO_NAMESPACE_GINAC
1033     mulcopyp->clearflag(status_flags::evaluated);
1034     mulcopyp->clearflag(status_flags::hash_calculated);
1035     return mulcopyp->setflag(status_flags::dynallocated);
1036 }
1037
1038
1039 /** Exception thrown by heur_gcd() to signal failure. */
1040 class gcdheu_failed {};
1041
1042 /** Compute GCD of multivariate polynomials using the heuristic GCD algorithm.
1043  *  get_symbol_stats() must have been called previously with the input
1044  *  polynomials and an iterator to the first element of the sym_desc vector
1045  *  passed in. This function is used internally by gcd().
1046  *
1047  *  @param a  first multivariate polynomial (expanded)
1048  *  @param b  second multivariate polynomial (expanded)
1049  *  @param ca  cofactor of polynomial a (returned), NULL to suppress
1050  *             calculation of cofactor
1051  *  @param cb  cofactor of polynomial b (returned), NULL to suppress
1052  *             calculation of cofactor
1053  *  @param var iterator to first element of vector of sym_desc structs
1054  *  @return the GCD as a new expression
1055  *  @see gcd
1056  *  @exception gcdheu_failed() */
1057
1058 static ex heur_gcd(const ex &a, const ex &b, ex *ca, ex *cb, sym_desc_vec::const_iterator var)
1059 {
1060 //clog << "heur_gcd(" << a << "," << b << ")\n";
1061 #if STATISTICS
1062         heur_gcd_called++;
1063 #endif
1064
1065         // GCD of two numeric values -> CLN
1066     if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric)) {
1067         numeric g = gcd(ex_to_numeric(a), ex_to_numeric(b));
1068         numeric rg;
1069         if (ca || cb)
1070             rg = g.inverse();
1071         if (ca)
1072             *ca = ex_to_numeric(a).mul(rg);
1073         if (cb)
1074             *cb = ex_to_numeric(b).mul(rg);
1075         return g;
1076     }
1077
1078     // The first symbol is our main variable
1079     const symbol *x = var->sym;
1080
1081     // Remove integer content
1082     numeric gc = gcd(a.integer_content(), b.integer_content());
1083     numeric rgc = gc.inverse();
1084     ex p = a * rgc;
1085     ex q = b * rgc;
1086     int maxdeg = max(p.degree(*x), q.degree(*x));
1087
1088     // Find evaluation point
1089     numeric mp = p.max_coefficient(), mq = q.max_coefficient();
1090     numeric xi;
1091     if (mp > mq)
1092         xi = mq * _num2() + _num2();
1093     else
1094         xi = mp * _num2() + _num2();
1095
1096     // 6 tries maximum
1097     for (int t=0; t<6; t++) {
1098         if (xi.int_length() * maxdeg > 100000) {
1099 //clog << "giving up heur_gcd, xi.int_length = " << xi.int_length() << ", maxdeg = " << maxdeg << endl;
1100             throw gcdheu_failed();
1101                 }
1102
1103         // Apply evaluation homomorphism and calculate GCD
1104         ex gamma = heur_gcd(p.subs(*x == xi), q.subs(*x == xi), NULL, NULL, var+1).expand();
1105         if (!is_ex_exactly_of_type(gamma, fail)) {
1106
1107             // Reconstruct polynomial from GCD of mapped polynomials
1108             ex g = _ex0();
1109             numeric rxi = xi.inverse();
1110             for (int i=0; !gamma.is_zero(); i++) {
1111                 ex gi = gamma.smod(xi);
1112                 g += gi * power(*x, i);
1113                 gamma = (gamma - gi) * rxi;
1114             }
1115             // Remove integer content
1116             g /= g.integer_content();
1117
1118             // If the calculated polynomial divides both a and b, this is the GCD
1119             ex dummy;
1120             if (divide_in_z(p, g, ca ? *ca : dummy, var) && divide_in_z(q, g, cb ? *cb : dummy, var)) {
1121                 g *= gc;
1122                 ex lc = g.lcoeff(*x);
1123                 if (is_ex_exactly_of_type(lc, numeric) && ex_to_numeric(lc).is_negative())
1124                     return -g;
1125                 else
1126                     return g;
1127             }
1128         }
1129
1130         // Next evaluation point
1131         xi = iquo(xi * isqrt(isqrt(xi)) * numeric(73794), numeric(27011));
1132     }
1133     return *new ex(fail());
1134 }
1135
1136
1137 /** Compute GCD (Greatest Common Divisor) of multivariate polynomials a(X)
1138  *  and b(X) in Z[X].
1139  *
1140  *  @param a  first multivariate polynomial
1141  *  @param b  second multivariate polynomial
1142  *  @param check_args  check whether a and b are polynomials with rational
1143  *         coefficients (defaults to "true")
1144  *  @return the GCD as a new expression */
1145
1146 ex gcd(const ex &a, const ex &b, ex *ca, ex *cb, bool check_args)
1147 {
1148 //clog << "gcd(" << a << "," << b << ")\n";
1149 #if STATISTICS
1150         gcd_called++;
1151 #endif
1152
1153         // GCD of numerics -> CLN
1154     if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric)) {
1155         numeric g = gcd(ex_to_numeric(a), ex_to_numeric(b));
1156         if (ca)
1157             *ca = ex_to_numeric(a) / g;
1158         if (cb)
1159             *cb = ex_to_numeric(b) / g;
1160         return g;
1161     }
1162
1163         // Check arguments
1164     if (check_args && !a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial)) {
1165         throw(std::invalid_argument("gcd: arguments must be polynomials over the rationals"));
1166     }
1167
1168         // Partially factored cases (to avoid expanding large expressions)
1169         if (is_ex_exactly_of_type(a, mul)) {
1170                 if (is_ex_exactly_of_type(b, mul) && b.nops() > a.nops())
1171                         goto factored_b;
1172 factored_a:
1173                 ex g = _ex1();
1174                 ex acc_ca = _ex1();
1175                 ex part_b = b;
1176                 for (unsigned i=0; i<a.nops(); i++) {
1177                         ex part_ca, part_cb;
1178                         g *= gcd(a.op(i), part_b, &part_ca, &part_cb, check_args);
1179                         acc_ca *= part_ca;
1180                         part_b = part_cb;
1181                 }
1182                 if (ca)
1183                         *ca = acc_ca;
1184                 if (cb)
1185                         *cb = part_b;
1186                 return g;
1187         } else if (is_ex_exactly_of_type(b, mul)) {
1188                 if (is_ex_exactly_of_type(a, mul) && a.nops() > b.nops())
1189                         goto factored_a;
1190 factored_b:
1191                 ex g = _ex1();
1192                 ex acc_cb = _ex1();
1193                 ex part_a = a;
1194                 for (unsigned i=0; i<b.nops(); i++) {
1195                         ex part_ca, part_cb;
1196                         g *= gcd(part_a, b.op(i), &part_ca, &part_cb, check_args);
1197                         acc_cb *= part_cb;
1198                         part_a = part_ca;
1199                 }
1200                 if (ca)
1201                         *ca = part_a;
1202                 if (cb)
1203                         *cb = acc_cb;
1204                 return g;
1205         }
1206
1207 #if FAST_COMPARE
1208         // Input polynomials of the form poly^n are sometimes also trivial
1209         if (is_ex_exactly_of_type(a, power)) {
1210                 ex p = a.op(0);
1211                 if (is_ex_exactly_of_type(b, power)) {
1212                         if (p.is_equal(b.op(0))) {
1213                                 // a = p^n, b = p^m, gcd = p^min(n, m)
1214                                 ex exp_a = a.op(1), exp_b = b.op(1);
1215                                 if (exp_a < exp_b) {
1216                                         if (ca)
1217                                                 *ca = _ex1();
1218                                         if (cb)
1219                                                 *cb = power(p, exp_b - exp_a);
1220                                         return power(p, exp_a);
1221                                 } else {
1222                                         if (ca)
1223                                                 *ca = power(p, exp_a - exp_b);
1224                                         if (cb)
1225                                                 *cb = _ex1();
1226                                         return power(p, exp_b);
1227                                 }
1228                         }
1229                 } else {
1230                         if (p.is_equal(b)) {
1231                                 // a = p^n, b = p, gcd = p
1232                                 if (ca)
1233                                         *ca = power(p, a.op(1) - 1);
1234                                 if (cb)
1235                                         *cb = _ex1();
1236                                 return p;
1237                         }
1238                 }
1239         } else if (is_ex_exactly_of_type(b, power)) {
1240                 ex p = b.op(0);
1241                 if (p.is_equal(a)) {
1242                         // a = p, b = p^n, gcd = p
1243                         if (ca)
1244                                 *ca = _ex1();
1245                         if (cb)
1246                                 *cb = power(p, b.op(1) - 1);
1247                         return p;
1248                 }
1249         }
1250 #endif
1251
1252     // Some trivial cases
1253         ex aex = a.expand(), bex = b.expand();
1254     if (aex.is_zero()) {
1255         if (ca)
1256             *ca = _ex0();
1257         if (cb)
1258             *cb = _ex1();
1259         return b;
1260     }
1261     if (bex.is_zero()) {
1262         if (ca)
1263             *ca = _ex1();
1264         if (cb)
1265             *cb = _ex0();
1266         return a;
1267     }
1268     if (aex.is_equal(_ex1()) || bex.is_equal(_ex1())) {
1269         if (ca)
1270             *ca = a;
1271         if (cb)
1272             *cb = b;
1273         return _ex1();
1274     }
1275 #if FAST_COMPARE
1276     if (a.is_equal(b)) {
1277         if (ca)
1278             *ca = _ex1();
1279         if (cb)
1280             *cb = _ex1();
1281         return a;
1282     }
1283 #endif
1284
1285     // Gather symbol statistics
1286     sym_desc_vec sym_stats;
1287     get_symbol_stats(a, b, sym_stats);
1288
1289     // The symbol with least degree is our main variable
1290     sym_desc_vec::const_iterator var = sym_stats.begin();
1291     const symbol *x = var->sym;
1292
1293     // Cancel trivial common factor
1294     int ldeg_a = var->ldeg_a;
1295     int ldeg_b = var->ldeg_b;
1296     int min_ldeg = min(ldeg_a, ldeg_b);
1297     if (min_ldeg > 0) {
1298         ex common = power(*x, min_ldeg);
1299 //clog << "trivial common factor " << common << endl;
1300         return gcd((aex / common).expand(), (bex / common).expand(), ca, cb, false) * common;
1301     }
1302
1303     // Try to eliminate variables
1304     if (var->deg_a == 0) {
1305 //clog << "eliminating variable " << *x << " from b" << endl;
1306         ex c = bex.content(*x);
1307         ex g = gcd(aex, c, ca, cb, false);
1308         if (cb)
1309             *cb *= bex.unit(*x) * bex.primpart(*x, c);
1310         return g;
1311     } else if (var->deg_b == 0) {
1312 //clog << "eliminating variable " << *x << " from a" << endl;
1313         ex c = aex.content(*x);
1314         ex g = gcd(c, bex, ca, cb, false);
1315         if (ca)
1316             *ca *= aex.unit(*x) * aex.primpart(*x, c);
1317         return g;
1318     }
1319
1320     // Try heuristic algorithm first, fall back to PRS if that failed
1321     ex g;
1322     try {
1323         g = heur_gcd(aex, bex, ca, cb, var);
1324     } catch (gcdheu_failed) {
1325         g = *new ex(fail());
1326     }
1327     if (is_ex_exactly_of_type(g, fail)) {
1328 //clog << "heuristics failed" << endl;
1329 #if STATISTICS
1330                 heur_gcd_failed++;
1331 #endif
1332         g = sr_gcd(aex, bex, x);
1333                 if (g.is_equal(_ex1())) {
1334                         // Keep cofactors factored if possible
1335                         if (ca)
1336                                 *ca = a;
1337                         if (cb)
1338                                 *cb = b;
1339                 } else {
1340                 if (ca)
1341                     divide(aex, g, *ca, false);
1342                 if (cb)
1343                     divide(bex, g, *cb, false);
1344                 }
1345     } else {
1346                 if (g.is_equal(_ex1())) {
1347                         // Keep cofactors factored if possible
1348                         if (ca)
1349                                 *ca = a;
1350                         if (cb)
1351                                 *cb = b;
1352                 }
1353             return g;
1354         }
1355 }
1356
1357
1358 /** Compute LCM (Least Common Multiple) of multivariate polynomials in Z[X].
1359  *
1360  *  @param a  first multivariate polynomial
1361  *  @param b  second multivariate polynomial
1362  *  @param check_args  check whether a and b are polynomials with rational
1363  *         coefficients (defaults to "true")
1364  *  @return the LCM as a new expression */
1365 ex lcm(const ex &a, const ex &b, bool check_args)
1366 {
1367     if (is_ex_exactly_of_type(a, numeric) && is_ex_exactly_of_type(b, numeric))
1368         return lcm(ex_to_numeric(a), ex_to_numeric(b));
1369     if (check_args && !a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial))
1370         throw(std::invalid_argument("lcm: arguments must be polynomials over the rationals"));
1371     
1372     ex ca, cb;
1373     ex g = gcd(a, b, &ca, &cb, false);
1374     return ca * cb * g;
1375 }
1376
1377
1378 /*
1379  *  Square-free factorization
1380  */
1381
1382 // Univariate GCD of polynomials in Q[x] (used internally by sqrfree()).
1383 // a and b can be multivariate polynomials but they are treated as univariate polynomials in x.
1384 static ex univariate_gcd(const ex &a, const ex &b, const symbol &x)
1385 {
1386     if (a.is_zero())
1387         return b;
1388     if (b.is_zero())
1389         return a;
1390     if (a.is_equal(_ex1()) || b.is_equal(_ex1()))
1391         return _ex1();
1392     if (is_ex_of_type(a, numeric) && is_ex_of_type(b, numeric))
1393         return gcd(ex_to_numeric(a), ex_to_numeric(b));
1394     if (!a.info(info_flags::rational_polynomial) || !b.info(info_flags::rational_polynomial))
1395         throw(std::invalid_argument("univariate_gcd: arguments must be polynomials over the rationals"));
1396
1397     // Euclidean algorithm
1398     ex c, d, r;
1399     if (a.degree(x) >= b.degree(x)) {
1400         c = a;
1401         d = b;
1402     } else {
1403         c = b;
1404         d = a;
1405     }
1406     for (;;) {
1407         r = rem(c, d, x, false);
1408         if (r.is_zero())
1409             break;
1410         c = d;
1411         d = r;
1412     }
1413     return d / d.lcoeff(x);
1414 }
1415
1416
1417 /** Compute square-free factorization of multivariate polynomial a(x) using
1418  *  YunĀ“s algorithm.
1419  *
1420  * @param a  multivariate polynomial
1421  * @param x  variable to factor in
1422  * @return factored polynomial */
1423 ex sqrfree(const ex &a, const symbol &x)
1424 {
1425     int i = 1;
1426     ex res = _ex1();
1427     ex b = a.diff(x);
1428     ex c = univariate_gcd(a, b, x);
1429     ex w;
1430     if (c.is_equal(_ex1())) {
1431         w = a;
1432     } else {
1433         w = quo(a, c, x);
1434         ex y = quo(b, c, x);
1435         ex z = y - w.diff(x);
1436         while (!z.is_zero()) {
1437             ex g = univariate_gcd(w, z, x);
1438             res *= power(g, i);
1439             w = quo(w, g, x);
1440             y = quo(z, g, x);
1441             z = y - w.diff(x);
1442             i++;
1443         }
1444     }
1445     return res * power(w, i);
1446 }
1447
1448
1449 /*
1450  *  Normal form of rational functions
1451  */
1452
1453 /*
1454  *  Note: The internal normal() functions (= basic::normal() and overloaded
1455  *  functions) all return lists of the form {numerator, denominator}. This
1456  *  is to get around mul::eval()'s automatic expansion of numeric coefficients.
1457  *  E.g. (a+b)/3 is automatically converted to a/3+b/3 but we want to keep
1458  *  the information that (a+b) is the numerator and 3 is the denominator.
1459  */
1460
1461 /** Create a symbol for replacing the expression "e" (or return a previously
1462  *  assigned symbol). The symbol is appended to sym_lst and returned, the
1463  *  expression is appended to repl_lst.
1464  *  @see ex::normal */
1465 static ex replace_with_symbol(const ex &e, lst &sym_lst, lst &repl_lst)
1466 {
1467     // Expression already in repl_lst? Then return the assigned symbol
1468     for (unsigned i=0; i<repl_lst.nops(); i++)
1469         if (repl_lst.op(i).is_equal(e))
1470             return sym_lst.op(i);
1471
1472     // Otherwise create new symbol and add to list, taking care that the
1473         // replacement expression doesn't contain symbols from the sym_lst
1474         // because subs() is not recursive
1475         symbol s;
1476         ex es(s);
1477         ex e_replaced = e.subs(sym_lst, repl_lst);
1478     sym_lst.append(es);
1479     repl_lst.append(e_replaced);
1480     return es;
1481 }
1482
1483 /** Create a symbol for replacing the expression "e" (or return a previously
1484  *  assigned symbol). An expression of the form "symbol == expression" is added
1485  *  to repl_lst and the symbol is returned.
1486  *  @see ex::to_rational */
1487 static ex replace_with_symbol(const ex &e, lst &repl_lst)
1488 {
1489     // Expression already in repl_lst? Then return the assigned symbol
1490     for (unsigned i=0; i<repl_lst.nops(); i++)
1491         if (repl_lst.op(i).op(1).is_equal(e))
1492             return repl_lst.op(i).op(0);
1493
1494     // Otherwise create new symbol and add to list, taking care that the
1495         // replacement expression doesn't contain symbols from the sym_lst
1496         // because subs() is not recursive
1497         symbol s;
1498         ex es(s);
1499         ex e_replaced = e.subs(repl_lst);
1500     repl_lst.append(es == e_replaced);
1501     return es;
1502 }
1503
1504 /** Default implementation of ex::normal(). It replaces the object with a
1505  *  temporary symbol.
1506  *  @see ex::normal */
1507 ex basic::normal(lst &sym_lst, lst &repl_lst, int level) const
1508 {
1509     return (new lst(replace_with_symbol(*this, sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
1510 }
1511
1512
1513 /** Implementation of ex::normal() for symbols. This returns the unmodified symbol.
1514  *  @see ex::normal */
1515 ex symbol::normal(lst &sym_lst, lst &repl_lst, int level) const
1516 {
1517     return (new lst(*this, _ex1()))->setflag(status_flags::dynallocated);
1518 }
1519
1520
1521 /** Implementation of ex::normal() for a numeric. It splits complex numbers
1522  *  into re+I*im and replaces I and non-rational real numbers with a temporary
1523  *  symbol.
1524  *  @see ex::normal */
1525 ex numeric::normal(lst &sym_lst, lst &repl_lst, int level) const
1526 {
1527         numeric num = numer();
1528         ex numex = num;
1529
1530     if (num.is_real()) {
1531         if (!num.is_integer())
1532             numex = replace_with_symbol(numex, sym_lst, repl_lst);
1533     } else { // complex
1534         numeric re = num.real(), im = num.imag();
1535         ex re_ex = re.is_rational() ? re : replace_with_symbol(re, sym_lst, repl_lst);
1536         ex im_ex = im.is_rational() ? im : replace_with_symbol(im, sym_lst, repl_lst);
1537         numex = re_ex + im_ex * replace_with_symbol(I, sym_lst, repl_lst);
1538     }
1539
1540         // Denominator is always a real integer (see numeric::denom())
1541         return (new lst(numex, denom()))->setflag(status_flags::dynallocated);
1542 }
1543
1544
1545 /** Fraction cancellation.
1546  *  @param n  numerator
1547  *  @param d  denominator
1548  *  @return cancelled fraction {n, d} as a list */
1549 static ex frac_cancel(const ex &n, const ex &d)
1550 {
1551     ex num = n;
1552     ex den = d;
1553     numeric pre_factor = _num1();
1554
1555 //clog << "frac_cancel num = " << num << ", den = " << den << endl;
1556
1557     // Handle special cases where numerator or denominator is 0
1558     if (num.is_zero())
1559                 return (new lst(_ex0(), _ex1()))->setflag(status_flags::dynallocated);
1560     if (den.expand().is_zero())
1561         throw(std::overflow_error("frac_cancel: division by zero in frac_cancel"));
1562
1563     // Bring numerator and denominator to Z[X] by multiplying with
1564     // LCM of all coefficients' denominators
1565     numeric num_lcm = lcm_of_coefficients_denominators(num);
1566     numeric den_lcm = lcm_of_coefficients_denominators(den);
1567         num = multiply_lcm(num, num_lcm);
1568         den = multiply_lcm(den, den_lcm);
1569     pre_factor = den_lcm / num_lcm;
1570
1571     // Cancel GCD from numerator and denominator
1572     ex cnum, cden;
1573     if (gcd(num, den, &cnum, &cden, false) != _ex1()) {
1574                 num = cnum;
1575                 den = cden;
1576         }
1577
1578         // Make denominator unit normal (i.e. coefficient of first symbol
1579         // as defined by get_first_symbol() is made positive)
1580         const symbol *x;
1581         if (get_first_symbol(den, x)) {
1582                 GINAC_ASSERT(is_ex_exactly_of_type(den.unit(*x),numeric));
1583                 if (ex_to_numeric(den.unit(*x)).is_negative()) {
1584                         num *= _ex_1();
1585                         den *= _ex_1();
1586                 }
1587         }
1588
1589         // Return result as list
1590 //clog << " returns num = " << num << ", den = " << den << ", pre_factor = " << pre_factor << endl;
1591     return (new lst(num * pre_factor.numer(), den * pre_factor.denom()))->setflag(status_flags::dynallocated);
1592 }
1593
1594
1595 /** Implementation of ex::normal() for a sum. It expands terms and performs
1596  *  fractional addition.
1597  *  @see ex::normal */
1598 ex add::normal(lst &sym_lst, lst &repl_lst, int level) const
1599 {
1600     // Normalize and expand children, chop into summands
1601     exvector o;
1602     o.reserve(seq.size()+1);
1603     epvector::const_iterator it = seq.begin(), itend = seq.end();
1604     while (it != itend) {
1605
1606                 // Normalize and expand child
1607         ex n = recombine_pair_to_ex(*it).bp->normal(sym_lst, repl_lst, level-1).expand();
1608
1609                 // If numerator is a sum, chop into summands
1610         if (is_ex_exactly_of_type(n.op(0), add)) {
1611             epvector::const_iterator bit = ex_to_add(n.op(0)).seq.begin(), bitend = ex_to_add(n.op(0)).seq.end();
1612             while (bit != bitend) {
1613                 o.push_back((new lst(recombine_pair_to_ex(*bit), n.op(1)))->setflag(status_flags::dynallocated));
1614                 bit++;
1615             }
1616
1617                         // The overall_coeff is already normalized (== rational), we just
1618                         // split it into numerator and denominator
1619                         GINAC_ASSERT(ex_to_numeric(ex_to_add(n.op(0)).overall_coeff).is_rational());
1620                         numeric overall = ex_to_numeric(ex_to_add(n.op(0)).overall_coeff);
1621             o.push_back((new lst(overall.numer(), overall.denom() * n.op(1)))->setflag(status_flags::dynallocated));
1622         } else
1623             o.push_back(n);
1624         it++;
1625     }
1626     o.push_back(overall_coeff.bp->normal(sym_lst, repl_lst, level-1));
1627
1628         // o is now a vector of {numerator, denominator} lists
1629
1630     // Determine common denominator
1631     ex den = _ex1();
1632     exvector::const_iterator ait = o.begin(), aitend = o.end();
1633 //clog << "add::normal uses the following summands:\n";
1634     while (ait != aitend) {
1635 //clog << " num = " << ait->op(0) << ", den = " << ait->op(1) << endl;
1636         den = lcm(ait->op(1), den, false);
1637         ait++;
1638     }
1639 //clog << " common denominator = " << den << endl;
1640
1641     // Add fractions
1642     if (den.is_equal(_ex1())) {
1643
1644                 // Common denominator is 1, simply add all numerators
1645         exvector num_seq;
1646                 for (ait=o.begin(); ait!=aitend; ait++) {
1647                         num_seq.push_back(ait->op(0));
1648                 }
1649                 return (new lst((new add(num_seq))->setflag(status_flags::dynallocated), den))->setflag(status_flags::dynallocated);
1650
1651         } else {
1652
1653                 // Perform fractional addition
1654         exvector num_seq;
1655         for (ait=o.begin(); ait!=aitend; ait++) {
1656             ex q;
1657             if (!divide(den, ait->op(1), q, false)) {
1658                 // should not happen
1659                 throw(std::runtime_error("invalid expression in add::normal, division failed"));
1660             }
1661             num_seq.push_back((ait->op(0) * q).expand());
1662         }
1663         ex num = (new add(num_seq))->setflag(status_flags::dynallocated);
1664
1665         // Cancel common factors from num/den
1666         return frac_cancel(num, den);
1667     }
1668 }
1669
1670
1671 /** Implementation of ex::normal() for a product. It cancels common factors
1672  *  from fractions.
1673  *  @see ex::normal() */
1674 ex mul::normal(lst &sym_lst, lst &repl_lst, int level) const
1675 {
1676     // Normalize children, separate into numerator and denominator
1677         ex num = _ex1();
1678         ex den = _ex1(); 
1679         ex n;
1680     epvector::const_iterator it = seq.begin(), itend = seq.end();
1681     while (it != itend) {
1682                 n = recombine_pair_to_ex(*it).bp->normal(sym_lst, repl_lst, level-1);
1683                 num *= n.op(0);
1684                 den *= n.op(1);
1685         it++;
1686     }
1687         n = overall_coeff.bp->normal(sym_lst, repl_lst, level-1);
1688         num *= n.op(0);
1689         den *= n.op(1);
1690
1691         // Perform fraction cancellation
1692     return frac_cancel(num, den);
1693 }
1694
1695
1696 /** Implementation of ex::normal() for powers. It normalizes the basis,
1697  *  distributes integer exponents to numerator and denominator, and replaces
1698  *  non-integer powers by temporary symbols.
1699  *  @see ex::normal */
1700 ex power::normal(lst &sym_lst, lst &repl_lst, int level) const
1701 {
1702         // Normalize basis
1703     ex n = basis.bp->normal(sym_lst, repl_lst, level-1);
1704
1705         if (exponent.info(info_flags::integer)) {
1706
1707             if (exponent.info(info_flags::positive)) {
1708
1709                         // (a/b)^n -> {a^n, b^n}
1710                         return (new lst(power(n.op(0), exponent), power(n.op(1), exponent)))->setflag(status_flags::dynallocated);
1711
1712                 } else if (exponent.info(info_flags::negative)) {
1713
1714                         // (a/b)^-n -> {b^n, a^n}
1715                         return (new lst(power(n.op(1), -exponent), power(n.op(0), -exponent)))->setflag(status_flags::dynallocated);
1716                 }
1717
1718         } else {
1719
1720                 if (exponent.info(info_flags::positive)) {
1721
1722                         // (a/b)^x -> {sym((a/b)^x), 1}
1723                         return (new lst(replace_with_symbol(power(n.op(0) / n.op(1), exponent), sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
1724
1725                 } else if (exponent.info(info_flags::negative)) {
1726
1727                         if (n.op(1).is_equal(_ex1())) {
1728
1729                                 // a^-x -> {1, sym(a^x)}
1730                                 return (new lst(_ex1(), replace_with_symbol(power(n.op(0), -exponent), sym_lst, repl_lst)))->setflag(status_flags::dynallocated);
1731
1732                         } else {
1733
1734                                 // (a/b)^-x -> {sym((b/a)^x), 1}
1735                                 return (new lst(replace_with_symbol(power(n.op(1) / n.op(0), -exponent), sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
1736                         }
1737
1738                 } else {        // exponent not numeric
1739
1740                         // (a/b)^x -> {sym((a/b)^x, 1}
1741                         return (new lst(replace_with_symbol(power(n.op(0) / n.op(1), exponent), sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
1742                 }
1743     }
1744 }
1745
1746
1747 /** Implementation of ex::normal() for pseries. It normalizes each coefficient and
1748  *  replaces the series by a temporary symbol.
1749  *  @see ex::normal */
1750 ex pseries::normal(lst &sym_lst, lst &repl_lst, int level) const
1751 {
1752     epvector new_seq;
1753     new_seq.reserve(seq.size());
1754
1755     epvector::const_iterator it = seq.begin(), itend = seq.end();
1756     while (it != itend) {
1757         new_seq.push_back(expair(it->rest.normal(), it->coeff));
1758         it++;
1759     }
1760     ex n = pseries(relational(var,point), new_seq);
1761         return (new lst(replace_with_symbol(n, sym_lst, repl_lst), _ex1()))->setflag(status_flags::dynallocated);
1762 }
1763
1764
1765 /** Normalization of rational functions.
1766  *  This function converts an expression to its normal form
1767  *  "numerator/denominator", where numerator and denominator are (relatively
1768  *  prime) polynomials. Any subexpressions which are not rational functions
1769  *  (like non-rational numbers, non-integer powers or functions like sin(),
1770  *  cos() etc.) are replaced by temporary symbols which are re-substituted by
1771  *  the (normalized) subexpressions before normal() returns (this way, any
1772  *  expression can be treated as a rational function). normal() is applied
1773  *  recursively to arguments of functions etc.
1774  *
1775  *  @param level maximum depth of recursion
1776  *  @return normalized expression */
1777 ex ex::normal(int level) const
1778 {
1779     lst sym_lst, repl_lst;
1780
1781     ex e = bp->normal(sym_lst, repl_lst, level);
1782         GINAC_ASSERT(is_ex_of_type(e, lst));
1783
1784         // Re-insert replaced symbols
1785     if (sym_lst.nops() > 0)
1786         e = e.subs(sym_lst, repl_lst);
1787
1788         // Convert {numerator, denominator} form back to fraction
1789     return e.op(0) / e.op(1);
1790 }
1791
1792 /** Numerator of an expression. If the expression is not of the normal form
1793  *  "numerator/denominator", it is first converted to this form and then the
1794  *  numerator is returned.
1795  *
1796  *  @see ex::normal
1797  *  @return numerator */
1798 ex ex::numer(void) const
1799 {
1800     lst sym_lst, repl_lst;
1801
1802     ex e = bp->normal(sym_lst, repl_lst, 0);
1803         GINAC_ASSERT(is_ex_of_type(e, lst));
1804
1805         // Re-insert replaced symbols
1806     if (sym_lst.nops() > 0)
1807         return e.op(0).subs(sym_lst, repl_lst);
1808         else
1809                 return e.op(0);
1810 }
1811
1812 /** Denominator of an expression. If the expression is not of the normal form
1813  *  "numerator/denominator", it is first converted to this form and then the
1814  *  denominator is returned.
1815  *
1816  *  @see ex::normal
1817  *  @return denominator */
1818 ex ex::denom(void) const
1819 {
1820     lst sym_lst, repl_lst;
1821
1822     ex e = bp->normal(sym_lst, repl_lst, 0);
1823         GINAC_ASSERT(is_ex_of_type(e, lst));
1824
1825         // Re-insert replaced symbols
1826     if (sym_lst.nops() > 0)
1827         return e.op(1).subs(sym_lst, repl_lst);
1828         else
1829                 return e.op(1);
1830 }
1831
1832
1833 /** Default implementation of ex::to_rational(). It replaces the object with a
1834  *  temporary symbol.
1835  *  @see ex::to_rational */
1836 ex basic::to_rational(lst &repl_lst) const
1837 {
1838         return replace_with_symbol(*this, repl_lst);
1839 }
1840
1841
1842 /** Implementation of ex::to_rational() for symbols. This returns the unmodified symbol.
1843  *  @see ex::to_rational */
1844 ex symbol::to_rational(lst &repl_lst) const
1845 {
1846     return *this;
1847 }
1848
1849
1850 /** Implementation of ex::to_rational() for a numeric. It splits complex numbers
1851  *  into re+I*im and replaces I and non-rational real numbers with a temporary
1852  *  symbol.
1853  *  @see ex::to_rational */
1854 ex numeric::to_rational(lst &repl_lst) const
1855 {
1856         numeric num = numer();
1857         ex numex = num;
1858
1859     if (num.is_real()) {
1860         if (!num.is_integer())
1861             numex = replace_with_symbol(numex, repl_lst);
1862     } else { // complex
1863         numeric re = num.real(), im = num.imag();
1864         ex re_ex = re.is_rational() ? re : replace_with_symbol(re, repl_lst);
1865         ex im_ex = im.is_rational() ? im : replace_with_symbol(im, repl_lst);
1866         numex = re_ex + im_ex * replace_with_symbol(I, repl_lst);
1867     }
1868         return numex;
1869 }
1870
1871
1872 /** Implementation of ex::to_rational() for powers. It replaces non-integer
1873  *  powers by temporary symbols.
1874  *  @see ex::to_rational */
1875 ex power::to_rational(lst &repl_lst) const
1876 {
1877         if (exponent.info(info_flags::integer))
1878                 return power(basis.to_rational(repl_lst), exponent);
1879         else
1880                 return replace_with_symbol(*this, repl_lst);
1881 }
1882
1883
1884 /** Rationalization of non-rational functions.
1885  *  This function converts a general expression to a rational polynomial
1886  *  by replacing all non-rational subexpressions (like non-rational numbers,
1887  *  non-integer powers or functions like sin(), cos() etc.) to temporary
1888  *  symbols. This makes it possible to use functions like gcd() and divide()
1889  *  on non-rational functions by applying to_rational() on the arguments,
1890  *  calling the desired function and re-substituting the temporary symbols
1891  *  in the result. To make the last step possible, all temporary symbols and
1892  *  their associated expressions are collected in the list specified by the
1893  *  repl_lst parameter in the form {symbol == expression}, ready to be passed
1894  *  as an argument to ex::subs().
1895  *
1896  *  @param repl_lst collects a list of all temporary symbols and their replacements
1897  *  @return rationalized expression */
1898 ex ex::to_rational(lst &repl_lst) const
1899 {
1900         return bp->to_rational(repl_lst);
1901 }
1902
1903
1904 #ifndef NO_NAMESPACE_GINAC
1905 } // namespace GiNaC
1906 #endif // ndef NO_NAMESPACE_GINAC