Speed up pow(+(...),n).expand() where n>2.
[ginac.git] / ginac / power.cpp
1 /** @file power.cpp
2  *
3  *  Implementation of GiNaC's symbolic exponentiation (basis^exponent). */
4
5 /*
6  *  GiNaC Copyright (C) 1999-2015 Johannes Gutenberg University Mainz, Germany
7  *
8  *  This program is free software; you can redistribute it and/or modify
9  *  it under the terms of the GNU General Public License as published by
10  *  the Free Software Foundation; either version 2 of the License, or
11  *  (at your option) any later version.
12  *
13  *  This program is distributed in the hope that it will be useful,
14  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
15  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  *  GNU General Public License for more details.
17  *
18  *  You should have received a copy of the GNU General Public License
19  *  along with this program; if not, write to the Free Software
20  *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
21  */
22
23 #include "power.h"
24 #include "expairseq.h"
25 #include "add.h"
26 #include "mul.h"
27 #include "ncmul.h"
28 #include "numeric.h"
29 #include "constant.h"
30 #include "operators.h"
31 #include "inifcns.h" // for log() in power::derivative()
32 #include "matrix.h"
33 #include "indexed.h"
34 #include "symbol.h"
35 #include "lst.h"
36 #include "archive.h"
37 #include "utils.h"
38 #include "relational.h"
39 #include "compiler.h"
40
41 #include <iostream>
42 #include <limits>
43 #include <stdexcept>
44 #include <vector>
45
46 namespace GiNaC {
47
48 GINAC_IMPLEMENT_REGISTERED_CLASS_OPT(power, basic,
49   print_func<print_dflt>(&power::do_print_dflt).
50   print_func<print_latex>(&power::do_print_latex).
51   print_func<print_csrc>(&power::do_print_csrc).
52   print_func<print_python>(&power::do_print_python).
53   print_func<print_python_repr>(&power::do_print_python_repr).
54   print_func<print_csrc_cl_N>(&power::do_print_csrc_cl_N))
55
56 //////////
57 // default constructor
58 //////////
59
60 power::power() { }
61
62 //////////
63 // other constructors
64 //////////
65
66 // all inlined
67
68 //////////
69 // archiving
70 //////////
71
72 void power::read_archive(const archive_node &n, lst &sym_lst)
73 {
74         inherited::read_archive(n, sym_lst);
75         n.find_ex("basis", basis, sym_lst);
76         n.find_ex("exponent", exponent, sym_lst);
77 }
78
79 void power::archive(archive_node &n) const
80 {
81         inherited::archive(n);
82         n.add_ex("basis", basis);
83         n.add_ex("exponent", exponent);
84 }
85
86 //////////
87 // functions overriding virtual functions from base classes
88 //////////
89
90 // public
91
92 void power::print_power(const print_context & c, const char *powersymbol, const char *openbrace, const char *closebrace, unsigned level) const
93 {
94         // Ordinary output of powers using '^' or '**'
95         if (precedence() <= level)
96                 c.s << openbrace << '(';
97         basis.print(c, precedence());
98         c.s << powersymbol;
99         c.s << openbrace;
100         exponent.print(c, precedence());
101         c.s << closebrace;
102         if (precedence() <= level)
103                 c.s << ')' << closebrace;
104 }
105
106 void power::do_print_dflt(const print_dflt & c, unsigned level) const
107 {
108         if (exponent.is_equal(_ex1_2)) {
109
110                 // Square roots are printed in a special way
111                 c.s << "sqrt(";
112                 basis.print(c);
113                 c.s << ')';
114
115         } else
116                 print_power(c, "^", "", "", level);
117 }
118
119 void power::do_print_latex(const print_latex & c, unsigned level) const
120 {
121         if (is_exactly_a<numeric>(exponent) && ex_to<numeric>(exponent).is_negative()) {
122
123                 // Powers with negative numeric exponents are printed as fractions
124                 c.s << "\\frac{1}{";
125                 power(basis, -exponent).eval().print(c);
126                 c.s << '}';
127
128         } else if (exponent.is_equal(_ex1_2)) {
129
130                 // Square roots are printed in a special way
131                 c.s << "\\sqrt{";
132                 basis.print(c);
133                 c.s << '}';
134
135         } else
136                 print_power(c, "^", "{", "}", level);
137 }
138
139 static void print_sym_pow(const print_context & c, const symbol &x, int exp)
140 {
141         // Optimal output of integer powers of symbols to aid compiler CSE.
142         // C.f. ISO/IEC 14882:1998, section 1.9 [intro execution], paragraph 15
143         // to learn why such a parenthesation is really necessary.
144         if (exp == 1) {
145                 x.print(c);
146         } else if (exp == 2) {
147                 x.print(c);
148                 c.s << "*";
149                 x.print(c);
150         } else if (exp & 1) {
151                 x.print(c);
152                 c.s << "*";
153                 print_sym_pow(c, x, exp-1);
154         } else {
155                 c.s << "(";
156                 print_sym_pow(c, x, exp >> 1);
157                 c.s << ")*(";
158                 print_sym_pow(c, x, exp >> 1);
159                 c.s << ")";
160         }
161 }
162
163 void power::do_print_csrc_cl_N(const print_csrc_cl_N& c, unsigned level) const
164 {
165         if (exponent.is_equal(_ex_1)) {
166                 c.s << "recip(";
167                 basis.print(c);
168                 c.s << ')';
169                 return;
170         }
171         c.s << "expt(";
172         basis.print(c);
173         c.s << ", ";
174         exponent.print(c);
175         c.s << ')';
176 }
177
178 void power::do_print_csrc(const print_csrc & c, unsigned level) const
179 {
180         // Integer powers of symbols are printed in a special, optimized way
181         if (exponent.info(info_flags::integer)
182          && (is_a<symbol>(basis) || is_a<constant>(basis))) {
183                 int exp = ex_to<numeric>(exponent).to_int();
184                 if (exp > 0)
185                         c.s << '(';
186                 else {
187                         exp = -exp;
188                         c.s << "1.0/(";
189                 }
190                 print_sym_pow(c, ex_to<symbol>(basis), exp);
191                 c.s << ')';
192
193         // <expr>^-1 is printed as "1.0/<expr>" or with the recip() function of CLN
194         } else if (exponent.is_equal(_ex_1)) {
195                 c.s << "1.0/(";
196                 basis.print(c);
197                 c.s << ')';
198
199         // Otherwise, use the pow() function
200         } else {
201                 c.s << "pow(";
202                 basis.print(c);
203                 c.s << ',';
204                 exponent.print(c);
205                 c.s << ')';
206         }
207 }
208
209 void power::do_print_python(const print_python & c, unsigned level) const
210 {
211         print_power(c, "**", "", "", level);
212 }
213
214 void power::do_print_python_repr(const print_python_repr & c, unsigned level) const
215 {
216         c.s << class_name() << '(';
217         basis.print(c);
218         c.s << ',';
219         exponent.print(c);
220         c.s << ')';
221 }
222
223 bool power::info(unsigned inf) const
224 {
225         switch (inf) {
226                 case info_flags::polynomial:
227                 case info_flags::integer_polynomial:
228                 case info_flags::cinteger_polynomial:
229                 case info_flags::rational_polynomial:
230                 case info_flags::crational_polynomial:
231                         return exponent.info(info_flags::nonnegint) &&
232                                basis.info(inf);
233                 case info_flags::rational_function:
234                         return exponent.info(info_flags::integer) &&
235                                basis.info(inf);
236                 case info_flags::algebraic:
237                         return !exponent.info(info_flags::integer) ||
238                                basis.info(inf);
239                 case info_flags::expanded:
240                         return (flags & status_flags::expanded);
241                 case info_flags::positive:
242                         return basis.info(info_flags::positive) && exponent.info(info_flags::real);
243                 case info_flags::nonnegative:
244                         return (basis.info(info_flags::positive) && exponent.info(info_flags::real)) ||
245                                (basis.info(info_flags::real) && exponent.info(info_flags::integer) && exponent.info(info_flags::even));
246                 case info_flags::has_indices: {
247                         if (flags & status_flags::has_indices)
248                                 return true;
249                         else if (flags & status_flags::has_no_indices)
250                                 return false;
251                         else if (basis.info(info_flags::has_indices)) {
252                                 setflag(status_flags::has_indices);
253                                 clearflag(status_flags::has_no_indices);
254                                 return true;
255                         } else {
256                                 clearflag(status_flags::has_indices);
257                                 setflag(status_flags::has_no_indices);
258                                 return false;
259                         }
260                 }
261         }
262         return inherited::info(inf);
263 }
264
265 size_t power::nops() const
266 {
267         return 2;
268 }
269
270 ex power::op(size_t i) const
271 {
272         GINAC_ASSERT(i<2);
273
274         return i==0 ? basis : exponent;
275 }
276
277 ex power::map(map_function & f) const
278 {
279         const ex &mapped_basis = f(basis);
280         const ex &mapped_exponent = f(exponent);
281
282         if (!are_ex_trivially_equal(basis, mapped_basis)
283          || !are_ex_trivially_equal(exponent, mapped_exponent))
284                 return (new power(mapped_basis, mapped_exponent))->setflag(status_flags::dynallocated);
285         else
286                 return *this;
287 }
288
289 bool power::is_polynomial(const ex & var) const
290 {
291         if (basis.is_polynomial(var)) {
292                 if (basis.has(var))
293                         // basis is non-constant polynomial in var
294                         return exponent.info(info_flags::nonnegint);
295                 else
296                         // basis is constant in var
297                         return !exponent.has(var);
298         }
299         // basis is a non-polynomial function of var
300         return false;
301 }
302
303 int power::degree(const ex & s) const
304 {
305         if (is_equal(ex_to<basic>(s)))
306                 return 1;
307         else if (is_exactly_a<numeric>(exponent) && ex_to<numeric>(exponent).is_integer()) {
308                 if (basis.is_equal(s))
309                         return ex_to<numeric>(exponent).to_int();
310                 else
311                         return basis.degree(s) * ex_to<numeric>(exponent).to_int();
312         } else if (basis.has(s))
313                 throw(std::runtime_error("power::degree(): undefined degree because of non-integer exponent"));
314         else
315                 return 0;
316 }
317
318 int power::ldegree(const ex & s) const 
319 {
320         if (is_equal(ex_to<basic>(s)))
321                 return 1;
322         else if (is_exactly_a<numeric>(exponent) && ex_to<numeric>(exponent).is_integer()) {
323                 if (basis.is_equal(s))
324                         return ex_to<numeric>(exponent).to_int();
325                 else
326                         return basis.ldegree(s) * ex_to<numeric>(exponent).to_int();
327         } else if (basis.has(s))
328                 throw(std::runtime_error("power::ldegree(): undefined degree because of non-integer exponent"));
329         else
330                 return 0;
331 }
332
333 ex power::coeff(const ex & s, int n) const
334 {
335         if (is_equal(ex_to<basic>(s)))
336                 return n==1 ? _ex1 : _ex0;
337         else if (!basis.is_equal(s)) {
338                 // basis not equal to s
339                 if (n == 0)
340                         return *this;
341                 else
342                         return _ex0;
343         } else {
344                 // basis equal to s
345                 if (is_exactly_a<numeric>(exponent) && ex_to<numeric>(exponent).is_integer()) {
346                         // integer exponent
347                         int int_exp = ex_to<numeric>(exponent).to_int();
348                         if (n == int_exp)
349                                 return _ex1;
350                         else
351                                 return _ex0;
352                 } else {
353                         // non-integer exponents are treated as zero
354                         if (n == 0)
355                                 return *this;
356                         else
357                                 return _ex0;
358                 }
359         }
360 }
361
362 /** Perform automatic term rewriting rules in this class.  In the following
363  *  x, x1, x2,... stand for a symbolic variables of type ex and c, c1, c2...
364  *  stand for such expressions that contain a plain number.
365  *  - ^(x,0) -> 1  (also handles ^(0,0))
366  *  - ^(x,1) -> x
367  *  - ^(0,c) -> 0 or exception  (depending on the real part of c)
368  *  - ^(1,x) -> 1
369  *  - ^(c1,c2) -> *(c1^n,c1^(c2-n))  (so that 0<(c2-n)<1, try to evaluate roots, possibly in numerator and denominator of c1)
370  *  - ^(^(x,c1),c2) -> ^(x,c1*c2)  if x is positive and c1 is real.
371  *  - ^(^(x,c1),c2) -> ^(x,c1*c2)  (c2 integer or -1 < c1 <= 1 or (c1=-1 and c2>0), case c1=1 should not happen, see below!)
372  *  - ^(*(x,y,z),c) -> *(x^c,y^c,z^c)  (if c integer)
373  *  - ^(*(x,c1),c2) -> ^(x,c2)*c1^c2  (c1>0)
374  *  - ^(*(x,c1),c2) -> ^(-x,c2)*c1^c2  (c1<0)
375  *
376  *  @param level cut-off in recursive evaluation */
377 ex power::eval(int level) const
378 {
379         if ((level==1) && (flags & status_flags::evaluated))
380                 return *this;
381         else if (level == -max_recursion_level)
382                 throw(std::runtime_error("max recursion level reached"));
383         
384         const ex & ebasis    = level==1 ? basis    : basis.eval(level-1);
385         const ex & eexponent = level==1 ? exponent : exponent.eval(level-1);
386         
387         const numeric *num_basis = NULL;
388         const numeric *num_exponent = NULL;
389         
390         if (is_exactly_a<numeric>(ebasis)) {
391                 num_basis = &ex_to<numeric>(ebasis);
392         }
393         if (is_exactly_a<numeric>(eexponent)) {
394                 num_exponent = &ex_to<numeric>(eexponent);
395         }
396         
397         // ^(x,0) -> 1  (0^0 also handled here)
398         if (eexponent.is_zero()) {
399                 if (ebasis.is_zero())
400                         throw (std::domain_error("power::eval(): pow(0,0) is undefined"));
401                 else
402                         return _ex1;
403         }
404         
405         // ^(x,1) -> x
406         if (eexponent.is_equal(_ex1))
407                 return ebasis;
408
409         // ^(0,c1) -> 0 or exception  (depending on real value of c1)
410         if ( ebasis.is_zero() && num_exponent ) {
411                 if ((num_exponent->real()).is_zero())
412                         throw (std::domain_error("power::eval(): pow(0,I) is undefined"));
413                 else if ((num_exponent->real()).is_negative())
414                         throw (pole_error("power::eval(): division by zero",1));
415                 else
416                         return _ex0;
417         }
418
419         // ^(1,x) -> 1
420         if (ebasis.is_equal(_ex1))
421                 return _ex1;
422
423         // power of a function calculated by separate rules defined for this function
424         if (is_exactly_a<function>(ebasis))
425                 return ex_to<function>(ebasis).power(eexponent);
426
427         // Turn (x^c)^d into x^(c*d) in the case that x is positive and c is real.
428         if (is_exactly_a<power>(ebasis) && ebasis.op(0).info(info_flags::positive) && ebasis.op(1).info(info_flags::real))
429                 return power(ebasis.op(0), ebasis.op(1) * eexponent);
430
431         if ( num_exponent ) {
432
433                 // ^(c1,c2) -> c1^c2  (c1, c2 numeric(),
434                 // except if c1,c2 are rational, but c1^c2 is not)
435                 if ( num_basis ) {
436                         const bool basis_is_crational = num_basis->is_crational();
437                         const bool exponent_is_crational = num_exponent->is_crational();
438                         if (!basis_is_crational || !exponent_is_crational) {
439                                 // return a plain float
440                                 return (new numeric(num_basis->power(*num_exponent)))->setflag(status_flags::dynallocated |
441                                                                                                status_flags::evaluated |
442                                                                                                status_flags::expanded);
443                         }
444
445                         const numeric res = num_basis->power(*num_exponent);
446                         if (res.is_crational()) {
447                                 return res;
448                         }
449                         GINAC_ASSERT(!num_exponent->is_integer());  // has been handled by now
450
451                         // ^(c1,n/m) -> *(c1^q,c1^(n/m-q)), 0<(n/m-q)<1, q integer
452                         if (basis_is_crational && exponent_is_crational
453                             && num_exponent->is_real()
454                             && !num_exponent->is_integer()) {
455                                 const numeric n = num_exponent->numer();
456                                 const numeric m = num_exponent->denom();
457                                 numeric r;
458                                 numeric q = iquo(n, m, r);
459                                 if (r.is_negative()) {
460                                         r += m;
461                                         --q;
462                                 }
463                                 if (q.is_zero()) {  // the exponent was in the allowed range 0<(n/m)<1
464                                         if (num_basis->is_rational() && !num_basis->is_integer()) {
465                                                 // try it for numerator and denominator separately, in order to
466                                                 // partially simplify things like (5/8)^(1/3) -> 1/2*5^(1/3)
467                                                 const numeric bnum = num_basis->numer();
468                                                 const numeric bden = num_basis->denom();
469                                                 const numeric res_bnum = bnum.power(*num_exponent);
470                                                 const numeric res_bden = bden.power(*num_exponent);
471                                                 if (res_bnum.is_integer())
472                                                         return (new mul(power(bden,-*num_exponent),res_bnum))->setflag(status_flags::dynallocated | status_flags::evaluated);
473                                                 if (res_bden.is_integer())
474                                                         return (new mul(power(bnum,*num_exponent),res_bden.inverse()))->setflag(status_flags::dynallocated | status_flags::evaluated);
475                                         }
476                                         return this->hold();
477                                 } else {
478                                         // assemble resulting product, but allowing for a re-evaluation,
479                                         // because otherwise we'll end up with something like
480                                         //    (7/8)^(4/3)  ->  7/8*(1/2*7^(1/3))
481                                         // instead of 7/16*7^(1/3).
482                                         ex prod = power(*num_basis,r.div(m));
483                                         return prod*power(*num_basis,q);
484                                 }
485                         }
486                 }
487         
488                 // ^(^(x,c1),c2) -> ^(x,c1*c2)
489                 // (c1, c2 numeric(), c2 integer or -1 < c1 <= 1 or (c1=-1 and c2>0),
490                 // case c1==1 should not happen, see below!)
491                 if (is_exactly_a<power>(ebasis)) {
492                         const power & sub_power = ex_to<power>(ebasis);
493                         const ex & sub_basis = sub_power.basis;
494                         const ex & sub_exponent = sub_power.exponent;
495                         if (is_exactly_a<numeric>(sub_exponent)) {
496                                 const numeric & num_sub_exponent = ex_to<numeric>(sub_exponent);
497                                 GINAC_ASSERT(num_sub_exponent!=numeric(1));
498                                 if (num_exponent->is_integer() || (abs(num_sub_exponent) - (*_num1_p)).is_negative() 
499                                                 || (num_sub_exponent == *_num_1_p && num_exponent->is_positive())) {
500                                         return power(sub_basis,num_sub_exponent.mul(*num_exponent));
501                                 }
502                         }
503                 }
504         
505                 // ^(*(x,y,z),c1) -> *(x^c1,y^c1,z^c1) (c1 integer)
506                 if (num_exponent->is_integer() && is_exactly_a<mul>(ebasis)) {
507                         return expand_mul(ex_to<mul>(ebasis), *num_exponent, 0);
508                 }
509
510                 // (2*x + 6*y)^(-4) -> 1/16*(x + 3*y)^(-4)
511                 if (num_exponent->is_integer() && is_exactly_a<add>(ebasis)) {
512                         numeric icont = ebasis.integer_content();
513                         const numeric lead_coeff = 
514                                 ex_to<numeric>(ex_to<add>(ebasis).seq.begin()->coeff).div(icont);
515
516                         const bool canonicalizable = lead_coeff.is_integer();
517                         const bool unit_normal = lead_coeff.is_pos_integer();
518                         if (canonicalizable && (! unit_normal))
519                                 icont = icont.mul(*_num_1_p);
520                         
521                         if (canonicalizable && (icont != *_num1_p)) {
522                                 const add& addref = ex_to<add>(ebasis);
523                                 add* addp = new add(addref);
524                                 addp->setflag(status_flags::dynallocated);
525                                 addp->clearflag(status_flags::hash_calculated);
526                                 addp->overall_coeff = ex_to<numeric>(addp->overall_coeff).div_dyn(icont);
527                                 for (epvector::iterator i = addp->seq.begin(); i != addp->seq.end(); ++i)
528                                         i->coeff = ex_to<numeric>(i->coeff).div_dyn(icont);
529
530                                 const numeric c = icont.power(*num_exponent);
531                                 if (likely(c != *_num1_p))
532                                         return (new mul(power(*addp, *num_exponent), c))->setflag(status_flags::dynallocated);
533                                 else
534                                         return power(*addp, *num_exponent);
535                         }
536                 }
537
538                 // ^(*(...,x;c1),c2) -> *(^(*(...,x;1),c2),c1^c2)  (c1, c2 numeric(), c1>0)
539                 // ^(*(...,x;c1),c2) -> *(^(*(...,x;-1),c2),(-c1)^c2)  (c1, c2 numeric(), c1<0)
540                 if (is_exactly_a<mul>(ebasis)) {
541                         GINAC_ASSERT(!num_exponent->is_integer()); // should have been handled above
542                         const mul & mulref = ex_to<mul>(ebasis);
543                         if (!mulref.overall_coeff.is_equal(_ex1)) {
544                                 const numeric & num_coeff = ex_to<numeric>(mulref.overall_coeff);
545                                 if (num_coeff.is_real()) {
546                                         if (num_coeff.is_positive()) {
547                                                 mul *mulp = new mul(mulref);
548                                                 mulp->overall_coeff = _ex1;
549                                                 mulp->setflag(status_flags::dynallocated);
550                                                 mulp->clearflag(status_flags::evaluated);
551                                                 mulp->clearflag(status_flags::hash_calculated);
552                                                 return (new mul(power(*mulp,exponent),
553                                                                 power(num_coeff,*num_exponent)))->setflag(status_flags::dynallocated);
554                                         } else {
555                                                 GINAC_ASSERT(num_coeff.compare(*_num0_p)<0);
556                                                 if (!num_coeff.is_equal(*_num_1_p)) {
557                                                         mul *mulp = new mul(mulref);
558                                                         mulp->overall_coeff = _ex_1;
559                                                         mulp->setflag(status_flags::dynallocated);
560                                                         mulp->clearflag(status_flags::evaluated);
561                                                         mulp->clearflag(status_flags::hash_calculated);
562                                                         return (new mul(power(*mulp,exponent),
563                                                                         power(abs(num_coeff),*num_exponent)))->setflag(status_flags::dynallocated);
564                                                 }
565                                         }
566                                 }
567                         }
568                 }
569
570                 // ^(nc,c1) -> ncmul(nc,nc,...) (c1 positive integer, unless nc is a matrix)
571                 if (num_exponent->is_pos_integer() &&
572                     ebasis.return_type() != return_types::commutative &&
573                     !is_a<matrix>(ebasis)) {
574                         return ncmul(exvector(num_exponent->to_int(), ebasis), true);
575                 }
576         }
577         
578         if (are_ex_trivially_equal(ebasis,basis) &&
579             are_ex_trivially_equal(eexponent,exponent)) {
580                 return this->hold();
581         }
582         return (new power(ebasis, eexponent))->setflag(status_flags::dynallocated |
583                                                        status_flags::evaluated);
584 }
585
586 ex power::evalf(int level) const
587 {
588         ex ebasis;
589         ex eexponent;
590         
591         if (level==1) {
592                 ebasis = basis;
593                 eexponent = exponent;
594         } else if (level == -max_recursion_level) {
595                 throw(std::runtime_error("max recursion level reached"));
596         } else {
597                 ebasis = basis.evalf(level-1);
598                 if (!is_exactly_a<numeric>(exponent))
599                         eexponent = exponent.evalf(level-1);
600                 else
601                         eexponent = exponent;
602         }
603
604         return power(ebasis,eexponent);
605 }
606
607 ex power::evalm() const
608 {
609         const ex ebasis = basis.evalm();
610         const ex eexponent = exponent.evalm();
611         if (is_a<matrix>(ebasis)) {
612                 if (is_exactly_a<numeric>(eexponent)) {
613                         return (new matrix(ex_to<matrix>(ebasis).pow(eexponent)))->setflag(status_flags::dynallocated);
614                 }
615         }
616         return (new power(ebasis, eexponent))->setflag(status_flags::dynallocated);
617 }
618
619 bool power::has(const ex & other, unsigned options) const
620 {
621         if (!(options & has_options::algebraic))
622                 return basic::has(other, options);
623         if (!is_a<power>(other))
624                 return basic::has(other, options);
625         if (!exponent.info(info_flags::integer)
626                         || !other.op(1).info(info_flags::integer))
627                 return basic::has(other, options);
628         if (exponent.info(info_flags::posint)
629                         && other.op(1).info(info_flags::posint)
630                         && ex_to<numeric>(exponent).to_int()
631                                         > ex_to<numeric>(other.op(1)).to_int()
632                         && basis.match(other.op(0)))
633                 return true;
634         if (exponent.info(info_flags::negint)
635                         && other.op(1).info(info_flags::negint)
636                         && ex_to<numeric>(exponent).to_int()
637                                         < ex_to<numeric>(other.op(1)).to_int()
638                         && basis.match(other.op(0)))
639                 return true;
640         return basic::has(other, options);
641 }
642
643 // from mul.cpp
644 extern bool tryfactsubs(const ex &, const ex &, int &, exmap&);
645
646 ex power::subs(const exmap & m, unsigned options) const
647 {       
648         const ex &subsed_basis = basis.subs(m, options);
649         const ex &subsed_exponent = exponent.subs(m, options);
650
651         if (!are_ex_trivially_equal(basis, subsed_basis)
652          || !are_ex_trivially_equal(exponent, subsed_exponent)) 
653                 return power(subsed_basis, subsed_exponent).subs_one_level(m, options);
654
655         if (!(options & subs_options::algebraic))
656                 return subs_one_level(m, options);
657
658         for (exmap::const_iterator it = m.begin(); it != m.end(); ++it) {
659                 int nummatches = std::numeric_limits<int>::max();
660                 exmap repls;
661                 if (tryfactsubs(*this, it->first, nummatches, repls)) {
662                         ex anum = it->second.subs(repls, subs_options::no_pattern);
663                         ex aden = it->first.subs(repls, subs_options::no_pattern);
664                         ex result = (*this)*power(anum/aden, nummatches);
665                         return (ex_to<basic>(result)).subs_one_level(m, options);
666                 }
667         }
668
669         return subs_one_level(m, options);
670 }
671
672 ex power::eval_ncmul(const exvector & v) const
673 {
674         return inherited::eval_ncmul(v);
675 }
676
677 ex power::conjugate() const
678 {
679         // conjugate(pow(x,y))==pow(conjugate(x),conjugate(y)) unless on the
680         // branch cut which runs along the negative real axis.
681         if (basis.info(info_flags::positive)) {
682                 ex newexponent = exponent.conjugate();
683                 if (are_ex_trivially_equal(exponent, newexponent)) {
684                         return *this;
685                 }
686                 return (new power(basis, newexponent))->setflag(status_flags::dynallocated);
687         }
688         if (exponent.info(info_flags::integer)) {
689                 ex newbasis = basis.conjugate();
690                 if (are_ex_trivially_equal(basis, newbasis)) {
691                         return *this;
692                 }
693                 return (new power(newbasis, exponent))->setflag(status_flags::dynallocated);
694         }
695         return conjugate_function(*this).hold();
696 }
697
698 ex power::real_part() const
699 {
700         if (exponent.info(info_flags::integer)) {
701                 ex basis_real = basis.real_part();
702                 if (basis_real == basis)
703                         return *this;
704                 realsymbol a("a"),b("b");
705                 ex result;
706                 if (exponent.info(info_flags::posint))
707                         result = power(a+I*b,exponent);
708                 else
709                         result = power(a/(a*a+b*b)-I*b/(a*a+b*b),-exponent);
710                 result = result.expand();
711                 result = result.real_part();
712                 result = result.subs(lst( a==basis_real, b==basis.imag_part() ));
713                 return result;
714         }
715         
716         ex a = basis.real_part();
717         ex b = basis.imag_part();
718         ex c = exponent.real_part();
719         ex d = exponent.imag_part();
720         return power(abs(basis),c)*exp(-d*atan2(b,a))*cos(c*atan2(b,a)+d*log(abs(basis)));
721 }
722
723 ex power::imag_part() const
724 {
725         if (exponent.info(info_flags::integer)) {
726                 ex basis_real = basis.real_part();
727                 if (basis_real == basis)
728                         return 0;
729                 realsymbol a("a"),b("b");
730                 ex result;
731                 if (exponent.info(info_flags::posint))
732                         result = power(a+I*b,exponent);
733                 else
734                         result = power(a/(a*a+b*b)-I*b/(a*a+b*b),-exponent);
735                 result = result.expand();
736                 result = result.imag_part();
737                 result = result.subs(lst( a==basis_real, b==basis.imag_part() ));
738                 return result;
739         }
740         
741         ex a=basis.real_part();
742         ex b=basis.imag_part();
743         ex c=exponent.real_part();
744         ex d=exponent.imag_part();
745         return power(abs(basis),c)*exp(-d*atan2(b,a))*sin(c*atan2(b,a)+d*log(abs(basis)));
746 }
747
748 // protected
749
750 /** Implementation of ex::diff() for a power.
751  *  @see ex::diff */
752 ex power::derivative(const symbol & s) const
753 {
754         if (is_a<numeric>(exponent)) {
755                 // D(b^r) = r * b^(r-1) * D(b) (faster than the formula below)
756                 epvector newseq;
757                 newseq.reserve(2);
758                 newseq.push_back(expair(basis, exponent - _ex1));
759                 newseq.push_back(expair(basis.diff(s), _ex1));
760                 return mul(newseq, exponent);
761         } else {
762                 // D(b^e) = b^e * (D(e)*ln(b) + e*D(b)/b)
763                 return mul(*this,
764                            add(mul(exponent.diff(s), log(basis)),
765                            mul(mul(exponent, basis.diff(s)), power(basis, _ex_1))));
766         }
767 }
768
769 int power::compare_same_type(const basic & other) const
770 {
771         GINAC_ASSERT(is_exactly_a<power>(other));
772         const power &o = static_cast<const power &>(other);
773
774         int cmpval = basis.compare(o.basis);
775         if (cmpval)
776                 return cmpval;
777         else
778                 return exponent.compare(o.exponent);
779 }
780
781 unsigned power::return_type() const
782 {
783         return basis.return_type();
784 }
785
786 return_type_t power::return_type_tinfo() const
787 {
788         return basis.return_type_tinfo();
789 }
790
791 ex power::expand(unsigned options) const
792 {
793         if (is_a<symbol>(basis) && exponent.info(info_flags::integer)) {
794                 // A special case worth optimizing.
795                 setflag(status_flags::expanded);
796                 return *this;
797         }
798
799         // (x*p)^c -> x^c * p^c, if p>0
800         // makes sense before expanding the basis
801         if (is_exactly_a<mul>(basis) && !basis.info(info_flags::indefinite)) {
802                 const mul &m = ex_to<mul>(basis);
803                 exvector prodseq;
804                 epvector powseq;
805                 prodseq.reserve(m.seq.size() + 1);
806                 powseq.reserve(m.seq.size() + 1);
807                 epvector::const_iterator last = m.seq.end();
808                 epvector::const_iterator cit = m.seq.begin();
809                 bool possign = true;
810
811                 // search for positive/negative factors
812                 while (cit!=last) {
813                         ex e=m.recombine_pair_to_ex(*cit);
814                         if (e.info(info_flags::positive))
815                                 prodseq.push_back(pow(e, exponent).expand(options));
816                         else if (e.info(info_flags::negative)) {
817                                 prodseq.push_back(pow(-e, exponent).expand(options));
818                                 possign = !possign;
819                         } else
820                                 powseq.push_back(*cit);
821                         ++cit;
822                 }
823
824                 // take care on the numeric coefficient
825                 ex coeff=(possign? _ex1 : _ex_1);
826                 if (m.overall_coeff.info(info_flags::positive) && m.overall_coeff != _ex1)
827                         prodseq.push_back(power(m.overall_coeff, exponent));
828                 else if (m.overall_coeff.info(info_flags::negative) && m.overall_coeff != _ex_1)
829                         prodseq.push_back(power(-m.overall_coeff, exponent));
830                 else
831                         coeff *= m.overall_coeff;
832
833                 // If positive/negative factors are found, then extract them.
834                 // In either case we set a flag to avoid the second run on a part
835                 // which does not have positive/negative terms.
836                 if (prodseq.size() > 0) {
837                         ex newbasis = coeff*mul(powseq);
838                         ex_to<basic>(newbasis).setflag(status_flags::purely_indefinite);
839                         return ((new mul(prodseq))->setflag(status_flags::dynallocated)*(new power(newbasis, exponent))->setflag(status_flags::dynallocated).expand(options)).expand(options);
840                 } else
841                         ex_to<basic>(basis).setflag(status_flags::purely_indefinite);
842         }
843
844         const ex expanded_basis = basis.expand(options);
845         const ex expanded_exponent = exponent.expand(options);
846         
847         // x^(a+b) -> x^a * x^b
848         if (is_exactly_a<add>(expanded_exponent)) {
849                 const add &a = ex_to<add>(expanded_exponent);
850                 exvector distrseq;
851                 distrseq.reserve(a.seq.size() + 1);
852                 epvector::const_iterator last = a.seq.end();
853                 epvector::const_iterator cit = a.seq.begin();
854                 while (cit!=last) {
855                         distrseq.push_back(power(expanded_basis, a.recombine_pair_to_ex(*cit)));
856                         ++cit;
857                 }
858                 
859                 // Make sure that e.g. (x+y)^(2+a) expands the (x+y)^2 factor
860                 if (ex_to<numeric>(a.overall_coeff).is_integer()) {
861                         const numeric &num_exponent = ex_to<numeric>(a.overall_coeff);
862                         int int_exponent = num_exponent.to_int();
863                         if (int_exponent > 0 && is_exactly_a<add>(expanded_basis))
864                                 distrseq.push_back(expand_add(ex_to<add>(expanded_basis), int_exponent, options));
865                         else
866                                 distrseq.push_back(power(expanded_basis, a.overall_coeff));
867                 } else
868                         distrseq.push_back(power(expanded_basis, a.overall_coeff));
869                 
870                 // Make sure that e.g. (x+y)^(1+a) -> x*(x+y)^a + y*(x+y)^a
871                 ex r = (new mul(distrseq))->setflag(status_flags::dynallocated);
872                 return r.expand(options);
873         }
874         
875         if (!is_exactly_a<numeric>(expanded_exponent) ||
876                 !ex_to<numeric>(expanded_exponent).is_integer()) {
877                 if (are_ex_trivially_equal(basis,expanded_basis) && are_ex_trivially_equal(exponent,expanded_exponent)) {
878                         return this->hold();
879                 } else {
880                         return (new power(expanded_basis,expanded_exponent))->setflag(status_flags::dynallocated | (options == 0 ? status_flags::expanded : 0));
881                 }
882         }
883         
884         // integer numeric exponent
885         const numeric & num_exponent = ex_to<numeric>(expanded_exponent);
886         int int_exponent = num_exponent.to_int();
887         
888         // (x+y)^n, n>0
889         if (int_exponent > 0 && is_exactly_a<add>(expanded_basis))
890                 return expand_add(ex_to<add>(expanded_basis), int_exponent, options);
891         
892         // (x*y)^n -> x^n * y^n
893         if (is_exactly_a<mul>(expanded_basis))
894                 return expand_mul(ex_to<mul>(expanded_basis), num_exponent, options, true);
895         
896         // cannot expand further
897         if (are_ex_trivially_equal(basis,expanded_basis) && are_ex_trivially_equal(exponent,expanded_exponent))
898                 return this->hold();
899         else
900                 return (new power(expanded_basis,expanded_exponent))->setflag(status_flags::dynallocated | (options == 0 ? status_flags::expanded : 0));
901 }
902
903 //////////
904 // new virtual functions which can be overridden by derived classes
905 //////////
906
907 // none
908
909 //////////
910 // non-virtual functions in this class
911 //////////
912
913 namespace {  // anonymous namespace for power::expand_add() helpers
914
915 /** Helper class to generate all bounded combinatorial partitions of an integer
916  *  n with exactly m parts (including zero parts) in non-decreaing order.
917  */
918 class partition_generator {
919 private:
920         // Partitions n into m parts, not including zero parts.
921         // (Cf. OEIS sequence A008284; implementation adapted from Jörg Arndt's
922         // FXT library)
923         struct mpartition2
924         {
925                 // partition: x[1] + x[2] + ... + x[m] = n and sentinel x[0] == 0
926                 std::vector<int> x;
927                 int n;   // n>0
928                 int m;   // 0<m<=n
929                 mpartition2(unsigned n_, unsigned m_)
930                   : x(m_+1), n(n_), m(m_)
931                 {
932                         for (int k=1; k<m; ++k)
933                                 x[k] = 1;
934                         x[m] = n - m + 1;
935                 }
936                 bool next_partition()
937                 {
938                         int u = x[m];  // last element
939                         int k = m;
940                         int s = u;
941                         while (--k) {
942                                 s += x[k];
943                                 if (x[k] + 2 <= u)
944                                         break;
945                         }
946                         if (k==0)
947                                 return false;  // current is last
948                         int f = x[k] + 1;
949                         while (k < m) {
950                                 x[k] = f;
951                                 s -= f;
952                                 ++k;
953                         }
954                         x[m] = s;
955                         return true;
956                 }
957         } mpgen;
958         int m;  // number of parts 0<m<=n
959         mutable std::vector<int> partition;  // current partition
960 public:
961         partition_generator(unsigned n_, unsigned m_)
962           : mpgen(n_, 1), m(m_), partition(m_)
963         { }
964         // returns current partition in non-decreasing order, padded with zeros
965         const std::vector<int>& current() const
966         {
967                 for (int i = 0; i < m - mpgen.m; ++i)
968                         partition[i] = 0;  // pad with zeros
969
970                 for (int i = m - mpgen.m; i < m; ++i)
971                         partition[i] = mpgen.x[i - m + mpgen.m + 1];
972
973                 return partition;
974         }
975         bool next()
976         {
977                 if (!mpgen.next_partition()) {
978                         if (mpgen.m == m || mpgen.m == mpgen.n)
979                                 return false;  // current is last
980                         // increment number of parts
981                         mpgen = mpartition2(mpgen.n, mpgen.m + 1);
982                 }
983                 return true;
984         }
985 };
986
987 /** Helper class to generate all compositions of a partition of an integer n,
988  *  starting with the compositions which has non-decreasing order.
989  */
990 class composition_generator {
991 private:
992         // Generates all distinct permutations of a multiset.
993         // (Based on Aaron Williams' algorithm 1 from "Loopless Generation of
994         // Multiset Permutations using a Constant Number of Variables by Prefix
995         // Shifts." <http://webhome.csc.uvic.ca/~haron/CoolMulti.pdf>)
996         struct coolmulti {
997                 // element of singly linked list
998                 struct element {
999                         int value;
1000                         element* next;
1001                         element(int val, element* n)
1002                           : value(val), next(n) {}
1003                         ~element()
1004                         {   // recurses down to the end of the singly linked list
1005                                 delete next;
1006                         }
1007                 };
1008                 element *head, *i, *after_i;
1009                 // NB: Partition must be sorted in non-decreasing order.
1010                 explicit coolmulti(const std::vector<int>& partition)
1011                 {
1012                         head = NULL;
1013                         for (unsigned n = 0; n < partition.size(); ++n) {
1014                                 head = new element(partition[n], head);
1015                                 if (n <= 1)
1016                                         i = head;
1017                         }
1018                         after_i = i->next;
1019                 }
1020                 ~coolmulti()
1021                 {   // deletes singly linked list
1022                         delete head;
1023                 }
1024                 void next_permutation()
1025                 {
1026                         element *before_k;
1027                         if (after_i->next != NULL && i->value >= after_i->next->value)
1028                                 before_k = after_i;
1029                         else
1030                                 before_k = i;
1031                         element *k = before_k->next;
1032                         before_k->next = k->next;
1033                         k->next = head;
1034                         if (k->value < head->value)
1035                                 i = k;
1036                         after_i = i->next;
1037                         head = k;
1038                 }
1039                 bool finished() const
1040                 {
1041                         return after_i->next == NULL && after_i->value >= head->value;
1042                 }
1043         } cmgen;
1044         bool atend;  // needed for simplifying iteration over permutations
1045         bool trivial;  // likewise, true if all elements are equal
1046         mutable std::vector<int> composition;  // current compositions
1047 public:
1048         explicit composition_generator(const std::vector<int>& partition)
1049           : cmgen(partition), atend(false), trivial(true), composition(partition.size())
1050         {
1051                 for (unsigned i=1; i<partition.size(); ++i)
1052                         trivial = trivial && (partition[0] == partition[i]);
1053         }
1054         const std::vector<int>& current() const
1055         {
1056                 coolmulti::element* it = cmgen.head;
1057                 size_t i = 0;
1058                 while (it != NULL) {
1059                         composition[i] = it->value;
1060                         it = it->next;
1061                         ++i;
1062                 }
1063                 return composition;
1064         }
1065         bool next()
1066         {
1067                 // This ugly contortion is needed because the original coolmulti
1068                 // algorithm requires code duplication of the payload procedure,
1069                 // one before the loop and one inside it.
1070                 if (trivial || atend)
1071                         return false;
1072                 cmgen.next_permutation();
1073                 atend = cmgen.finished();
1074                 return true;
1075         }
1076 };
1077
1078 /** Helper function to compute the multinomial coefficient n!/(p1!*p2!*...*pk!)
1079  *  where n = p1+p2+...+pk, i.e. p is a partition of n.
1080  */
1081 const numeric
1082 multinomial_coefficient(const std::vector<int> p)
1083 {
1084         numeric n = 0, d = 1;
1085         std::vector<int>::const_iterator it = p.begin(), itend = p.end();
1086         while (it != itend) {
1087                 n += numeric(*it);
1088                 d *= factorial(numeric(*it));
1089                 ++it;
1090         }
1091         return factorial(numeric(n)) / d;
1092 }
1093
1094 }  // anonymous namespace
1095
1096 /** expand a^n where a is an add and n is a positive integer.
1097  *  @see power::expand */
1098 ex power::expand_add(const add & a, int n, unsigned options) const
1099 {
1100         // The special case power(+(x,...y;x),2) can be optimized better.
1101         if (n==2)
1102                 return expand_add_2(a, options);
1103
1104         // method:
1105         //
1106         // Consider base as the sum of all symbolic terms and the overall numeric
1107         // coefficient and apply the binomial theorem:
1108         // S = power(+(x,...,z;c),n)
1109         //   = power(+(+(x,...,z;0);c),n)
1110         //   = sum(binomial(n,k)*power(+(x,...,z;0),k)*c^(n-k), k=1..n) + c^n
1111         // Then, apply the multinomial theorem to expand all power(+(x,...,z;0),k):
1112         // The multinomial theorem is computed by an outer loop over all
1113         // partitions of the exponent and an inner loop over all compositions of
1114         // that partition. This method makes the expansion a combinatorial
1115         // problem and allows us to directly construct the expanded sum and also
1116         // to re-use the multinomial coefficients (since they depend only on the
1117         // partition, not on the composition).
1118         // 
1119         // multinomial power(+(x,y,z;0),3) example:
1120         // partition : compositions                : multinomial coefficient
1121         // [0,0,3]   : [3,0,0],[0,3,0],[0,0,3]     : 3!/(3!*0!*0!) = 1
1122         // [0,1,2]   : [2,1,0],[1,2,0],[2,0,1],... : 3!/(2!*1!*0!) = 3
1123         // [1,1,1]   : [1,1,1]                     : 3!/(1!*1!*1!) = 6
1124         //  =>  (x + y + z)^3 =
1125         //        x^3 + y^3 + z^3
1126         //      + 3*x^2*y + 3*x*y^2 + 3*y^2*z + 3*y*z^2 + 3*x*z^2 + 3*x^2*z
1127         //      + 6*x*y*z
1128         //
1129         // multinomial power(+(x,y,z;0),4) example:
1130         // partition : compositions                : multinomial coefficient
1131         // [0,0,4]   : [4,0,0],[0,4,0],[0,0,4]     : 4!/(4!*0!*0!) = 1
1132         // [0,1,3]   : [3,1,0],[1,3,0],[3,0,1],... : 4!/(3!*1!*0!) = 4
1133         // [0,2,2]   : [2,2,0],[2,0,2],[0,2,2]     : 4!/(2!*2!*0!) = 6
1134         // [1,1,2]   : [2,1,1],[1,2,1],[1,1,2]     : 4!/(2!*1!*1!) = 12
1135         // (no [1,1,1,1] partition since it has too many parts)
1136         //  =>  (x + y + z)^4 =
1137         //        x^4 + y^4 + z^4
1138         //      + 4*x^3*y + 4*x*y^3 + 4*y^3*z + 4*y*z^3 + 4*x*z^3 + 4*x^3*z
1139         //      + 6*x^2*y^2 + 6*y^2*z^2 + 6*x^2*z^2
1140         //      + 12*x^2*y*z + 12*x*y^2*z + 12*x*y*z^2
1141         //
1142         // Summary:
1143         // r = 0
1144         // for k from 0 to n:
1145         //     f = c^(n-k)*binomial(n,k)
1146         //     for p in all partitions of n with m parts (including zero parts):
1147         //         h = f * multinomial coefficient of p
1148         //         for c in all compositions of p:
1149         //             t = 1
1150         //             for e in all elements of c:
1151         //                 t = t * a[e]^e
1152         //             r = r + h*t
1153         // return r
1154
1155         epvector result;
1156         // The number of terms will be the number of combinatorial compositions,
1157         // i.e. the number of unordered arrangements of m nonnegative integers
1158         // which sum up to n.  It is frequently written as C_n(m) and directly
1159         // related with binomial coefficients: binomial(n+m-1,m-1).
1160         size_t result_size = binomial(numeric(n+a.nops()-1), numeric(a.nops()-1)).to_int();
1161         if (!a.overall_coeff.is_zero()) {
1162                 // the result's overall_coeff is one of the terms
1163                 --result_size;
1164         }
1165         result.reserve(result_size);
1166
1167         // Iterate over all terms in binomial expansion of
1168         // S = power(+(x,...,z;c),n)
1169         //   = sum(binomial(n,k)*power(+(x,...,z;0),k)*c^(n-k), k=1..n) + c^n
1170         for (int k = 1; k <= n; ++k) {
1171                 numeric binomial_coefficient;  // binomial(n,k)*c^(n-k)
1172                 if (a.overall_coeff.is_zero()) {
1173                         // degenerate case with zero overall_coeff:
1174                         // apply multinomial theorem directly to power(+(x,...z;0),n)
1175                         binomial_coefficient = 1;
1176                         if (k < n) {
1177                                 continue;
1178                         }
1179                 } else {
1180                         binomial_coefficient = binomial(numeric(n), numeric(k)) * pow(ex_to<numeric>(a.overall_coeff), numeric(n-k));
1181                 }
1182
1183                 // Multinomial expansion of power(+(x,...,z;0),k)*c^(n-k):
1184                 // Iterate over all partitions of k with exactly as many parts as
1185                 // there are symbolic terms in the basis (including zero parts).
1186                 partition_generator partitions(k, a.seq.size());
1187                 do {
1188                         const std::vector<int>& partition = partitions.current();
1189                         const numeric coeff = multinomial_coefficient(partition) * binomial_coefficient;
1190
1191                         // Iterate over all compositions of the current partition.
1192                         composition_generator compositions(partition);
1193                         do {
1194                                 const std::vector<int>& exponent = compositions.current();
1195                                 exvector term;
1196                                 term.reserve(n);
1197                                 numeric factor = coeff;
1198                                 for (unsigned i = 0; i < exponent.size(); ++i) {
1199                                         const ex & r = a.seq[i].rest;
1200                                         const ex & c = a.seq[i].coeff;
1201                                         GINAC_ASSERT(!is_exactly_a<add>(r));
1202                                         GINAC_ASSERT(!is_exactly_a<power>(r) ||
1203                                                      !is_exactly_a<numeric>(ex_to<power>(r).exponent) ||
1204                                                      !ex_to<numeric>(ex_to<power>(r).exponent).is_pos_integer() ||
1205                                                      !is_exactly_a<add>(ex_to<power>(r).basis) ||
1206                                                      !is_exactly_a<mul>(ex_to<power>(r).basis) ||
1207                                                      !is_exactly_a<power>(ex_to<power>(r).basis));
1208                                         if (exponent[i] == 0) {
1209                                                 // optimize away
1210                                         } else if (exponent[i] == 1) {
1211                                                 // optimized
1212                                                 term.push_back(r);
1213                                                 factor = factor.mul(ex_to<numeric>(c));
1214                                         } else { // general case exponent[i] > 1
1215                                                 term.push_back((new power(r, exponent[i]))->setflag(status_flags::dynallocated));
1216                                                 factor = factor.mul(ex_to<numeric>(c).power(exponent[i]));
1217                                         }
1218                                 }
1219                                 result.push_back(a.combine_ex_with_coeff_to_pair(mul(term).expand(options), factor));
1220                         } while (compositions.next());
1221                 } while (partitions.next());
1222         }
1223
1224         GINAC_ASSERT(result.size() == result_size);
1225
1226         if (a.overall_coeff.is_zero()) {
1227                 return (new add(result))->setflag(status_flags::dynallocated |
1228                                                   status_flags::expanded);
1229         } else {
1230                 return (new add(result, ex_to<numeric>(a.overall_coeff).power(n)))->setflag(status_flags::dynallocated |
1231                                                                                             status_flags::expanded);
1232         }
1233 }
1234
1235
1236 /** Special case of power::expand_add. Expands a^2 where a is an add.
1237  *  @see power::expand_add */
1238 ex power::expand_add_2(const add & a, unsigned options) const
1239 {
1240         epvector sum;
1241         size_t a_nops = a.nops();
1242         sum.reserve((a_nops*(a_nops+1))/2);
1243         epvector::const_iterator last = a.seq.end();
1244
1245         // power(+(x,...,z;c),2)=power(+(x,...,z;0),2)+2*c*+(x,...,z;0)+c*c
1246         // first part: ignore overall_coeff and expand other terms
1247         for (epvector::const_iterator cit0=a.seq.begin(); cit0!=last; ++cit0) {
1248                 const ex & r = cit0->rest;
1249                 const ex & c = cit0->coeff;
1250                 
1251                 GINAC_ASSERT(!is_exactly_a<add>(r));
1252                 GINAC_ASSERT(!is_exactly_a<power>(r) ||
1253                              !is_exactly_a<numeric>(ex_to<power>(r).exponent) ||
1254                              !ex_to<numeric>(ex_to<power>(r).exponent).is_pos_integer() ||
1255                              !is_exactly_a<add>(ex_to<power>(r).basis) ||
1256                              !is_exactly_a<mul>(ex_to<power>(r).basis) ||
1257                              !is_exactly_a<power>(ex_to<power>(r).basis));
1258                 
1259                 if (c.is_equal(_ex1)) {
1260                         if (is_exactly_a<mul>(r)) {
1261                                 sum.push_back(a.combine_ex_with_coeff_to_pair(expand_mul(ex_to<mul>(r), *_num2_p, options, true),
1262                                                                               _ex1));
1263                         } else {
1264                                 sum.push_back(a.combine_ex_with_coeff_to_pair((new power(r,_ex2))->setflag(status_flags::dynallocated),
1265                                                                               _ex1));
1266                         }
1267                 } else {
1268                         if (is_exactly_a<mul>(r)) {
1269                                 sum.push_back(a.combine_ex_with_coeff_to_pair(expand_mul(ex_to<mul>(r), *_num2_p, options, true),
1270                                                      ex_to<numeric>(c).power_dyn(*_num2_p)));
1271                         } else {
1272                                 sum.push_back(a.combine_ex_with_coeff_to_pair((new power(r,_ex2))->setflag(status_flags::dynallocated),
1273                                                      ex_to<numeric>(c).power_dyn(*_num2_p)));
1274                         }
1275                 }
1276
1277                 for (epvector::const_iterator cit1=cit0+1; cit1!=last; ++cit1) {
1278                         const ex & r1 = cit1->rest;
1279                         const ex & c1 = cit1->coeff;
1280                         sum.push_back(a.combine_ex_with_coeff_to_pair(mul(r,r1).expand(options),
1281                                                                       _num2_p->mul(ex_to<numeric>(c)).mul_dyn(ex_to<numeric>(c1))));
1282                 }
1283         }
1284         
1285         GINAC_ASSERT(sum.size()==(a.seq.size()*(a.seq.size()+1))/2);
1286         
1287         // second part: add terms coming from overall_coeff (if != 0)
1288         if (!a.overall_coeff.is_zero()) {
1289                 epvector::const_iterator i = a.seq.begin(), end = a.seq.end();
1290                 while (i != end) {
1291                         sum.push_back(a.combine_pair_with_coeff_to_pair(*i, ex_to<numeric>(a.overall_coeff).mul_dyn(*_num2_p)));
1292                         ++i;
1293                 }
1294                 sum.push_back(expair(ex_to<numeric>(a.overall_coeff).power_dyn(*_num2_p),_ex1));
1295         }
1296         
1297         GINAC_ASSERT(sum.size()==(a_nops*(a_nops+1))/2);
1298         
1299         return (new add(sum))->setflag(status_flags::dynallocated | status_flags::expanded);
1300 }
1301
1302 /** Expand factors of m in m^n where m is a mul and n is an integer.
1303  *  @see power::expand */
1304 ex power::expand_mul(const mul & m, const numeric & n, unsigned options, bool from_expand) const
1305 {
1306         GINAC_ASSERT(n.is_integer());
1307
1308         if (n.is_zero()) {
1309                 return _ex1;
1310         }
1311
1312         // do not bother to rename indices if there are no any.
1313         if ((!(options & expand_options::expand_rename_idx)) 
1314                         && m.info(info_flags::has_indices))
1315                 options |= expand_options::expand_rename_idx;
1316         // Leave it to multiplication since dummy indices have to be renamed
1317         if ((options & expand_options::expand_rename_idx) &&
1318                 (get_all_dummy_indices(m).size() > 0) && n.is_positive()) {
1319                 ex result = m;
1320                 exvector va = get_all_dummy_indices(m);
1321                 sort(va.begin(), va.end(), ex_is_less());
1322
1323                 for (int i=1; i < n.to_int(); i++)
1324                         result *= rename_dummy_indices_uniquely(va, m);
1325                 return result;
1326         }
1327
1328         epvector distrseq;
1329         distrseq.reserve(m.seq.size());
1330         bool need_reexpand = false;
1331
1332         epvector::const_iterator last = m.seq.end();
1333         epvector::const_iterator cit = m.seq.begin();
1334         while (cit!=last) {
1335                 expair p = m.combine_pair_with_coeff_to_pair(*cit, n);
1336                 if (from_expand && is_exactly_a<add>(cit->rest) && ex_to<numeric>(p.coeff).is_pos_integer()) {
1337                         // this happens when e.g. (a+b)^(1/2) gets squared and
1338                         // the resulting product needs to be reexpanded
1339                         need_reexpand = true;
1340                 }
1341                 distrseq.push_back(p);
1342                 ++cit;
1343         }
1344
1345         const mul & result = static_cast<const mul &>((new mul(distrseq, ex_to<numeric>(m.overall_coeff).power_dyn(n)))->setflag(status_flags::dynallocated));
1346         if (need_reexpand)
1347                 return ex(result).expand(options);
1348         if (from_expand)
1349                 return result.setflag(status_flags::expanded);
1350         return result;
1351 }
1352
1353 GINAC_BIND_UNARCHIVER(power);
1354
1355 } // namespace GiNaC