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