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