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