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