Code coverage tests

This page documents the degree to which the PARI/GP source code is tested by our public test suite, distributed with the source distribution in directory src/test/. This is measured by the gcov utility; we then process gcov output using the lcov frond-end.

We test a few variants depending on Configure flags on the pari.math.u-bordeaux.fr machine (x86_64 architecture), and agregate them in the final report:

The target is to exceed 90% coverage for all mathematical modules (given that branches depending on DEBUGLEVEL or DEBUGMEM are not covered). This script is run to produce the results below.

LCOV - code coverage report
Current view: top level - basemath - trans1.c (source / functions) Hit Total Coverage
Test: PARI/GP v2.16.1 lcov report (development 28904-c3aa21e911) Lines: 2242 2314 96.9 %
Date: 2023-12-04 07:51:13 Functions: 166 167 99.4 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /* Copyright (C) 2000  The PARI group.
       2             : 
       3             : This file is part of the PARI/GP package.
       4             : 
       5             : PARI/GP is free software; you can redistribute it and/or modify it under the
       6             : terms of the GNU General Public License as published by the Free Software
       7             : Foundation; either version 2 of the License, or (at your option) any later
       8             : version. It is distributed in the hope that it will be useful, but WITHOUT
       9             : ANY WARRANTY WHATSOEVER.
      10             : 
      11             : Check the License for details. You should have received a copy of it, along
      12             : with the package; see the file 'COPYING'. If not, write to the Free Software
      13             : Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */
      14             : 
      15             : /********************************************************************/
      16             : /**                                                                **/
      17             : /**                   TRANSCENDENTAL FUNCTIONS                     **/
      18             : /**                                                                **/
      19             : /********************************************************************/
      20             : #include "pari.h"
      21             : #include "paripriv.h"
      22             : 
      23             : #define DEBUGLEVEL DEBUGLEVEL_trans
      24             : 
      25             : #ifdef LONG_IS_64BIT
      26             : static const long SQRTVERYBIGINT = 3037000500L; /* ceil(sqrt(LONG_MAX)) */
      27             : #else
      28             : static const long SQRTVERYBIGINT = 46341L;
      29             : #endif
      30             : 
      31             : static THREAD GEN gcatalan, geuler, glog2, gpi;
      32             : void
      33      347814 : pari_init_floats(void)
      34             : {
      35      347814 :   gcatalan = geuler = gpi = zetazone = bernzone = glog2 = eulerzone = NULL;
      36      347814 : }
      37             : 
      38             : void
      39      345597 : pari_close_floats(void)
      40             : {
      41      345597 :   guncloneNULL(gcatalan);
      42      344597 :   guncloneNULL(geuler);
      43      343348 :   guncloneNULL(gpi);
      44      343171 :   guncloneNULL(glog2);
      45      343058 :   guncloneNULL(zetazone);
      46      342931 :   guncloneNULL_deep(bernzone);
      47      342918 :   guncloneNULL_deep(eulerzone);
      48      342808 : }
      49             : 
      50             : /********************************************************************/
      51             : /**                   GENERIC BINARY SPLITTING                     **/
      52             : /**                    (Haible, Papanikolaou)                      **/
      53             : /********************************************************************/
      54             : void
      55      274286 : abpq_init(struct abpq *A, long n)
      56             : {
      57      274286 :   A->a = (GEN*)new_chunk(n+1);
      58      274407 :   A->b = (GEN*)new_chunk(n+1);
      59      274508 :   A->p = (GEN*)new_chunk(n+1);
      60      274547 :   A->q = (GEN*)new_chunk(n+1);
      61      274572 : }
      62             : static GEN
      63    20155064 : mulii3(GEN a, GEN b, GEN c) { return mulii(mulii(a,b),c); }
      64             : 
      65             : /* T_{n1,n1+1} */
      66             : static GEN
      67     4301800 : T2(struct abpq *A, long n1)
      68             : {
      69     4301800 :   GEN u = mulii3(A->a[n1], A->b[n1+1], A->q[n1+1]);
      70     4301519 :   GEN v = mulii3(A->b[n1], A->a[n1+1], A->p[n1+1]);
      71     4301821 :   return mulii(A->p[n1], addii(u, v));
      72             : }
      73             : 
      74             : /* assume n2 > n1. Compute sum_{n1 <= n < n2} a/b(n) p/q(n1)... p/q(n) */
      75             : void
      76     8372004 : abpq_sum(struct abpq_res *r, long n1, long n2, struct abpq *A)
      77             : {
      78             :   struct abpq_res L, R;
      79             :   GEN u1, u2;
      80             :   pari_sp av;
      81             :   long n;
      82     8372004 :   switch(n2 - n1)
      83             :   {
      84             :     GEN b, q;
      85          58 :     case 1:
      86          58 :       r->P = A->p[n1];
      87          58 :       r->Q = A->q[n1];
      88          58 :       r->B = A->b[n1];
      89          58 :       r->T = mulii(A->a[n1], A->p[n1]);
      90     4313038 :       return;
      91     2424648 :     case 2:
      92     2424648 :       r->P = mulii(A->p[n1], A->p[n1+1]);
      93     2416113 :       r->Q = mulii(A->q[n1], A->q[n1+1]);
      94     2415494 :       r->B = mulii(A->b[n1], A->b[n1+1]);
      95     2415482 :       av = avma;
      96     2415482 :       r->T = gerepileuptoint(av, T2(A, n1));
      97     2419658 :       return;
      98             : 
      99     1903059 :     case 3:
     100     1903059 :       q = mulii(A->q[n1+1], A->q[n1+2]);
     101     1899907 :       b = mulii(A->b[n1+1], A->b[n1+2]);
     102     1899664 :       r->P = mulii3(A->p[n1], A->p[n1+1], A->p[n1+2]);
     103     1899451 :       r->Q = mulii(A->q[n1], q);
     104     1899543 :       r->B = mulii(A->b[n1], b);
     105     1899537 :       av = avma;
     106     1899537 :       u1 = mulii3(b, q, A->a[n1]);
     107     1899356 :       u2 = mulii(A->b[n1], T2(A, n1+1));
     108     1899556 :       r->T = gerepileuptoint(av, mulii(A->p[n1], addii(u1, u2)));
     109     1893322 :       return;
     110             :   }
     111             : 
     112     4044239 :   av = avma;
     113     4044239 :   n = (n1 + n2) >> 1;
     114     4044239 :   abpq_sum(&L, n1, n, A);
     115     4048378 :   abpq_sum(&R, n, n2, A);
     116             : 
     117     4049436 :   r->P = mulii(L.P, R.P);
     118     4035243 :   r->Q = mulii(L.Q, R.Q);
     119     4036687 :   r->B = mulii(L.B, R.B);
     120     4034906 :   u1 = mulii3(R.B, R.Q, L.T);
     121     4035201 :   u2 = mulii3(L.B, L.P, R.T);
     122     4033831 :   r->T = addii(u1,u2);
     123     4035835 :   set_avma(av);
     124     4036968 :   r->P = icopy(r->P);
     125     4048255 :   r->Q = icopy(r->Q);
     126     4051704 :   r->B = icopy(r->B);
     127     4051987 :   r->T = icopy(r->T);
     128             : }
     129             : 
     130             : /********************************************************************/
     131             : /**                                                                **/
     132             : /**                               PI                               **/
     133             : /**                                                                **/
     134             : /********************************************************************/
     135             : /* replace *old clone by c. Protect against SIGINT */
     136             : static void
     137       78099 : swap_clone(GEN *old, GEN c)
     138       78099 : { GEN tmp = *old; *old = c; guncloneNULL(tmp); }
     139             : 
     140             : /*                         ----
     141             :  *  53360 (640320)^(1/2)   \    (6n)! (545140134 n + 13591409)
     142             :  *  -------------------- = /    ------------------------------
     143             :  *        Pi               ----   (n!)^3 (3n)! (-640320)^(3n)
     144             :  *                         n>=0
     145             :  *
     146             :  * Ramanujan's formula + binary splitting */
     147             : static GEN
     148       38409 : pi_ramanujan(long prec)
     149             : {
     150       38409 :   const ulong B = 545140134, A = 13591409, C = 640320;
     151       38409 :   const double alpha2 = 47.11041314; /* 3log(C/12) / log(2) */
     152             :   long n, nmax, prec2;
     153             :   struct abpq_res R;
     154             :   struct abpq S;
     155             :   GEN D, u;
     156             : 
     157       38409 :   nmax = (long)(1 + prec2nbits(prec)/alpha2);
     158             : #ifdef LONG_IS_64BIT
     159       37899 :   D = utoipos(10939058860032000UL); /* C^3/24 */
     160             : #else
     161         510 :   D = uutoi(2546948UL,495419392UL);
     162             : #endif
     163       38408 :   abpq_init(&S, nmax);
     164       38417 :   S.a[0] = utoipos(A);
     165       38411 :   S.b[0] = S.p[0] = S.q[0] = gen_1;
     166      312774 :   for (n = 1; n <= nmax; n++)
     167             :   {
     168      274404 :     S.a[n] = addiu(muluu(B, n), A);
     169      274373 :     S.b[n] = gen_1;
     170      274373 :     S.p[n] = mulis(muluu(6*n-5, 2*n-1), 1-6*n);
     171      274308 :     S.q[n] = mulii(sqru(n), muliu(D,n));
     172             :   }
     173       38370 :   abpq_sum(&R, 0, nmax, &S); prec2 = prec+EXTRAPREC64;
     174       38417 :   u = itor(muliu(R.Q,C/12), prec2);
     175       38412 :   return rtor(mulrr(divri(u, R.T), sqrtr_abs(utor(C,prec2))), prec);
     176             : }
     177             : 
     178             : #if 0 /* Much slower than binary splitting at least up to prec = 10^8 */
     179             : /* Gauss - Brent-Salamin AGM iteration */
     180             : static GEN
     181             : pi_brent_salamin(long prec)
     182             : {
     183             :   GEN A, B, C;
     184             :   pari_sp av2;
     185             :   long i, G;
     186             : 
     187             :   G = - prec2nbits(prec);
     188             :   incrprec(prec);
     189             : 
     190             :   A = real2n(-1, prec);
     191             :   B = sqrtr_abs(A); /* = 1/sqrt(2) */
     192             :   setexpo(A, 0);
     193             :   C = real2n(-2, prec); av2 = avma;
     194             :   for (i = 0;; i++)
     195             :   {
     196             :     GEN y, a, b, B_A = subrr(B, A);
     197             :     pari_sp av3 = avma;
     198             :     if (expo(B_A) < G) break;
     199             :     a = addrr(A,B); shiftr_inplace(a, -1);
     200             :     b = mulrr(A,B);
     201             :     affrr(a, A);
     202             :     affrr(sqrtr_abs(b), B); set_avma(av3);
     203             :     y = sqrr(B_A); shiftr_inplace(y, i - 2);
     204             :     affrr(subrr(C, y), C); set_avma(av2);
     205             :   }
     206             :   shiftr_inplace(C, 2);
     207             :   return divrr(sqrr(addrr(A,B)), C);
     208             : }
     209             : #endif
     210             : 
     211             : GEN
     212    34573885 : constpi(long prec)
     213             : {
     214             :   pari_sp av;
     215             :   GEN tmp;
     216    34573885 :   if (gpi && realprec(gpi) >= prec) return gpi;
     217             : 
     218       38274 :   av = avma;
     219       38274 :   tmp = gclone(pi_ramanujan(prec));
     220       38424 :   swap_clone(&gpi,tmp);
     221       38424 :   return gc_const(av, gpi);
     222             : }
     223             : 
     224             : GEN
     225    34573866 : mppi(long prec) { return rtor(constpi(prec), prec); }
     226             : 
     227             : /* Pi * 2^n */
     228             : GEN
     229    21420773 : Pi2n(long n, long prec)
     230             : {
     231    21420773 :   GEN x = mppi(prec); shiftr_inplace(x, n);
     232    21420805 :   return x;
     233             : }
     234             : 
     235             : /* I * Pi * 2^n */
     236             : GEN
     237      262235 : PiI2n(long n, long prec) { retmkcomplex(gen_0, Pi2n(n, prec)); }
     238             : 
     239             : /* 2I * Pi */
     240             : GEN
     241      261346 : PiI2(long prec) { return PiI2n(1, prec); }
     242             : 
     243             : /********************************************************************/
     244             : /**                                                                **/
     245             : /**                       EULER CONSTANT                           **/
     246             : /**                                                                **/
     247             : /********************************************************************/
     248             : 
     249             : GEN
     250       57530 : consteuler(long prec)
     251             : {
     252             :   GEN u,v,a,b,tmpeuler;
     253             :   long l, n1, n, k, x;
     254             :   pari_sp av1, av2;
     255             : 
     256       57530 :   if (geuler && realprec(geuler) >= prec) return geuler;
     257             : 
     258         511 :   av1 = avma; tmpeuler = cgetr_block(prec);
     259             : 
     260         511 :   incrprec(prec);
     261             : 
     262         511 :   l = prec+EXTRAPREC64; x = (long) (1 + prec2nbits_mul(l, M_LN2/4));
     263         511 :   a = utor(x,l); u=logr_abs(a); setsigne(u,-1); affrr(u,a);
     264         511 :   b = real_1(l);
     265         511 :   v = real_1(l);
     266         511 :   n = (long)(1+3.591*x); /* z=3.591: z*[ ln(z)-1 ]=1 */
     267         511 :   n1 = minss(n, SQRTVERYBIGINT);
     268         511 :   if (x < SQRTVERYBIGINT)
     269             :   {
     270         511 :     ulong xx = x*x;
     271         511 :     av2 = avma;
     272      166199 :     for (k=1; k<n1; k++)
     273             :     {
     274      165688 :       affrr(divru(mulur(xx,b),k*k), b);
     275      165703 :       affrr(divru(addrr(divru(mulur(xx,a),k),b),k), a);
     276      165699 :       affrr(addrr(u,a), u);
     277      165676 :       affrr(addrr(v,b), v); set_avma(av2);
     278             :     }
     279        1022 :     for (   ; k<=n; k++)
     280             :     {
     281         511 :       affrr(divru(divru(mulur(xx,b),k),k), b);
     282         511 :       affrr(divru(addrr(divru(mulur(xx,a),k),b),k), a);
     283         511 :       affrr(addrr(u,a), u);
     284         511 :       affrr(addrr(v,b), v); set_avma(av2);
     285             :     }
     286             :   }
     287             :   else
     288             :   {
     289           0 :     GEN xx = sqru(x);
     290           0 :     av2 = avma;
     291           0 :     for (k=1; k<n1; k++)
     292             :     {
     293           0 :       affrr(divru(mulir(xx,b),k*k), b);
     294           0 :       affrr(divru(addrr(divru(mulir(xx,a),k),b),k), a);
     295           0 :       affrr(addrr(u,a), u);
     296           0 :       affrr(addrr(v,b), v); set_avma(av2);
     297             :     }
     298           0 :     for (   ; k<=n; k++)
     299             :     {
     300           0 :       affrr(divru(divru(mulir(xx,b),k),k), b);
     301           0 :       affrr(divru(addrr(divru(mulir(xx,a),k),b),k), a);
     302           0 :       affrr(addrr(u,a), u);
     303           0 :       affrr(addrr(v,b), v); set_avma(av2);
     304             :     }
     305             :   }
     306         511 :   divrrz(u,v,tmpeuler);
     307         511 :   swap_clone(&geuler,tmpeuler);
     308         511 :   return gc_const(av1, geuler);
     309             : }
     310             : 
     311             : GEN
     312       57530 : mpeuler(long prec) { return rtor(consteuler(prec), prec); }
     313             : 
     314             : /********************************************************************/
     315             : /**                                                                **/
     316             : /**                       CATALAN CONSTANT                         **/
     317             : /**                                                                **/
     318             : /********************************************************************/
     319             : /*        inf  256^i (580i^2 - 184i + 15) (2i)!^3 (3i)!^2
     320             :  * 64 G = SUM  ------------------------------------------
     321             :  *        i=1             i^3 (2i-1) (6i)!^2           */
     322             : static GEN
     323          14 : catalan(long prec)
     324             : {
     325          14 :   long i, nmax = 1 + prec2nbits(prec) / 7.509; /* / log2(729/4) */
     326             :   struct abpq_res R;
     327             :   struct abpq A;
     328             :   GEN u;
     329          14 :   abpq_init(&A, nmax);
     330          14 :   A.a[0] = gen_0; A.b[0] = A.p[0] = A.q[0] = gen_1;
     331        1750 :   for (i = 1; i <= nmax; i++)
     332             :   {
     333        1736 :     A.a[i] = addiu(muluu(580*i - 184, i), 15);
     334        1736 :     A.b[i] = muliu(powuu(i, 3), 2*i - 1);
     335        1736 :     A.p[i] = mului(64*i-32, powuu(i,3));
     336        1736 :     A.q[i] = sqri(muluu(6*i - 1, 18*i - 15));
     337             :   }
     338          14 :   abpq_sum(&R, 0, nmax, &A);
     339          14 :   u = rdivii(R.T, mulii(R.B,R.Q),prec);
     340          14 :   shiftr_inplace(u, -6); return u;
     341             : }
     342             : 
     343             : GEN
     344          14 : constcatalan(long prec)
     345             : {
     346          14 :   pari_sp av = avma;
     347             :   GEN tmp;
     348          14 :   if (gcatalan && realprec(gcatalan) >= prec) return gcatalan;
     349          14 :   tmp = gclone(catalan(prec));
     350          14 :   swap_clone(&gcatalan,tmp);
     351          14 :   return gc_const(av, gcatalan);
     352             : }
     353             : 
     354             : GEN
     355          14 : mpcatalan(long prec) { return rtor(constcatalan(prec), prec); }
     356             : 
     357             : /********************************************************************/
     358             : /**                                                                **/
     359             : /**          TYPE CONVERSION FOR TRANSCENDENTAL FUNCTIONS          **/
     360             : /**                                                                **/
     361             : /********************************************************************/
     362             : static GEN
     363     2013064 : transvec(GEN (*f)(GEN,long), GEN x, long prec)
     364     6550875 : { pari_APPLY_same(f(gel(x,i), prec)); }
     365             : static GEN
     366         329 : transvecgen(void *E, GEN (*f)(void *,GEN,long), GEN x, long prec)
     367         735 : { pari_APPLY_same(f(E, gel(x,i), prec)); }
     368             : 
     369             : GEN
     370     3738795 : trans_eval(const char *fun, GEN (*f)(GEN,long), GEN x, long prec)
     371             : {
     372     3738795 :   pari_sp av = avma;
     373     3738795 :   if (prec < LOWDEFAULTPREC) pari_err_BUG("trans_eval [prec < 3]");
     374     3738811 :   switch(typ(x))
     375             :   {
     376     1478504 :     case t_INT:    x = f(itor(x,prec),prec); break;
     377      247186 :     case t_FRAC:   x = f(fractor(x, prec),prec); break;
     378           7 :     case t_QUAD:   x = f(quadtofp(x,prec),prec); break;
     379          14 :     case t_POLMOD: x = transvec(f, polmod_to_embed(x,prec), prec); break;
     380     2013051 :     case t_VEC:
     381             :     case t_COL:
     382     2013051 :     case t_MAT: return transvec(f, x, prec);
     383          49 :     default: pari_err_TYPE(fun,x);
     384             :       return NULL;/*LCOV_EXCL_LINE*/
     385             :   }
     386     1725684 :   return gerepileupto(av, x);
     387             : }
     388             : 
     389             : GEN
     390        1883 : trans_evalgen(const char *fun, void *E, GEN (*f)(void*,GEN,long),
     391             :               GEN x, long prec)
     392             : {
     393        1883 :   pari_sp av = avma;
     394        1883 :   if (prec < LOWDEFAULTPREC) pari_err_BUG("trans_eval [prec < 3]");
     395        1883 :   switch(typ(x))
     396             :   {
     397         273 :     case t_INT:    x = f(E, itor(x,prec),prec); break;
     398        1246 :     case t_FRAC:   x = f(E, fractor(x, prec),prec); break;
     399           0 :     case t_QUAD:   x = f(E, quadtofp(x,prec),prec); break;
     400          70 :     case t_POLMOD: x = transvecgen(E, f, polmod_to_embed(x,prec), prec); break;
     401         259 :     case t_VEC:
     402             :     case t_COL:
     403         259 :     case t_MAT: return transvecgen(E, f, x, prec);
     404          35 :     default: pari_err_TYPE(fun,x);
     405             :       return NULL;/*LCOV_EXCL_LINE*/
     406             :   }
     407        1589 :   return gerepileupto(av, x);
     408             : }
     409             : 
     410             : /*******************************************************************/
     411             : /*                                                                 */
     412             : /*                            POWERING                             */
     413             : /*                                                                 */
     414             : /*******************************************************************/
     415             : /* x a t_REAL 0, return exp(x) */
     416             : static GEN
     417       71077 : mpexp0(GEN x)
     418             : {
     419       71077 :   long e = expo(x);
     420       71077 :   return e >= 0? real_0_bit(e): real_1_bit(-e);
     421             : }
     422             : static GEN
     423       21049 : powr0(GEN x)
     424       21049 : { return signe(x)? real_1(realprec(x)): mpexp0(x); }
     425             : 
     426             : /* assume typ(x) = t_VEC */
     427             : static int
     428          49 : is_ext_qfr(GEN x)
     429          35 : { return lg(x) == 3 && typ(gel(x,1)) == t_QFB && !qfb_is_qfi(gel(x,1))
     430          84 :                     && typ(gel(x,2)) == t_REAL; }
     431             : 
     432             : /* x t_POL or t_SER, return scalarpol(Rg_get_1(x)) */
     433             : static GEN
     434      370292 : scalarpol_get_1(GEN x)
     435             : {
     436      370292 :   GEN y = cgetg(3,t_POL);
     437      370292 :   y[1] = evalvarn(varn(x)) | evalsigne(1);
     438      370292 :   gel(y,2) = Rg_get_1(x); return y;
     439             : }
     440             : /* to be called by the generic function gpowgs(x,s) when s = 0 */
     441             : static GEN
     442     1586915 : gpowg0(GEN x)
     443             : {
     444             :   long lx, i;
     445             :   GEN y;
     446             : 
     447     1586915 :   switch(typ(x))
     448             :   {
     449     1172665 :     case t_INT: case t_REAL: case t_FRAC: case t_PADIC:
     450     1172665 :       return gen_1;
     451             : 
     452           7 :     case t_QUAD: x++; /*fall through*/
     453       37902 :     case t_COMPLEX: {
     454       37902 :       pari_sp av = avma;
     455       37902 :       GEN a = gpowg0(gel(x,1));
     456       37902 :       GEN b = gpowg0(gel(x,2));
     457       37902 :       if (a == gen_1) return b;
     458          14 :       if (b == gen_1) return a;
     459           7 :       return gerepileupto(av, gmul(a,b));
     460             :     }
     461         133 :     case t_INTMOD:
     462         133 :       y = cgetg(3,t_INTMOD);
     463         133 :       gel(y,1) = icopy(gel(x,1));
     464         133 :       gel(y,2) = is_pm1(gel(x,1))? gen_0: gen_1;
     465         133 :       return y;
     466             : 
     467        5754 :     case t_FFELT: return FF_1(x);
     468             : 
     469         973 :     case t_POLMOD:
     470         973 :       retmkpolmod(scalarpol_get_1(gel(x,1)), gcopy(gel(x,1)));
     471             : 
     472           7 :     case t_RFRAC:
     473           7 :       return scalarpol_get_1(gel(x,2));
     474      369312 :     case t_POL: case t_SER:
     475      369312 :       return scalarpol_get_1(x);
     476             : 
     477          84 :     case t_MAT:
     478          84 :       lx=lg(x); if (lx==1) return cgetg(1,t_MAT);
     479          77 :       if (lx != lgcols(x)) pari_err_DIM("gpow");
     480          77 :       y = matid(lx-1);
     481         252 :       for (i=1; i<lx; i++) gcoeff(y,i,i) = gpowg0(gcoeff(x,i,i));
     482          77 :       return y;
     483          21 :     case t_VEC: if (!is_ext_qfr(x)) break;
     484             :     /* fall through handle extended t_QFB */
     485          28 :     case t_QFB: return qfbpow(x, gen_0);
     486          49 :     case t_VECSMALL: return identity_perm(lg(x) - 1);
     487             :   }
     488          12 :   pari_err_TYPE("gpow",x);
     489             :   return NULL; /* LCOV_EXCL_LINE */
     490             : }
     491             : 
     492             : static GEN
     493     5532811 : _sqr(void *data /* ignored */, GEN x) { (void)data; return gsqr(x); }
     494             : static GEN
     495     3468588 : _mul(void *data /* ignored */, GEN x, GEN y) { (void)data; return gmul(x,y); }
     496             : static GEN
     497      331929 : _one(void *x) { return gpowg0((GEN) x); }
     498             : static GEN
     499    81856870 : _sqri(void *data /* ignored */, GEN x) { (void)data; return sqri(x); }
     500             : static GEN
     501    29948352 : _muli(void *data /* ignored */, GEN x, GEN y) { (void)data; return mulii(x,y); }
     502             : static GEN
     503    14939814 : _sqrr(void *data /* ignored */, GEN x) { (void)data; return sqrr(x); }
     504             : static GEN
     505     6259897 : _mulr(void *data /* ignored */, GEN x, GEN y) { (void)data; return mulrr(x,y); }
     506             : static GEN
     507       13755 : _oner(void *data /* prec */) { return real_1( *(long*) data); }
     508             : 
     509             : /* INTEGER POWERING (a^n for integer a != 0 and integer n > 0)
     510             :  *
     511             :  * Use left shift binary algorithm (RS is wasteful: multiplies big numbers,
     512             :  * with LS one of them is the base, hence small). Sign of result is set
     513             :  * to s (= 1,-1). Makes life easier for caller, which otherwise might do a
     514             :  * setsigne(gen_1 / gen_m1) */
     515             : static GEN
     516    96254828 : powiu_sign(GEN a, ulong N, long s)
     517             : {
     518             :   pari_sp av;
     519             :   GEN y;
     520             : 
     521    96254828 :   if (lgefint(a) == 3)
     522             :   { /* easy if |a| < 3 */
     523    94751873 :     ulong q = a[2];
     524    94751873 :     if (q == 1) return (s>0)? gen_1: gen_m1;
     525    85607780 :     if (q == 2) { a = int2u(N); setsigne(a,s); return a; }
     526    63177215 :     q = upowuu(q, N);
     527    63179483 :     if (q) return s>0? utoipos(q): utoineg(q);
     528             :   }
     529    32608170 :   if (N <= 2) {
     530     1817392 :     if (N == 2) return sqri(a);
     531       20475 :     a = icopy(a); setsigne(a,s); return a;
     532             :   }
     533    30790778 :   av = avma;
     534    30790778 :   y = gen_powu_i(a, N, NULL, &_sqri, &_muli);
     535    30791201 :   setsigne(y,s); return gerepileuptoint(av, y);
     536             : }
     537             : /* a^n */
     538             : GEN
     539    96431671 : powiu(GEN a, ulong n)
     540             : {
     541             :   long s;
     542    96431671 :   if (!n) return gen_1;
     543    95180283 :   s = signe(a);
     544    95180283 :   if (!s) return gen_0;
     545    95105381 :   return powiu_sign(a, n, (s < 0 && odd(n))? -1: 1);
     546             : }
     547             : GEN
     548    20900520 : powis(GEN a, long n)
     549             : {
     550             :   long s;
     551             :   GEN t, y;
     552    20900520 :   if (n >= 0) return powiu(a, n);
     553      578222 :   s = signe(a);
     554      578222 :   if (!s) pari_err_INV("powis",gen_0);
     555      578226 :   t = (s < 0 && odd(n))? gen_m1: gen_1;
     556      578226 :   if (is_pm1(a)) return t;
     557             :   /* n < 0, |a| > 1 */
     558      575824 :   y = cgetg(3,t_FRAC);
     559      575825 :   gel(y,1) = t;
     560      575825 :   gel(y,2) = powiu_sign(a, -n, 1); /* force denominator > 0 */
     561      575821 :   return y;
     562             : }
     563             : GEN
     564    46223854 : powuu(ulong p, ulong N)
     565             : {
     566             :   pari_sp av;
     567             :   ulong pN;
     568             :   GEN y;
     569    46223854 :   if (!p) return gen_0;
     570    46223777 :   if (N <= 2)
     571             :   {
     572    40248415 :     if (N == 2) return sqru(p);
     573    37964944 :     if (N == 1) return utoipos(p);
     574     5087020 :     return gen_1;
     575             :   }
     576     5975362 :   pN = upowuu(p, N);
     577     5975471 :   if (pN) return utoipos(pN);
     578      993642 :   if (p == 2) return int2u(N);
     579      980189 :   av = avma;
     580      980189 :   y = gen_powu_i(utoipos(p), N, NULL, &_sqri, &_muli);
     581      980183 :   return gerepileuptoint(av, y);
     582             : }
     583             : 
     584             : /* return 0 if overflow */
     585             : static ulong
     586    18875344 : usqru(ulong p) { return p & HIGHMASK? 0: p*p; }
     587             : ulong
     588    99730037 : upowuu(ulong p, ulong k)
     589             : {
     590             : #ifdef LONG_IS_64BIT
     591    85636322 :   const ulong CUTOFF3 = 2642245;
     592    85636322 :   const ulong CUTOFF4 = 65535;
     593    85636322 :   const ulong CUTOFF5 = 7131;
     594    85636322 :   const ulong CUTOFF6 = 1625;
     595    85636322 :   const ulong CUTOFF7 = 565;
     596    85636322 :   const ulong CUTOFF8 = 255;
     597    85636322 :   const ulong CUTOFF9 = 138;
     598    85636322 :   const ulong CUTOFF10 = 84;
     599    85636322 :   const ulong CUTOFF11 = 56;
     600    85636322 :   const ulong CUTOFF12 = 40;
     601    85636322 :   const ulong CUTOFF13 = 30;
     602    85636322 :   const ulong CUTOFF14 = 23;
     603    85636322 :   const ulong CUTOFF15 = 19;
     604    85636322 :   const ulong CUTOFF16 = 15;
     605    85636322 :   const ulong CUTOFF17 = 13;
     606    85636322 :   const ulong CUTOFF18 = 11;
     607    85636322 :   const ulong CUTOFF19 = 10;
     608    85636322 :   const ulong CUTOFF20 =  9;
     609             : #else
     610    14093715 :   const ulong CUTOFF3 = 1625;
     611    14093715 :   const ulong CUTOFF4 =  255;
     612    14093715 :   const ulong CUTOFF5 =   84;
     613    14093715 :   const ulong CUTOFF6 =   40;
     614    14093715 :   const ulong CUTOFF7 =   23;
     615    14093715 :   const ulong CUTOFF8 =   15;
     616    14093715 :   const ulong CUTOFF9 =   11;
     617    14093715 :   const ulong CUTOFF10 =   9;
     618    14093715 :   const ulong CUTOFF11 =   7;
     619    14093715 :   const ulong CUTOFF12 =   6;
     620    14093715 :   const ulong CUTOFF13 =   5;
     621    14093715 :   const ulong CUTOFF14 =   4;
     622    14093715 :   const ulong CUTOFF15 =   4;
     623    14093715 :   const ulong CUTOFF16 =   3;
     624    14093715 :   const ulong CUTOFF17 =   3;
     625    14093715 :   const ulong CUTOFF18 =   3;
     626    14093715 :   const ulong CUTOFF19 =   3;
     627    14093715 :   const ulong CUTOFF20 =   3;
     628             : #endif
     629             : 
     630    99730037 :   if (p <= 2)
     631             :   {
     632     9624528 :     if (p < 2) return p;
     633     9077778 :     return k < BITS_IN_LONG? 1UL<<k: 0;
     634             :   }
     635    90105509 :   switch(k)
     636             :   {
     637             :     ulong p2, p3, p4, p5, p8;
     638     8249936 :     case 0:  return 1;
     639    19924084 :     case 1:  return p;
     640    18875341 :     case 2:  return usqru(p);
     641     3643705 :     case 3:  if (p > CUTOFF3) return 0; return p*p*p;
     642    11364939 :     case 4:  if (p > CUTOFF4) return 0; p2=p*p; return p2*p2;
     643     2176532 :     case 5:  if (p > CUTOFF5) return 0; p2=p*p; return p2*p2*p;
     644     6977429 :     case 6:  if (p > CUTOFF6) return 0; p2=p*p; return p2*p2*p2;
     645      346822 :     case 7:  if (p > CUTOFF7) return 0; p2=p*p; return p2*p2*p2*p;
     646      455539 :     case 8:  if (p > CUTOFF8) return 0; p2=p*p; p4=p2*p2; return p4*p4;
     647      395649 :     case 9:  if (p > CUTOFF9) return 0; p2=p*p; p4=p2*p2; return p4*p4*p;
     648     4914800 :     case 10: if (p > CUTOFF10)return 0; p2=p*p; p4=p2*p2; return p4*p4*p2;
     649      170352 :     case 11: if (p > CUTOFF11)return 0; p2=p*p; p4=p2*p2; return p4*p4*p2*p;
     650     4792785 :     case 12: if (p > CUTOFF12)return 0; p2=p*p; p4=p2*p2; return p4*p4*p4;
     651       97089 :     case 13: if (p > CUTOFF13)return 0; p2=p*p; p4=p2*p2; return p4*p4*p4*p;
     652     4746599 :     case 14: if (p > CUTOFF14)return 0; p2=p*p; p4=p2*p2; return p4*p4*p4*p2;
     653      131122 :     case 15: if (p > CUTOFF15)return 0;
     654       75476 :       p2=p*p; p3=p2*p; p5=p3*p2; return p5*p5*p5;
     655      104306 :     case 16: if (p > CUTOFF16)return 0;
     656       52249 :       p2=p*p; p4=p2*p2; p8=p4*p4; return p8*p8;
     657       79525 :     case 17: if (p > CUTOFF17)return 0;
     658       41864 :       p2=p*p; p4=p2*p2; p8=p4*p4; return p*p8*p8;
     659       69145 :     case 18: if (p > CUTOFF18)return 0;
     660       38783 :       p2=p*p; p4=p2*p2; p8=p4*p4; return p2*p8*p8;
     661      818761 :     case 19: if (p > CUTOFF19)return 0;
     662      764910 :       p2=p*p; p4=p2*p2; p8=p4*p4; return p*p2*p8*p8;
     663       63745 :     case 20: if (p > CUTOFF20)return 0;
     664       21660 :       p2=p*p; p4=p2*p2; p8=p4*p4; return p4*p8*p8;
     665             :   }
     666             : #ifdef LONG_IS_64BIT
     667     1487368 :   switch(p)
     668             :   {
     669      221651 :     case 3: if (k > 40) return 0;
     670      135642 :       break;
     671       17028 :     case 4: if (k > 31) return 0;
     672         774 :       return 1UL<<(2*k);
     673      637562 :     case 5: if (k > 27) return 0;
     674       20039 :       break;
     675       49650 :     case 6: if (k > 24) return 0;
     676        9180 :       break;
     677       56098 :     case 7: if (k > 22) return 0;
     678        2732 :       break;
     679      505379 :     default: return 0;
     680             :   }
     681             :   /* no overflow */
     682             :   {
     683      167593 :     ulong q = upowuu(p, k >> 1);
     684      167593 :     q *= q ;
     685      167593 :     return odd(k)? q*p: q;
     686             :   }
     687             : #else
     688      219936 :   return 0;
     689             : #endif
     690             : }
     691             : 
     692             : GEN
     693       12017 : upowers(ulong x, long n)
     694             : {
     695             :   long i;
     696       12017 :   GEN p = cgetg(n + 2, t_VECSMALL);
     697       12017 :   uel(p,1) = 1; if (n == 0) return p;
     698       12017 :   uel(p,2) = x;
     699       91465 :   for (i = 3; i <= n; i++)
     700       79448 :     uel(p,i) = uel(p,i-1)*x;
     701       12017 :   return p;
     702             : }
     703             : 
     704             : typedef struct {
     705             :   long prec, a;
     706             :   GEN (*sqr)(GEN);
     707             :   GEN (*mulug)(ulong,GEN);
     708             : } sr_muldata;
     709             : 
     710             : static GEN
     711     1595605 : _rpowuu_sqr(void *data, GEN x)
     712             : {
     713     1595605 :   sr_muldata *D = (sr_muldata *)data;
     714     1595605 :   if (typ(x) == t_INT && lgefint(x) >= D->prec)
     715             :   { /* switch to t_REAL */
     716         187 :     D->sqr   = &sqrr;
     717         187 :     D->mulug = &mulur; x = itor(x, D->prec);
     718             :   }
     719     1595605 :   return D->sqr(x);
     720             : }
     721             : 
     722             : static GEN
     723      624180 : _rpowuu_msqr(void *data, GEN x)
     724             : {
     725      624180 :   GEN x2 = _rpowuu_sqr(data, x);
     726      624180 :   sr_muldata *D = (sr_muldata *)data;
     727      624180 :   return D->mulug(D->a, x2);
     728             : }
     729             : 
     730             : /* return a^n as a t_REAL of precision prec. Assume a > 0, n > 0 */
     731             : GEN
     732      428539 : rpowuu(ulong a, ulong n, long prec)
     733             : {
     734             :   pari_sp av;
     735             :   GEN y, z;
     736             :   sr_muldata D;
     737             : 
     738      428539 :   if (a == 1) return real_1(prec);
     739      428539 :   if (a == 2) return real2n(n, prec);
     740      428539 :   if (n == 1) return utor(a, prec);
     741      423608 :   z = cgetr(prec);
     742      423608 :   av = avma;
     743      423608 :   D.sqr   = &sqri;
     744      423608 :   D.mulug = &mului;
     745      423608 :   D.prec = prec;
     746      423608 :   D.a = (long)a;
     747      423608 :   y = gen_powu_fold_i(utoipos(a), n, (void*)&D, &_rpowuu_sqr, &_rpowuu_msqr);
     748      423608 :   mpaff(y, z); return gc_const(av,z);
     749             : }
     750             : 
     751             : GEN
     752     4948802 : powrs(GEN x, long n)
     753             : {
     754     4948802 :   pari_sp av = avma;
     755             :   GEN y;
     756     4948802 :   if (!n) return powr0(x);
     757     4948802 :   y = gen_powu_i(x, (ulong)labs(n), NULL, &_sqrr, &_mulr);
     758     4949226 :   if (n < 0) y = invr(y);
     759     4949028 :   return gerepileuptoleaf(av,y);
     760             : }
     761             : GEN
     762     4815459 : powru(GEN x, ulong n)
     763             : {
     764     4815459 :   pari_sp av = avma;
     765             :   GEN y;
     766     4815459 :   if (!n) return powr0(x);
     767     4794921 :   y = gen_powu_i(x, n, NULL, &_sqrr, &_mulr);
     768     4794897 :   return gerepileuptoleaf(av,y);
     769             : }
     770             : 
     771             : GEN
     772       13755 : powersr(GEN x, long n)
     773             : {
     774       13755 :   long prec = realprec(x);
     775       13755 :   return gen_powers(x, n, 1, &prec, &_sqrr, &_mulr, &_oner);
     776             : }
     777             : 
     778             : /* x^(s/2), assume x t_REAL */
     779             : GEN
     780           0 : powrshalf(GEN x, long s)
     781             : {
     782           0 :   if (s & 1) return sqrtr(powrs(x, s));
     783           0 :   return powrs(x, s>>1);
     784             : }
     785             : /* x^(s/2), assume x t_REAL */
     786             : GEN
     787      117812 : powruhalf(GEN x, ulong s)
     788             : {
     789      117812 :   if (s & 1) return sqrtr(powru(x, s));
     790        7085 :   return powru(x, s>>1);
     791             : }
     792             : /* x^(n/d), assume x t_REAL, return t_REAL */
     793             : GEN
     794         511 : powrfrac(GEN x, long n, long d)
     795             : {
     796             :   long z;
     797         511 :   if (!n) return powr0(x);
     798           0 :   z = cgcd(n, d); if (z > 1) { n /= z; d /= z; }
     799           0 :   if (d == 1) return powrs(x, n);
     800           0 :   x = powrs(x, n);
     801           0 :   if (d == 2) return sqrtr(x);
     802           0 :   return sqrtnr(x, d);
     803             : }
     804             : 
     805             : /* assume x != 0 */
     806             : static GEN
     807      624608 : pow_monome(GEN x, long n)
     808             : {
     809      624608 :   long i, d, dx = degpol(x);
     810             :   GEN A, b, y;
     811             : 
     812      624608 :   if (n < 0) { n = -n; y = cgetg(3, t_RFRAC); } else y = NULL;
     813             : 
     814      624608 :   if (HIGHWORD(dx) || HIGHWORD(n))
     815           8 :   {
     816             :     LOCAL_HIREMAINDER;
     817           9 :     d = (long)mulll((ulong)dx, (ulong)n);
     818           9 :     if (hiremainder || (d &~ LGBITS)) d = LGBITS; /* overflow */
     819           9 :     d += 2;
     820             :   }
     821             :   else
     822      624599 :     d = dx*n + 2;
     823      624608 :   if ((d + 1) & ~LGBITS) pari_err(e_OVERFLOW,"pow_monome [degree]");
     824      624601 :   A = cgetg(d+1, t_POL); A[1] = x[1];
     825     6050983 :   for (i=2; i < d; i++) gel(A,i) = gen_0;
     826      624601 :   b = gpowgs(gel(x,dx+2), n); /* not memory clean if (n < 0) */
     827      624600 :   if (!y) y = A;
     828             :   else {
     829       20482 :     GEN c = denom_i(b);
     830       20482 :     gel(y,1) = c; if (c != gen_1) b = gmul(b,c);
     831       20482 :     gel(y,2) = A;
     832             :   }
     833      624600 :   gel(A,d) = b; return y;
     834             : }
     835             : 
     836             : /* x t_PADIC */
     837             : static GEN
     838     1305479 : powps(GEN x, long n)
     839             : {
     840     1305479 :   long e = n*valp(x), v;
     841     1305479 :   GEN t, y, mod, p = gel(x,2);
     842             :   pari_sp av;
     843             : 
     844     1305479 :   if (!signe(gel(x,4))) {
     845          84 :     if (n < 0) pari_err_INV("powps",x);
     846          77 :     return zeropadic(p, e);
     847             :   }
     848     1305395 :   v = z_pval(n, p);
     849             : 
     850     1305392 :   y = cgetg(5,t_PADIC);
     851     1305389 :   mod = gel(x,3);
     852     1305389 :   if (v == 0) mod = icopy(mod);
     853             :   else
     854             :   {
     855       86632 :     if (precp(x) == 1 && absequaliu(p, 2)) v++;
     856       86632 :     mod = mulii(mod, powiu(p,v));
     857       86632 :     mod = gerepileuptoint((pari_sp)y, mod);
     858             :   }
     859     1305389 :   y[1] = evalprecp(precp(x) + v) | evalvalp(e);
     860     1305388 :   gel(y,2) = icopy(p);
     861     1305386 :   gel(y,3) = mod;
     862             : 
     863     1305386 :   av = avma; t = gel(x,4);
     864     1305386 :   if (n < 0) { t = Fp_inv(t, mod); n = -n; }
     865     1305386 :   t = Fp_powu(t, n, mod);
     866     1305390 :   gel(y,4) = gerepileuptoint(av, t);
     867     1305389 :   return y;
     868             : }
     869             : /* x t_PADIC */
     870             : static GEN
     871         161 : powp(GEN x, GEN n)
     872             : {
     873             :   long v;
     874         161 :   GEN y, mod, p = gel(x,2);
     875             : 
     876         161 :   if (valp(x)) pari_err_OVERFLOW("valp()");
     877             : 
     878         161 :   if (!signe(gel(x,4))) {
     879          14 :     if (signe(n) < 0) pari_err_INV("powp",x);
     880           7 :     return zeropadic(p, 0);
     881             :   }
     882         147 :   v = Z_pval(n, p);
     883             : 
     884         147 :   y = cgetg(5,t_PADIC);
     885         147 :   mod = gel(x,3);
     886         147 :   if (v == 0) mod = icopy(mod);
     887             :   else
     888             :   {
     889          70 :     mod = mulii(mod, powiu(p,v));
     890          70 :     mod = gerepileuptoint((pari_sp)y, mod);
     891             :   }
     892         147 :   y[1] = evalprecp(precp(x) + v) | _evalvalp(0);
     893         147 :   gel(y,2) = icopy(p);
     894         147 :   gel(y,3) = mod;
     895         147 :   gel(y,4) = Fp_pow(gel(x,4), n, mod);
     896         147 :   return y;
     897             : }
     898             : static GEN
     899       23753 : pow_polmod(GEN x, GEN n)
     900             : {
     901       23753 :   GEN z = cgetg(3, t_POLMOD), a = gel(x,2), T = gel(x,1);
     902       23753 :   gel(z,1) = gcopy(T);
     903       23753 :   if (typ(a) != t_POL || varn(a) != varn(T) || lg(a) <= 3)
     904        1269 :     a = powgi(a, n);
     905             :   else {
     906       22484 :     pari_sp av = avma;
     907       22484 :     GEN p = NULL;
     908       22484 :     if (RgX_is_FpX(T, &p) && RgX_is_FpX(a, &p) && p)
     909             :     {
     910        8771 :       T = RgX_to_FpX(T, p); a = RgX_to_FpX(a, p);
     911        8771 :       if (lgefint(p) == 3)
     912             :       {
     913        8764 :         ulong pp = p[2];
     914        8764 :         a = Flxq_pow(ZX_to_Flx(a, pp), n, ZX_to_Flx(T, pp), pp);
     915        8764 :         a = Flx_to_ZX(a);
     916             :       }
     917             :       else
     918           7 :         a = FpXQ_pow(a, n, T, p);
     919        8771 :       a = FpX_to_mod(a, p);
     920        8771 :       a = gerepileupto(av, a);
     921             :     }
     922             :     else
     923             :     {
     924       13713 :       set_avma(av);
     925       13713 :       a = RgXQ_pow(a, n, gel(z,1));
     926             :     }
     927             :   }
     928       23753 :   gel(z,2) = a; return z;
     929             : }
     930             : 
     931             : GEN
     932   109386912 : gpowgs(GEN x, long n)
     933             : {
     934             :   long m;
     935             :   pari_sp av;
     936             :   GEN y;
     937             : 
     938   109386912 :   if (n == 0) return gpowg0(x);
     939   108207899 :   if (n == 1)
     940             :   {
     941    73231307 :     long t = typ(x);
     942    73231307 :     if (is_scalar_t(t)) return gcopy(x);
     943      718474 :     switch(t)
     944             :     {
     945      665505 :       case t_POL: case t_SER: case t_RFRAC: case t_MAT: case t_VECSMALL:
     946      665505 :         return gcopy(x);
     947          21 :       case t_VEC: if (!is_ext_qfr(x)) break;
     948             :       /* fall through handle extended t_QFB */
     949       52955 :       case t_QFB: return qfbred(x);
     950             :     }
     951          14 :     pari_err_TYPE("gpow", x);
     952             :   }
     953    34976717 :   if (n ==-1) return ginv(x);
     954    31823942 :   switch(typ(x))
     955             :   {
     956    20742346 :     case t_INT: return powis(x,n);
     957     4940401 :     case t_REAL: return powrs(x,n);
     958       29271 :     case t_INTMOD:
     959       29271 :       y = cgetg(3,t_INTMOD); gel(y,1) = icopy(gel(x,1));
     960       29271 :       gel(y,2) = Fp_pows(gel(x,2), n, gel(x,1));
     961       29271 :       return y;
     962      286150 :     case t_FRAC:
     963             :     {
     964      286150 :       GEN a = gel(x,1), b = gel(x,2);
     965      286150 :       long s = (signe(a) < 0 && odd(n))? -1: 1;
     966      286150 :       if (n < 0) {
     967         700 :         n = -n;
     968         700 :         if (is_pm1(a)) return powiu_sign(b, n, s); /* +-1/x[2] inverts to t_INT */
     969         490 :         swap(a, b);
     970             :       }
     971      285940 :       y = cgetg(3, t_FRAC);
     972      285940 :       gel(y,1) = powiu_sign(a, n, s);
     973      285940 :       gel(y,2) = powiu_sign(b, n, 1);
     974      285940 :       return y;
     975             :     }
     976     1305479 :     case t_PADIC: return powps(x, n);
     977      249144 :     case t_RFRAC:
     978             :     {
     979      249144 :       av = avma; y = cgetg(3, t_RFRAC); m = labs(n);
     980      249144 :       gel(y,1) = gpowgs(gel(x,1),m);
     981      249144 :       gel(y,2) = gpowgs(gel(x,2),m);
     982      249144 :       if (n < 0) y = ginv(y);
     983      249144 :       return gerepileupto(av,y);
     984             :     }
     985       23746 :     case t_POLMOD: {
     986       23746 :       long N[] = {evaltyp(t_INT) | _evallg(3),0,0};
     987       23746 :       affsi(n,N); return pow_polmod(x, N);
     988             :     }
     989           7 :     case t_VEC: if (!is_ext_qfr(x)) pari_err_TYPE("gpow", x);
     990             :     /* fall through handle extended t_QFB */
     991     1293818 :     case t_QFB: return qfbpows(x, n);
     992     1183135 :     case t_POL:
     993     1183135 :       if (RgX_is_monomial(x)) return pow_monome(x, n);
     994             :     default: {
     995     2328979 :       pari_sp av = avma;
     996     2328979 :       y = gen_powu_i(x, (ulong)labs(n), NULL, &_sqr, &_mul);
     997     2328996 :       if (n < 0) y = ginv(y);
     998     2329002 :       return gerepileupto(av,y);
     999             :     }
    1000             :   }
    1001             : }
    1002             : 
    1003             : /* n a t_INT */
    1004             : GEN
    1005    98164222 : powgi(GEN x, GEN n)
    1006             : {
    1007             :   GEN y;
    1008             : 
    1009    98164222 :   if (!is_bigint(n)) return gpowgs(x, itos(n));
    1010             :   /* probable overflow for nonmodular types (typical exception: (X^0)^N) */
    1011       25653 :   switch(typ(x))
    1012             :   {
    1013       25326 :     case t_INTMOD:
    1014       25326 :       y = cgetg(3,t_INTMOD); gel(y,1) = icopy(gel(x,1));
    1015       25328 :       gel(y,2) = Fp_pow(gel(x,2), n, gel(x,1));
    1016       25330 :       return y;
    1017         101 :     case t_FFELT: return FF_pow(x,n);
    1018         161 :     case t_PADIC: return powp(x, n);
    1019             : 
    1020          35 :     case t_INT:
    1021          35 :       if (is_pm1(x)) return (signe(x) < 0 && mpodd(n))? gen_m1: gen_1;
    1022          14 :       if (signe(x)) pari_err_OVERFLOW("lg()");
    1023           7 :       if (signe(n) < 0) pari_err_INV("powgi",gen_0);
    1024           7 :       return gen_0;
    1025           7 :     case t_FRAC:
    1026           7 :       pari_err_OVERFLOW("lg()");
    1027             : 
    1028           0 :     case t_VEC: if (!is_ext_qfr(x)) pari_err_TYPE("gpow",x);
    1029             :     /* fall through handle extended t_QFB */
    1030          12 :     case t_QFB: return qfbpow(x, n);
    1031           7 :     case t_POLMOD: return pow_polmod(x, n);
    1032           7 :     default: {
    1033           7 :       pari_sp av = avma;
    1034           7 :       y = gen_pow_i(x, n, NULL, &_sqr, &_mul);
    1035           7 :       if (signe(n) < 0) return gerepileupto(av, ginv(y));
    1036           7 :       return gerepilecopy(av,y);
    1037             :     }
    1038             :   }
    1039             : }
    1040             : 
    1041             : /* Assume x = 1 + O(t), n a scalar. Return x^n */
    1042             : static GEN
    1043        7854 : ser_pow_1(GEN x, GEN n)
    1044             : {
    1045             :   long lx, mi, i, j, d;
    1046        7854 :   GEN y = cgetg_copy(x, &lx), X = x+2, Y = y + 2;
    1047        7854 :   y[1] = evalsigne(1) | _evalvalser(0) | evalvarn(varn(x));
    1048       74179 :   d = mi = lx-3; while (mi>=1 && isrationalzero(gel(X,mi))) mi--;
    1049        7854 :   gel(Y,0) = gen_1;
    1050      110383 :   for (i=1; i<=d; i++)
    1051             :   {
    1052      102529 :     pari_sp av = avma;
    1053      102529 :     GEN s = gen_0;
    1054      487704 :     for (j=1; j<=minss(i,mi); j++)
    1055             :     {
    1056      385175 :       GEN t = gsubgs(gmulgu(n,j),i-j);
    1057      385175 :       s = gadd(s, gmul(gmul(t, gel(X,j)), gel(Y,i-j)));
    1058             :     }
    1059      102529 :     gel(Y,i) = gerepileupto(av, gdivgu(s,i));
    1060             :   }
    1061        7854 :   return y;
    1062             : }
    1063             : 
    1064             : /* we suppose n != 0, valser(x) = 0 and leading-term(x) != 0. Not stack clean */
    1065             : static GEN
    1066        7959 : ser_pow(GEN x, GEN n, long prec)
    1067             : {
    1068             :   GEN y, c, lead;
    1069        7959 :   if (varncmp(gvar(n), varn(x)) <= 0) return gexp(gmul(n, glog(x,prec)), prec);
    1070        7854 :   lead = gel(x,2);
    1071        7854 :   if (gequal1(lead)) return ser_pow_1(x, n);
    1072        7469 :   x = ser_normalize(x);
    1073        7469 :   if (typ(n) == t_FRAC && !isinexact(lead) && ispower(lead, gel(n,2), &c))
    1074         112 :     c = powgi(c, gel(n,1));
    1075             :   else
    1076        7357 :     c = gpow(lead,n, prec);
    1077        7469 :   y = gmul(c, ser_pow_1(x, n));
    1078             :   /* gpow(t_POLMOD,n) can be a t_COL [conjvec] */
    1079        7469 :   if (typ(y) != t_SER) pari_err_TYPE("gpow", y);
    1080        7469 :   return y;
    1081             : }
    1082             : 
    1083             : static long
    1084        7868 : val_from_i(GEN E)
    1085             : {
    1086        7868 :   if (is_bigint(E)) pari_err_OVERFLOW("sqrtn [valuation]");
    1087        7861 :   return itos(E);
    1088             : }
    1089             : 
    1090             : /* return x^q, assume typ(x) = t_SER, typ(q) = t_INT/t_FRAC and q != 0 */
    1091             : static GEN
    1092        7875 : ser_powfrac(GEN x, GEN q, long prec)
    1093             : {
    1094        7875 :   GEN y, E = gmulsg(valser(x), q);
    1095             :   long e;
    1096             : 
    1097        7875 :   if (!signe(x))
    1098             :   {
    1099          21 :     if (gsigne(q) < 0) pari_err_INV("gpow", x);
    1100          21 :     return zeroser(varn(x), val_from_i(gfloor(E)));
    1101             :   }
    1102        7854 :   if (typ(E) != t_INT)
    1103           7 :     pari_err_DOMAIN("sqrtn", "valuation", "!=", mkintmod(gen_0, gel(q,2)), x);
    1104        7847 :   e = val_from_i(E);
    1105        7847 :   y = leafcopy(x); setvalser(y, 0);
    1106        7847 :   y = ser_pow(y, q, prec);
    1107        7847 :   setvalser(y, e); return y;
    1108             : }
    1109             : 
    1110             : static GEN
    1111         126 : gpow0(GEN x, GEN n, long prec)
    1112             : {
    1113         126 :   pari_sp av = avma;
    1114             :   long i, lx;
    1115             :   GEN y;
    1116         126 :   switch(typ(n))
    1117             :   {
    1118          84 :     case t_INT: case t_REAL: case t_FRAC: case t_COMPLEX: case t_QUAD:
    1119          84 :       break;
    1120          35 :     case t_VEC: case t_COL: case t_MAT:
    1121          35 :       y = cgetg_copy(n, &lx);
    1122         105 :       for (i=1; i<lx; i++) gel(y,i) = gpow0(x,gel(n,i),prec);
    1123          35 :       return y;
    1124           7 :     default: pari_err_TYPE("gpow(0,n)", n);
    1125             :   }
    1126          84 :   n = real_i(n);
    1127          84 :   if (gsigne(n) <= 0) pari_err_DOMAIN("gpow(0,n)", "n", "<=", gen_0, n);
    1128          77 :   if (!precision(x)) return gcopy(x);
    1129             : 
    1130          14 :   x = ground(gmulsg(gexpo(x),n));
    1131          14 :   if (is_bigint(x) || uel(x,2) >= HIGHEXPOBIT)
    1132           7 :     pari_err_OVERFLOW("gpow");
    1133           7 :   set_avma(av); return real_0_bit(itos(x));
    1134             : }
    1135             : 
    1136             : /* centermod(x, log(2)), set *sh to the quotient */
    1137             : static GEN
    1138    15738504 : modlog2(GEN x, long *sh)
    1139             : {
    1140    15738504 :   double d = rtodbl(x), qd = (fabs(d) + M_LN2/2)/M_LN2;
    1141             :   long q;
    1142    15738614 :   if (dblexpo(qd) >= BITS_IN_LONG-1) pari_err_OVERFLOW("expo()");
    1143    15738595 :   q = d < 0 ? - (long) qd: (long) qd;
    1144    15738595 :   *sh = q;
    1145    15738595 :   if (q) {
    1146    12749026 :     long l = realprec(x) + EXTRAPRECWORD;
    1147    12749026 :     x = subrr(rtor(x,l), mulsr(q, mplog2(l)));
    1148    12748775 :     if (!signe(x)) return NULL;
    1149             :   }
    1150    15738344 :   return x;
    1151             : }
    1152             : 
    1153             : /* x^n, n a t_FRAC */
    1154             : static GEN
    1155     5130791 : powfrac(GEN x, GEN n, long prec)
    1156             : {
    1157     5130791 :   GEN a = gel(n,1), d = gel(n,2);
    1158     5130791 :   long D = itos_or_0(d);
    1159     5130777 :   if (D == 2)
    1160             :   {
    1161     3537217 :     GEN y = gsqrt(x,prec);
    1162     3537748 :     if (!equali1(a)) y = gmul(y, powgi(x, shifti(subiu(a,1), -1)));
    1163     3537332 :     return y;
    1164             :   }
    1165     1593560 :   if (D && (is_real_t(typ(x)) && gsigne(x) > 0))
    1166             :   {
    1167             :     GEN z;
    1168     1589539 :     prec += nbits2extraprec(expi(a));
    1169     1589540 :     if (typ(x) != t_REAL) x = gtofp(x, prec);
    1170     1589540 :     z = sqrtnr(x, D);
    1171     1589540 :     if (!equali1(a)) z = powgi(z, a);
    1172     1589540 :     return z;
    1173             :   }
    1174        4021 :   return NULL;
    1175             : }
    1176             : 
    1177             : /* n = a+ib, x > 0 real, ex ~ |log2(x)|; return precision at which
    1178             :  * log(x) must be computed to evaluate x^n */
    1179             : long
    1180      182141 : powcx_prec(long ex, GEN n, long prec)
    1181             : {
    1182      182141 :   GEN a = gel(n,1), b = gel(n,2);
    1183      182141 :   long e = (ex < 2)? 0: expu(ex);
    1184      182141 :   e += gexpo_safe(is_rational_t(typ(a))? b: n);
    1185      182141 :   return e > 2? prec + nbits2extraprec(e): prec;
    1186             : }
    1187             : GEN
    1188      266668 : powcx(GEN x, GEN logx, GEN n, long prec)
    1189             : {
    1190      266668 :   GEN sxb, cxb, xa, a = gel(n,1), xb = gmul(gel(n,2), logx);
    1191      266668 :   long sh, p = realprec(logx);
    1192      266668 :   switch(typ(a))
    1193             :   {
    1194       49498 :     case t_INT: xa = powgi(x, a); break;
    1195      127974 :     case t_FRAC: xa = powfrac(x, a, prec);
    1196      127974 :                  if (xa) break;
    1197             :     default:
    1198       89203 :       xa = modlog2(gmul(gel(n,1), logx), &sh);
    1199       89203 :       if (!xa) xa = real2n(sh, prec);
    1200             :       else
    1201             :       {
    1202       89203 :         if (signe(xa) && realprec(xa) > prec) setprec(xa, prec);
    1203       89203 :         xa = mpexp(xa); shiftr_inplace(xa, sh);
    1204             :       }
    1205             :   }
    1206      266668 :   if (typ(xb) != t_REAL) return xa;
    1207      266668 :   if (gexpo(xb) > 30)
    1208             :   {
    1209           0 :     GEN q, P = Pi2n(-2, p), z = addrr(xb,P); /* = x + Pi/4 */
    1210           0 :     shiftr_inplace(P, 1);
    1211           0 :     q = floorr(divrr(z, P)); /* round ( x / (Pi/2) ) */
    1212           0 :     xb = subrr(xb, mulir(q, P)); /* x mod Pi/2  */
    1213           0 :     sh = Mod4(q);
    1214             :   }
    1215             :   else
    1216             :   {
    1217      266668 :     long q = floor(rtodbl(xb) / (M_PI/2) + 0.5);
    1218      266668 :     if (q) xb = subrr(xb, mulsr(q, Pi2n(-1,p))); /* x mod Pi/2  */
    1219      266668 :     sh = q & 3;
    1220             :   }
    1221      266668 :   if (signe(xb) && realprec(xb) > prec) setprec(xb, prec);
    1222      266668 :   mpsincos(xb, &sxb, &cxb);
    1223      266668 :   return gmul(xa, mulcxpowIs(mkcomplex(cxb, sxb), sh));
    1224             : }
    1225             : 
    1226             : GEN
    1227    20162587 : gpow(GEN x, GEN n, long prec)
    1228             : {
    1229    20162587 :   long prec0, i, lx, tx, tn = typ(n);
    1230             :   pari_sp av;
    1231             :   GEN y;
    1232             : 
    1233    20162587 :   if (tn == t_INT) return powgi(x,n);
    1234     5343323 :   tx = typ(x);
    1235     5343323 :   if (is_matvec_t(tx))
    1236             :   {
    1237          49 :     y = cgetg_copy(x, &lx);
    1238         133 :     for (i=1; i<lx; i++) gel(y,i) = gpow(gel(x,i),n,prec);
    1239          49 :     return y;
    1240             :   }
    1241     5343329 :   av = avma;
    1242     5343329 :   switch (tx)
    1243             :   {
    1244          28 :     case t_POL: case t_RFRAC: x = toser_i(x); /* fall through */
    1245        7560 :     case t_SER:
    1246        7560 :       if (tn == t_FRAC) return gerepileupto(av, ser_powfrac(x, n, prec));
    1247         140 :       if (valser(x))
    1248          21 :         pari_err_DOMAIN("gpow [irrational exponent]",
    1249             :                         "valuation", "!=", gen_0, x);
    1250         119 :       if (lg(x) == 2) return gerepilecopy(av, x); /* O(1) */
    1251         112 :       return gerepileupto(av, ser_pow(x, n, prec));
    1252             :   }
    1253     5335770 :   if (gequal0(x)) return gpow0(x, n, prec);
    1254     5335721 :   if (tn == t_FRAC)
    1255             :   {
    1256     5005842 :     GEN p, z, a = gel(n,1), d = gel(n,2);
    1257     5005842 :     switch (tx)
    1258             :     {
    1259     1474004 :     case t_INT:
    1260     1474004 :       if (signe(x) < 0)
    1261             :       {
    1262          42 :         if (equaliu(d, 2) && Z_issquareall(negi(x), &z))
    1263             :         {
    1264          21 :           z = powgi(z, a);
    1265          21 :           if (Mod4(a) == 3) z = gneg(z);
    1266     5001712 :           return gerepilecopy(av, mkcomplex(gen_0, z));
    1267             :         }
    1268          21 :         break;
    1269             :       }
    1270     1473962 :       if (ispower(x, d, &z)) return powgi(z, a);
    1271     1472398 :       break;
    1272       69827 :     case t_FRAC:
    1273       69827 :       if (signe(gel(x,1)) < 0)
    1274             :       {
    1275          28 :         if (equaliu(d, 2) && ispower(absfrac(x), d, &z))
    1276           7 :           return gerepilecopy(av, mkcomplex(gen_0, powgi(z, a)));
    1277          21 :         break;
    1278             :       }
    1279       69799 :       if (ispower(x, d, &z)) return powgi(z, a);
    1280       68427 :       break;
    1281             : 
    1282          21 :     case t_INTMOD:
    1283          21 :       p = gel(x,1);
    1284          21 :       if (!BPSW_psp(p)) pari_err_PRIME("gpow",p);
    1285          14 :       y = cgetg(3,t_INTMOD); gel(y,1) = icopy(p);
    1286          14 :       av = avma;
    1287          14 :       z = Fp_sqrtn(gel(x,2), d, p, NULL);
    1288          14 :       if (!z) pari_err_SQRTN("gpow",x);
    1289           7 :       gel(y,2) = gerepileuptoint(av, Fp_pow(z, a, p));
    1290           7 :       return y;
    1291             : 
    1292          14 :     case t_PADIC:
    1293          14 :       z = Qp_sqrtn(x, d, NULL); if (!z) pari_err_SQRTN("gpow",x);
    1294           7 :       return gerepileupto(av, powgi(z, a));
    1295             : 
    1296          21 :     case t_FFELT:
    1297          21 :       return gerepileupto(av,FF_pow(FF_sqrtn(x,d,NULL),a));
    1298             :     }
    1299     5002822 :     z = powfrac(x, n, prec);
    1300     5002888 :     if (z) return gerepileupto(av, z);
    1301             :   }
    1302      333893 :   if (tn == t_COMPLEX && is_real_t(typ(x)) && gsigne(x) > 0)
    1303             :   {
    1304      171403 :     long p = powcx_prec(fabs(dbllog2(x)), n, prec);
    1305      171403 :     return gerepileupto(av, powcx(x, glog(x, p), n, prec));
    1306             :   }
    1307      162490 :   if (tn == t_PADIC) x = gcvtop(x, gel(n,2), precp(n));
    1308      162490 :   i = precision(n);
    1309      162491 :   if (i) prec = i;
    1310      162491 :   prec0 = prec;
    1311      162491 :   if (!gprecision(x))
    1312             :   {
    1313       38647 :     long e = gexpo_safe(n); /* avoided if n = 0 or gexpo not defined */
    1314       38647 :     if (e > 2) prec += nbits2extraprec(e);
    1315             :   }
    1316      162491 :   y = gmul(n, glog(x,prec));
    1317      162463 :   y = gexp(y,prec);
    1318      162463 :   if (prec0 == prec) return gerepileupto(av, y);
    1319       29246 :   return gerepilecopy(av, gprec_wtrunc(y,prec0));
    1320             : }
    1321             : GEN
    1322       10227 : powPis(GEN s, long prec)
    1323             : {
    1324       10227 :   pari_sp av = avma;
    1325             :   GEN x;
    1326       10227 :   if (typ(s) != t_COMPLEX) return gpow(mppi(prec), s, prec);
    1327         441 :   x = mppi(powcx_prec(1, s, prec));
    1328         441 :   return gerepileupto(av, powcx(x, logr_abs(x), s, prec));
    1329             : }
    1330             : GEN
    1331        7868 : pow2Pis(GEN s, long prec)
    1332             : {
    1333        7868 :   pari_sp av = avma;
    1334             :   GEN x;
    1335        7868 :   if (typ(s) != t_COMPLEX) return gpow(Pi2n(1,prec), s, prec);
    1336        1876 :   x = Pi2n(1, powcx_prec(2, s, prec));
    1337        1876 :   return gerepileupto(av, powcx(x, logr_abs(x), s, prec));
    1338             : }
    1339             : 
    1340             : GEN
    1341      199881 : gpowers0(GEN x, long n, GEN x0)
    1342             : {
    1343             :   long i, l;
    1344             :   GEN V;
    1345      199881 :   if (!x0) return gpowers(x,n);
    1346      185395 :   if (n < 0) return cgetg(1,t_VEC);
    1347      185395 :   l = n+2; V = cgetg(l, t_VEC); gel(V,1) = gcopy(x0);
    1348     7376856 :   for (i = 2; i < l; i++) gel(V,i) = gmul(gel(V,i-1),x);
    1349      185385 :   return V;
    1350             : }
    1351             : 
    1352             : GEN
    1353      331935 : gpowers(GEN x, long n)
    1354             : {
    1355      331935 :   if (n < 0) return cgetg(1,t_VEC);
    1356      331928 :   return gen_powers(x, n, 0, (void*)x, &_sqr, &_mul, &_one);
    1357             : }
    1358             : 
    1359             : /* return [q^1,q^4,...,q^{n^2}] */
    1360             : GEN
    1361       37170 : gsqrpowers(GEN q, long n)
    1362             : {
    1363       37170 :   pari_sp av = avma;
    1364       37170 :   GEN L = gpowers0(gsqr(q), n, q); /* L[i] = q^(2i - 1), i <= n+1 */
    1365       37170 :   GEN v = cgetg(n+1, t_VEC);
    1366             :   long i;
    1367       37170 :   gel(v, 1) = gcopy(q);
    1368     6711304 :   for (i = 2; i <= n ; ++i) gel(v, i) = q = gmul(q, gel(L,i)); /* q^(i^2) */
    1369       37170 :   return gerepileupto(av, v);
    1370             : }
    1371             : 
    1372             : /* 4 | N. returns a vector RU which contains exp(2*i*k*Pi/N), k=0..N-1 */
    1373             : static GEN
    1374      562843 : grootsof1_4(long N, long prec)
    1375             : {
    1376      562843 :   GEN z, RU = cgetg(N+1,t_COL), *v  = ((GEN*)RU) + 1;
    1377      562841 :   long i, N2 = (N>>1), N4 = (N>>2), N8 = (N>>3);
    1378             :   /* z^N2 = -1, z^N4 = I; if z^k = a+I*b, then z^(N4-k) = I*conj(z) = b+a*I */
    1379             : 
    1380      562841 :   v[0] = gen_1; v[1] = z = rootsof1u_cx(N, prec);
    1381      562846 :   if (odd(N4)) N8++;
    1382      669599 :   for (i=1; i<N8; i++)
    1383             :   {
    1384      106754 :     GEN t = v[i];
    1385      106754 :     v[i+1] = gmul(z, t);
    1386      106753 :     v[N4-i] = mkcomplex(gel(t,2), gel(t,1));
    1387             :   }
    1388     1645345 :   for (i=0; i<N4; i++) v[i+N4] = mulcxI(v[i]);
    1389     2727826 :   for (i=0; i<N2; i++) v[i+N2] = gneg(v[i]);
    1390      562832 :   return RU;
    1391             : }
    1392             : 
    1393             : /* as above, N arbitrary */
    1394             : GEN
    1395      694004 : grootsof1(long N, long prec)
    1396             : {
    1397             :   GEN z, RU, *v;
    1398             :   long i, k;
    1399             : 
    1400      694004 :   if (N <= 0) pari_err_DOMAIN("rootsof1", "N", "<=", gen_0, stoi(N));
    1401      693990 :   if ((N & 3) == 0) return grootsof1_4(N, prec);
    1402      131147 :   if (N <= 2) return N == 1? mkcol(gen_1): mkcol2(gen_1, gen_m1);
    1403       14056 :   k = (N+1)>>1;
    1404       14056 :   RU = cgetg(N+1,t_COL);
    1405       14056 :   v  = ((GEN*)RU) + 1;
    1406       14056 :   v[0] = gen_1; v[1] = z = rootsof1u_cx(N, prec);
    1407       74042 :   for (i=2; i<k; i++) v[i] = gmul(z, v[i-1]);
    1408       14056 :   if (!odd(N)) v[i++] = gen_m1; /*avoid loss of accuracy*/
    1409       88098 :   for (   ; i<N; i++) v[i] = gconj(v[N-i]);
    1410       14056 :   return RU;
    1411             : }
    1412             : 
    1413             : /********************************************************************/
    1414             : /**                                                                **/
    1415             : /**                        RACINE CARREE                           **/
    1416             : /**                                                                **/
    1417             : /********************************************************************/
    1418             : /* assume x unit, e = precp(x) */
    1419             : GEN
    1420      144690 : Z2_sqrt(GEN x, long e)
    1421             : {
    1422      144690 :   ulong r = signe(x)>=0?mod16(x):16-mod16(x);
    1423             :   GEN z;
    1424             :   long ez;
    1425             :   pari_sp av;
    1426             : 
    1427      144690 :   switch(e)
    1428             :   {
    1429           7 :     case 1: return gen_1;
    1430         161 :     case 2: return (r & 3UL) == 1? gen_1: NULL;
    1431          28 :     case 3: return (r & 7UL) == 1? gen_1: NULL;
    1432       71064 :     case 4: if (r == 1) return gen_1;
    1433       35133 :             else return (r == 9)? utoipos(3): NULL;
    1434       73430 :     default: if ((r&7UL) != 1) return NULL;
    1435             :   }
    1436       73430 :   av = avma; z = (r==1)? gen_1: utoipos(3);
    1437       73430 :   ez = 3; /* number of correct bits in z (compared to sqrt(x)) */
    1438             :   for(;;)
    1439       47978 :   {
    1440             :     GEN mod;
    1441      121408 :     ez = (ez<<1) - 1;
    1442      121408 :     if (ez > e) ez = e;
    1443      121408 :     mod = int2n(ez);
    1444      121408 :     z = addii(z, remi2n(mulii(x, Fp_inv(z,mod)), ez));
    1445      121408 :     z = shifti(z, -1); /* (z + x/z) / 2 */
    1446      121408 :     if (e == ez) return gerepileuptoint(av, z);
    1447       47978 :     if (ez < e) ez--;
    1448       47978 :     if (gc_needed(av,2))
    1449             :     {
    1450           0 :       if (DEBUGMEM > 1) pari_warn(warnmem,"Qp_sqrt");
    1451           0 :       z = gerepileuptoint(av,z);
    1452             :     }
    1453             :   }
    1454             : }
    1455             : 
    1456             : /* x unit defined modulo p^e, e > 0 */
    1457             : GEN
    1458        1897 : Qp_sqrt(GEN x)
    1459             : {
    1460        1897 :   long pp, e = valp(x);
    1461        1897 :   GEN z,y,mod, p = gel(x,2);
    1462             : 
    1463        1897 :   if (gequal0(x)) return zeropadic(p, (e+1) >> 1);
    1464        1883 :   if (e & 1) return NULL;
    1465             : 
    1466        1869 :   y = cgetg(5,t_PADIC);
    1467        1869 :   pp = precp(x);
    1468        1869 :   mod = gel(x,3);
    1469        1869 :   z   = gel(x,4); /* lift to t_INT */
    1470        1869 :   e >>= 1;
    1471        1869 :   z = Zp_sqrt(z, p, pp);
    1472        1869 :   if (!z) return NULL;
    1473        1806 :   if (absequaliu(p,2))
    1474             :   {
    1475         805 :     pp  = (pp <= 3) ? 1 : pp-1;
    1476         805 :     mod = int2n(pp);
    1477             :   }
    1478        1001 :   else mod = icopy(mod);
    1479        1806 :   y[1] = evalprecp(pp) | evalvalp(e);
    1480        1806 :   gel(y,2) = icopy(p);
    1481        1806 :   gel(y,3) = mod;
    1482        1806 :   gel(y,4) = z; return y;
    1483             : }
    1484             : 
    1485             : GEN
    1486         420 : Zn_sqrt(GEN d, GEN fn)
    1487             : {
    1488         420 :   pari_sp ltop = avma, btop;
    1489         420 :   GEN b = gen_0, m = gen_1;
    1490             :   long j, np;
    1491         420 :   if (typ(d) != t_INT) pari_err_TYPE("Zn_sqrt",d);
    1492         420 :   if (typ(fn) == t_INT)
    1493           0 :     fn = absZ_factor(fn);
    1494         420 :   else if (!is_Z_factorpos(fn))
    1495           0 :     pari_err_TYPE("Zn_sqrt",fn);
    1496         420 :   np = nbrows(fn);
    1497         420 :   btop = avma;
    1498        1680 :   for (j = 1; j <= np; ++j)
    1499             :   {
    1500             :     GEN  bp, mp, pr, r;
    1501        1260 :     GEN  p = gcoeff(fn, j, 1);
    1502        1260 :     long e = itos(gcoeff(fn, j, 2));
    1503        1260 :     long v = Z_pvalrem(d,p,&r);
    1504        1260 :     if (v >= e) bp =gen_0;
    1505             :     else
    1506             :     {
    1507        1134 :       if (odd(v)) return NULL;
    1508        1134 :       bp = Zp_sqrt(r, p, e-v);
    1509        1134 :       if (!bp)    return NULL;
    1510        1134 :       if (v) bp = mulii(bp, powiu(p, v>>1L));
    1511             :     }
    1512        1260 :     mp = powiu(p, e);
    1513        1260 :     pr = mulii(m, mp);
    1514        1260 :     b = Z_chinese_coprime(b, bp, m, mp, pr);
    1515        1260 :     m = pr;
    1516        1260 :     if (gc_needed(btop, 1))
    1517           0 :       gerepileall(btop, 2, &b, &m);
    1518             :   }
    1519         420 :   return gerepileupto(ltop, b);
    1520             : }
    1521             : 
    1522             : static GEN
    1523       18669 : sqrt_ser(GEN b, long prec)
    1524             : {
    1525       18669 :   long e = valser(b), vx = varn(b), lx, lold, j;
    1526             :   ulong mask;
    1527             :   GEN a, x, lta, ltx;
    1528             : 
    1529       18669 :   if (!signe(b)) return zeroser(vx, e>>1);
    1530       18669 :   a = leafcopy(b);
    1531       18669 :   x = cgetg_copy(b, &lx);
    1532       18669 :   if (e & 1)
    1533          14 :     pari_err_DOMAIN("sqrtn", "valuation", "!=", mkintmod(gen_0, gen_2), b);
    1534       18655 :   a[1] = x[1] = evalsigne(1) | evalvarn(0) | _evalvalser(0);
    1535       18655 :   lta = gel(a,2);
    1536       18655 :   if (gequal1(lta)) ltx = lta;
    1537       14833 :   else if (!issquareall(lta,&ltx)) ltx = gsqrt(lta,prec);
    1538       18648 :   gel(x,2) = ltx;
    1539      315399 :   for (j = 3; j < lx; j++) gel(x,j) = gen_0;
    1540       18648 :   setlg(x,3);
    1541       18648 :   mask = quadratic_prec_mask(lx - 2);
    1542       18648 :   lold = 1;
    1543       96295 :   while (mask > 1)
    1544             :   {
    1545       77647 :     GEN y, x2 = gmul2n(x,1);
    1546       77647 :     long l = lold << 1, lx;
    1547             : 
    1548       77647 :     if (mask & 1) l--;
    1549       77647 :     mask >>= 1;
    1550       77647 :     setlg(a, l + 2);
    1551       77647 :     setlg(x, l + 2);
    1552       77647 :     y = sqr_ser_part(x, lold, l-1) - lold;
    1553      374398 :     for (j = lold+2; j < l+2; j++) gel(y,j) = gsub(gel(y,j), gel(a,j));
    1554       77647 :     y += lold; setvalser(y, lold);
    1555       77647 :     y = normalizeser(y);
    1556       77647 :     y = gsub(x, gdiv(y, x2)); /* = gmul2n(gsub(x, gdiv(a,x)), -1); */
    1557       77647 :     lx = minss(l+2, lg(y));
    1558      374391 :     for (j = lold+2; j < lx; j++) gel(x,j) = gel(y,j);
    1559       77647 :     lold = l;
    1560             :   }
    1561       18648 :   x[1] = evalsigne(1) | evalvarn(vx) | _evalvalser(e >> 1);
    1562       18648 :   return x;
    1563             : }
    1564             : 
    1565             : GEN
    1566    49682102 : gsqrt(GEN x, long prec)
    1567             : {
    1568             :   pari_sp av;
    1569             :   GEN y;
    1570             : 
    1571    49682102 :   switch(typ(x))
    1572             :   {
    1573      298247 :     case t_INT:
    1574      298247 :       if (!signe(x)) return real_0(prec); /* no loss of accuracy */
    1575      298177 :       x = itor(x,prec); /* fall through */
    1576    43870504 :     case t_REAL: return sqrtr(x);
    1577             : 
    1578          35 :     case t_INTMOD:
    1579             :     {
    1580          35 :       GEN p = gel(x,1), a;
    1581          35 :       y = cgetg(3,t_INTMOD); gel(y,1) = icopy(p);
    1582          35 :       a = Fp_sqrt(gel(x,2),p);
    1583          21 :       if (!a)
    1584             :       {
    1585           7 :         if (!BPSW_psp(p)) pari_err_PRIME("sqrt [modulus]",p);
    1586           7 :         pari_err_SQRTN("gsqrt",x);
    1587             :       }
    1588          14 :       gel(y,2) = a; return y;
    1589             :     }
    1590             : 
    1591     5547143 :     case t_COMPLEX:
    1592             :     { /* (u+iv)^2 = a+ib <=> u^2+v^2 = sqrt(a^2+b^2), u^2-v^2=a, 2uv=b */
    1593     5547143 :       GEN a = gel(x,1), b = gel(x,2), r, u, v;
    1594     5547143 :       if (isrationalzero(b)) return gsqrt(a, prec);
    1595     5547143 :       y = cgetg(3,t_COMPLEX); av = avma;
    1596             : 
    1597     5547143 :       r = cxnorm(x);
    1598     5547144 :       if (typ(r) == t_INTMOD || typ(r) == t_PADIC)
    1599           0 :         pari_err_IMPL("sqrt(complex of t_INTMODs)");
    1600     5547144 :       r = gsqrt(r, prec); /* t_REAL, |a+Ib| */
    1601     5547147 :       if (!signe(r))
    1602          67 :         u = v = gerepileuptoleaf(av, sqrtr(r));
    1603     5547080 :       else if (gsigne(a) < 0)
    1604             :       {
    1605             :         /* v > 0 since r > 0, a < 0, rounding errors can't make the sum of two
    1606             :          * positive numbers = 0 */
    1607      136981 :         v = sqrtr( gmul2n(gsub(r,a), -1) );
    1608      136980 :         if (gsigne(b) < 0) togglesign(v);
    1609      136980 :         v = gerepileuptoleaf(av, v); av = avma;
    1610             :         /* v = 0 is impossible */
    1611      136981 :         u = gerepileuptoleaf(av, gdiv(b, shiftr(v,1)));
    1612             :       } else {
    1613     5410098 :         u = sqrtr( gmul2n(gadd(r,a), -1) );
    1614     5410100 :         u = gerepileuptoleaf(av, u); av = avma;
    1615     5410100 :         if (!signe(u)) /* possible if a = 0.0, e.g. sqrt(0.e-10+1e-10*I) */
    1616           7 :           v = u;
    1617             :         else
    1618     5410093 :           v = gerepileuptoleaf(av, gdiv(b, shiftr(u,1)));
    1619             :       }
    1620     5547145 :       gel(y,1) = u;
    1621     5547145 :       gel(y,2) = v; return y;
    1622             :     }
    1623             : 
    1624          63 :     case t_PADIC:
    1625          63 :       y = Qp_sqrt(x);
    1626          63 :       if (!y) pari_err_SQRTN("Qp_sqrt",x);
    1627          42 :       return y;
    1628             : 
    1629         161 :     case t_FFELT: return FF_sqrt(x);
    1630             : 
    1631      264126 :     default:
    1632      264126 :       av = avma; if (!(y = toser_i(x))) break;
    1633       18669 :       return gerepilecopy(av, sqrt_ser(y, prec));
    1634             :   }
    1635      245457 :   return trans_eval("sqrt",gsqrt,x,prec);
    1636             : }
    1637             : /********************************************************************/
    1638             : /**                                                                **/
    1639             : /**                          N-th ROOT                             **/
    1640             : /**                                                                **/
    1641             : /********************************************************************/
    1642             : 
    1643             : static GEN
    1644      303713 : Z_to_padic(GEN a, GEN p, long e)
    1645             : {
    1646      303713 :   if (signe(a)==0)
    1647        1036 :     return zeropadic(p, e);
    1648             :   else
    1649             :   {
    1650      302677 :     GEN z = cgetg(5, t_PADIC);
    1651      302678 :     long v = Z_pvalrem(a, p, &a), d = e - v;
    1652      302678 :     z[1] = evalprecp(d) | evalvalp(v);
    1653      302678 :     gel(z,2) = icopy(p);
    1654      302678 :     gel(z,3) = powiu(p, d);
    1655      302681 :     gel(z,4) = a;
    1656      302681 :     return z;
    1657             :   }
    1658             : }
    1659             : 
    1660             : GEN
    1661      196485 : Qp_log(GEN x)
    1662             : {
    1663      196485 :   pari_sp av = avma;
    1664      196485 :   GEN y, p = gel(x,2), a = gel(x,4);
    1665      196485 :   long e = precp(x);
    1666             : 
    1667      196485 :   if (!signe(a)) pari_err_DOMAIN("Qp_log", "argument", "=", gen_0, x);
    1668      196464 :   if (absequaliu(p,2) || equali1(modii(a, p)))
    1669       76986 :     y = Zp_log(a, p, e);
    1670             :   else
    1671             :   { /* compute log(x^(p-1)) / (p-1) */
    1672      119478 :     GEN q = gel(x,3), t = subiu(p, 1);
    1673      119478 :     a = Fp_pow(a, t, q);
    1674      119478 :     y = Fp_mul(Zp_log(a, p, e), diviiexact(subsi(1, q), t), q);
    1675             :   }
    1676      196463 :   return gerepileupto(av, Z_to_padic(y, p, e));
    1677             : }
    1678             : 
    1679             : static GEN Qp_exp_safe(GEN x);
    1680             : 
    1681             : /*compute the p^e th root of x p-adic, assume x != 0 */
    1682             : static GEN
    1683         854 : Qp_sqrtn_ram(GEN x, long e)
    1684             : {
    1685         854 :   pari_sp ltop=avma;
    1686         854 :   GEN a, p = gel(x,2), n = powiu(p,e);
    1687         854 :   long v = valp(x), va;
    1688         854 :   if (v)
    1689             :   {
    1690             :     long z;
    1691         161 :     v = sdivsi_rem(v, n, &z);
    1692         161 :     if (z) return NULL;
    1693          91 :     x = leafcopy(x);
    1694          91 :     setvalp(x,0);
    1695             :   }
    1696             :   /*If p = 2, -1 is a root of 1 in U1: need extra check*/
    1697         784 :   if (absequaliu(p, 2) && mod8(gel(x,4)) != 1) return NULL;
    1698         749 :   a = Qp_log(x);
    1699         749 :   va = valp(a) - e;
    1700         749 :   if (va <= 0)
    1701             :   {
    1702         287 :     if (signe(gel(a,4))) return NULL;
    1703             :     /* all accuracy lost */
    1704         119 :     a = cvtop(remii(gel(x,4),p), p, 1);
    1705             :   }
    1706             :   else
    1707             :   {
    1708         462 :     setvalp(a, va); /* divide by p^e */
    1709         462 :     a = Qp_exp_safe(a);
    1710         462 :     if (!a) return NULL;
    1711             :     /* n=p^e and a^n=z*x where z is a (p-1)th-root of 1.
    1712             :      * Since z^n=z, we have (a/z)^n = x. */
    1713         462 :     a = gdiv(x, powgi(a,subiu(n,1))); /* = a/z = x/a^(n-1)*/
    1714         462 :     if (v) setvalp(a,v);
    1715             :   }
    1716         581 :   return gerepileupto(ltop,a);
    1717             : }
    1718             : 
    1719             : /*compute the nth root of x p-adic p prime with n*/
    1720             : static GEN
    1721        2037 : Qp_sqrtn_unram(GEN x, GEN n, GEN *zetan)
    1722             : {
    1723             :   pari_sp av;
    1724        2037 :   GEN Z, a, r, p = gel(x,2);
    1725        2037 :   long v = valp(x);
    1726        2037 :   if (v)
    1727             :   {
    1728             :     long z;
    1729          84 :     v = sdivsi_rem(v,n,&z);
    1730          84 :     if (z) return NULL;
    1731             :   }
    1732        2030 :   r = cgetp(x); setvalp(r,v);
    1733        2030 :   Z = NULL; /* -Wall */
    1734        2030 :   if (zetan) Z = cgetp(x);
    1735        2030 :   av = avma; a = Fp_sqrtn(gel(x,4), n, p, zetan);
    1736        2030 :   if (!a) return NULL;
    1737        2016 :   affii(Zp_sqrtnlift(gel(x,4), n, a, p, precp(x)), gel(r,4));
    1738        2016 :   if (zetan)
    1739             :   {
    1740          14 :     affii(Zp_sqrtnlift(gen_1, n, *zetan, p, precp(x)), gel(Z,4));
    1741          14 :     *zetan = Z;
    1742             :   }
    1743        2016 :   return gc_const(av,r);
    1744             : }
    1745             : 
    1746             : GEN
    1747        2604 : Qp_sqrtn(GEN x, GEN n, GEN *zetan)
    1748             : {
    1749             :   pari_sp av, tetpil;
    1750             :   GEN q, p;
    1751             :   long e;
    1752        2604 :   if (absequaliu(n, 2))
    1753             :   {
    1754          70 :     if (zetan) *zetan = gen_m1;
    1755          70 :     if (signe(n) < 0) x = ginv(x);
    1756          63 :     return Qp_sqrt(x);
    1757             :   }
    1758        2534 :   av = avma; p = gel(x,2);
    1759        2534 :   if (!signe(gel(x,4)))
    1760             :   {
    1761         203 :     if (signe(n) < 0) pari_err_INV("Qp_sqrtn", x);
    1762         203 :     q = divii(addis(n, valp(x)-1), n);
    1763         203 :     if (zetan) *zetan = gen_1;
    1764         203 :     set_avma(av); return zeropadic(p, itos(q));
    1765             :   }
    1766             :   /* treat the ramified part using logarithms */
    1767        2331 :   e = Z_pvalrem(n, p, &q);
    1768        2331 :   if (e) { x = Qp_sqrtn_ram(x,e); if (!x) return NULL; }
    1769        2058 :   if (is_pm1(q))
    1770             :   { /* finished */
    1771          21 :     if (signe(q) < 0) x = ginv(x);
    1772          21 :     x = gerepileupto(av, x);
    1773          21 :     if (zetan)
    1774          28 :       *zetan = (e && absequaliu(p, 2))? gen_m1 /*-1 in Q_2*/
    1775          28 :                                    : gen_1;
    1776          21 :     return x;
    1777             :   }
    1778        2037 :   tetpil = avma;
    1779             :   /* use hensel lift for unramified case */
    1780        2037 :   x = Qp_sqrtn_unram(x, q, zetan);
    1781        2037 :   if (!x) return NULL;
    1782        2016 :   if (zetan)
    1783             :   {
    1784             :     GEN *gptr[2];
    1785          14 :     if (e && absequaliu(p, 2))/*-1 in Q_2*/
    1786             :     {
    1787           7 :       tetpil = avma; x = gcopy(x); *zetan = gneg(*zetan);
    1788             :     }
    1789          14 :     gptr[0] = &x; gptr[1] = zetan;
    1790          14 :     gerepilemanysp(av,tetpil,gptr,2);
    1791          14 :     return x;
    1792             :   }
    1793        2002 :   return gerepile(av,tetpil,x);
    1794             : }
    1795             : 
    1796             : GEN
    1797       23626 : sqrtnint(GEN a, long n)
    1798             : {
    1799       23626 :   pari_sp av = avma;
    1800             :   GEN x, b, q;
    1801             :   long s, k, e;
    1802       23626 :   const ulong nm1 = n - 1;
    1803       23626 :   if (n == 2) return sqrtint(a);
    1804       19643 :   if (typ(a) != t_INT)
    1805             :   {
    1806          35 :     if (typ(a) == t_REAL)
    1807             :     {
    1808             :       long e;
    1809          14 :       switch(signe(a))
    1810             :       {
    1811           0 :         case 0: return gen_0;
    1812           7 :         case -1: pari_err_DOMAIN("sqrtnint", "argument", "<", gen_0,a);
    1813             :       }
    1814           7 :       e = expo(a); if (e < 0) return gen_0;
    1815           7 :       if (nbits2lg(e+1) > lg(a))
    1816           0 :         a = floorr(sqrtnr(a,n)); /* try to avoid precision loss in truncation */
    1817             :       else
    1818           7 :         a = sqrtnint(truncr(a),n);
    1819             :     }
    1820             :     else
    1821             :     {
    1822          21 :       GEN b = gfloor(a);
    1823          21 :       if (typ(b) != t_INT) pari_err_TYPE("sqrtint",a);
    1824          14 :       if (signe(b) < 0) pari_err_DOMAIN("sqrtnint", "argument", "<", gen_0,b);
    1825           7 :       a = sqrtnint(b, n);
    1826             :     }
    1827          14 :     return gerepileuptoint(av, a);
    1828             :   }
    1829       19608 :   if (n <= 0) pari_err_DOMAIN("sqrtnint", "n", "<=", gen_0, stoi(n));
    1830       19601 :   if (n == 1) return icopy(a);
    1831       17459 :   s = signe(a);
    1832       17459 :   if (s < 0) pari_err_DOMAIN("sqrtnint", "x", "<", gen_0, a);
    1833       17459 :   if (!s) return gen_0;
    1834       17382 :   if (lgefint(a) == 3) return utoi(usqrtn(itou(a), n));
    1835       11606 :   e = expi(a); k = e/(2*n);
    1836       11606 :   if (k == 0)
    1837             :   {
    1838             :     long flag;
    1839         291 :     if (n > e) return gc_const(av, gen_1);
    1840         291 :     flag = cmpii(a, powuu(3, n)); set_avma(av);
    1841         291 :     return (flag < 0) ? gen_2: stoi(3);
    1842             :   }
    1843       11315 :   if (e < n*BITS_IN_LONG - 1)
    1844             :   {
    1845             :     ulong xs, qs;
    1846        4181 :     b = itor(a, (2*e < n*BITS_IN_LONG)? DEFAULTPREC: MEDDEFAULTPREC);
    1847        4181 :     x = mpexp(divru(logr_abs(b), n));
    1848        4181 :     xs = itou(floorr(x)) + 1; /* >= a^(1/n) */
    1849             :     for(;;) {
    1850        8184 :       q = divii(a, powuu(xs, nm1));
    1851        8184 :       if (lgefint(q) > 3) break;
    1852        8177 :       qs = itou(q); if (qs >= xs) break;
    1853        4003 :       xs -= (xs - qs + nm1)/n;
    1854             :     }
    1855        4181 :     return utoi(xs);
    1856             :   }
    1857        7134 :   b = addui(1, shifti(a, -n*k));
    1858        7134 :   x = shifti(addui(1, sqrtnint(b, n)), k);
    1859        7134 :   q = divii(a, powiu(x, nm1));
    1860       15994 :   while (cmpii(q, x) < 0) /* a priori one iteration, no GC necessary */
    1861             :   {
    1862        8860 :     x = subii(x, divis(addui(nm1, subii(x, q)), n));
    1863        8860 :     q = divii(a, powiu(x, nm1));
    1864             :   }
    1865        7134 :   return gerepileuptoleaf(av, x);
    1866             : }
    1867             : 
    1868             : ulong
    1869        7659 : usqrtn(ulong a, ulong n)
    1870             : {
    1871             :   ulong x, s, q;
    1872        7659 :   const ulong nm1 = n - 1;
    1873        7659 :   if (!n) pari_err_DOMAIN("sqrtnint", "n", "=", gen_0, utoi(n));
    1874        7659 :   if (n == 1 || a == 0) return a;
    1875        7659 :   s = 1 + expu(a)/n; x = 1UL << s;
    1876        7659 :   q = (nm1*s >= BITS_IN_LONG)? 0: a >> (nm1*s);
    1877       19624 :   while (q < x) {
    1878             :     ulong X;
    1879       11965 :     x -= (x - q + nm1)/n;
    1880       11965 :     X = upowuu(x, nm1);
    1881       11965 :     q = X? a/X: 0;
    1882             :   }
    1883        7659 :   return x;
    1884             : }
    1885             : 
    1886             : static ulong
    1887     1661338 : cubic_prec_mask(long n)
    1888             : {
    1889     1661338 :   long a = n, i;
    1890     1661338 :   ulong mask = 0;
    1891     1661338 :   for(i = 1;; i++, mask *= 3)
    1892     7891255 :   {
    1893     9552593 :     long c = a%3;
    1894     9552593 :     if (c) mask += 3 - c;
    1895     9552593 :     a = (a+2)/3;
    1896     9552593 :     if (a==1) return mask + upowuu(3, i);
    1897             :   }
    1898             : }
    1899             : 
    1900             : /* cubic Newton iteration, |a|^(1/n), assuming a != 0 */
    1901             : GEN
    1902     2483387 : sqrtnr_abs(GEN a, long n)
    1903             : {
    1904             :   pari_sp av;
    1905             :   GEN x, b;
    1906             :   long eextra, eold, n1, n2, prec, B, v;
    1907             :   ulong mask;
    1908             : 
    1909     2483387 :   if (n == 1) return mpabs(a);
    1910     2482743 :   if (n == 2) return sqrtr_abs(a);
    1911             : 
    1912     2188163 :   prec = realprec(a); v = expo(a) / n; av = avma;
    1913     2188163 :   if (v) a = shiftr(a, -n*v);
    1914     2188171 :   b = rtor(a, DEFAULTPREC);
    1915     2188194 :   x = mpexp(divru(logr_abs(b), n));
    1916     2188201 :   if (prec == DEFAULTPREC)
    1917             :   {
    1918      564264 :     if (v) shiftr_inplace(x, v);
    1919      564263 :     return gerepileuptoleaf(av, x);
    1920             :   }
    1921     1623937 :   n1 = n+1;
    1922     1623937 :   n2 = 2*n;
    1923     1623937 :   B = prec2nbits(prec);
    1924     1623937 :   eextra = expu(n)-1;
    1925     1623937 :   mask = cubic_prec_mask(B + 63);
    1926     1623937 :   eold = 1;
    1927             :   for(;;)
    1928     6473032 :   { /* reach 64 */
    1929     8096969 :     long enew = eold * 3;
    1930     8096969 :     enew -= mask % 3;
    1931     8096969 :     if (enew > 64) break; /* back up one step */
    1932     6473032 :     mask /= 3;
    1933     6473032 :     eold = enew;
    1934             :   }
    1935             :   for(;;)
    1936     1255672 :   {
    1937     2879609 :     long pr, enew = eold * 3;
    1938             :     GEN y, z;
    1939     2879609 :     enew -= mask % 3;
    1940     2879609 :     mask /= 3;
    1941     2879609 :     pr = nbits2prec(enew + eextra);
    1942     2879609 :     b = rtor(a, pr); setsigne(b,1);
    1943     2879609 :     x = rtor(x, pr);
    1944     2879609 :     y = subrr(powru(x, n), b);
    1945     2879609 :     z = divrr(y, addrr(mulur(n1, y), mulur(n2, b)));
    1946     2879609 :     shiftr_inplace(z,1);
    1947     2879609 :     x = mulrr(x, subsr(1,z));
    1948     2879609 :     if (mask == 1)
    1949             :     {
    1950     1623937 :       if (v) shiftr_inplace(x, v);
    1951     1623937 :       return gerepileuptoleaf(av, gprec_wtrunc(x,prec));
    1952             :     }
    1953     1255672 :     eold = enew;
    1954             :   }
    1955             : }
    1956             : 
    1957             : static void
    1958       53872 : shiftc_inplace(GEN z, long d)
    1959             : {
    1960       53872 :   shiftr_inplace(gel(z,1), d);
    1961       53872 :   shiftr_inplace(gel(z,2), d);
    1962       53872 : }
    1963             : 
    1964             : /* exp(2*Pi*I/n), same iteration as sqrtnr_abs, different initial point */
    1965             : static GEN
    1966      511767 : sqrtnof1(ulong n, long prec)
    1967             : {
    1968             :   pari_sp av;
    1969             :   GEN x;
    1970             :   long eold, n1, n2, B;
    1971             :   ulong mask;
    1972             : 
    1973      511767 :   B = prec2nbits(prec);
    1974      511767 :   n1 = n+1;
    1975      511767 :   n2 = 2*n; av = avma;
    1976             : 
    1977      511767 :   x = expIr(divru(Pi2n(1, LOWDEFAULTPREC), n));
    1978      511767 :   if (prec == LOWDEFAULTPREC) return gerepileupto(av, x);
    1979       37401 :   mask = cubic_prec_mask(B + BITS_IN_LONG-1);
    1980       37401 :   eold = 1;
    1981             :   for(;;)
    1982      146080 :   { /* reach BITS_IN_LONG */
    1983      183481 :     long enew = eold * 3;
    1984      183481 :     enew -= mask % 3;
    1985      183481 :     if (enew > BITS_IN_LONG) break; /* back up one step */
    1986      146080 :     mask /= 3;
    1987      146080 :     eold = enew;
    1988             :   }
    1989             :   for(;;)
    1990       16471 :   {
    1991       53872 :     long pr, enew = eold * 3;
    1992             :     GEN y, z;
    1993       53872 :     enew -= mask % 3;
    1994       53872 :     mask /= 3;
    1995       53872 :     pr = nbits2prec(enew);
    1996       53872 :     x = cxtofp(x, pr);
    1997       53872 :     y = gsub(gpowgs(x, n), gen_1);
    1998       53872 :     z = gdiv(y, gaddgs(gmulsg(n1, y), n2));
    1999       53872 :     shiftc_inplace(z,1);
    2000       53872 :     x = gmul(x, gsubsg(1, z));
    2001       53872 :     if (mask == 1) return gerepilecopy(av, gprec_w(x,prec));
    2002       16471 :     eold = enew;
    2003             :   }
    2004             : }
    2005             : 
    2006             : /* exp(2iPi/d) */
    2007             : GEN
    2008     1240454 : rootsof1u_cx(ulong n, long prec)
    2009             : {
    2010     1240454 :   switch(n)
    2011             :   {
    2012       13006 :     case 1: return gen_1;
    2013        2884 :     case 2: return gen_m1;
    2014      257814 :     case 4: return gen_I();
    2015       10402 :     case 3: case 6: case 12:
    2016             :     {
    2017       10402 :       pari_sp av = avma;
    2018       10402 :       GEN a = (n == 3)? mkfrac(gen_m1,gen_2): ghalf;
    2019       10402 :       GEN sq3 = sqrtr_abs(utor(3, prec));
    2020       10402 :       shiftr_inplace(sq3, -1);
    2021       10402 :       a = (n == 12)? mkcomplex(sq3, a): mkcomplex(a, sq3);
    2022       10402 :       return gerepilecopy(av, a);
    2023             :     }
    2024      444587 :     case 8:
    2025             :     {
    2026      444587 :       pari_sp av = avma;
    2027      444587 :       GEN sq2 = sqrtr_abs(utor(2, prec));
    2028      444581 :       shiftr_inplace(sq2,-1);
    2029      444579 :       return gerepilecopy(av, mkcomplex(sq2, sq2));
    2030             :     }
    2031             :   }
    2032      511761 :   return sqrtnof1(n, prec);
    2033             : }
    2034             : /* e(a/b) */
    2035             : GEN
    2036       14154 : rootsof1q_cx(long a, long b, long prec)
    2037             : {
    2038       14154 :   long g = cgcd(a,b);
    2039             :   GEN z;
    2040       14154 :   if (g != 1) { a /= g; b /= g; }
    2041       14154 :   if (b < 0) { b = -b; a = -a; }
    2042       14154 :   z = rootsof1u_cx(b, prec);
    2043       14154 :   if (a < 0) { z = conj_i(z); a = -a; }
    2044       14154 :   return gpowgs(z, a);
    2045             : }
    2046             : 
    2047             : /* initializes powers of e(a/b) */
    2048             : GEN
    2049       14987 : rootsof1powinit(long a, long b, long prec)
    2050             : {
    2051       14987 :   long g = cgcd(a,b);
    2052       14987 :   if (g != 1) { a /= g; b /= g; }
    2053       14987 :   if (b < 0) { b = -b; a = -a; }
    2054       14987 :   a %= b; if (a < 0) a += b;
    2055       14987 :   return mkvec2(grootsof1(b,prec), mkvecsmall2(a,b));
    2056             : }
    2057             : /* T = rootsof1powinit(a,b); return  e(a/b)^c */
    2058             : GEN
    2059    12516441 : rootsof1pow(GEN T, long c)
    2060             : {
    2061    12516441 :   GEN vz = gel(T,1), ab = gel(T,2);
    2062    12516441 :   long a = ab[1], b = ab[2]; /* a >= 0, b > 0 */
    2063    12516441 :   c %= b; if (c < 0) c += b;
    2064    12516441 :   a = Fl_mul(a, c, b);
    2065    12516441 :   return gel(vz, a + 1);
    2066             : }
    2067             : 
    2068             : /* exp(2iPi/d), assume d a t_INT */
    2069             : GEN
    2070        4480 : rootsof1_cx(GEN d, long prec)
    2071             : {
    2072        4480 :   if (lgefint(d) == 3) return rootsof1u_cx((ulong)d[2], prec);
    2073           0 :   return expIr(divri(Pi2n(1,prec), d));
    2074             : }
    2075             : 
    2076             : GEN
    2077       12357 : gsqrtn(GEN x, GEN n, GEN *zetan, long prec)
    2078             : {
    2079             :   long i, lx, tx;
    2080             :   pari_sp av;
    2081             :   GEN y, z;
    2082       12357 :   if (typ(n)!=t_INT) pari_err_TYPE("sqrtn",n);
    2083       12357 :   if (!signe(n)) pari_err_DOMAIN("sqrtn", "n", "=", gen_0, n);
    2084       12357 :   if (is_pm1(n))
    2085             :   {
    2086          70 :     if (zetan) *zetan = gen_1;
    2087          70 :     return (signe(n) > 0)? gcopy(x): ginv(x);
    2088             :   }
    2089       12287 :   if (zetan) *zetan = gen_0;
    2090       12287 :   tx = typ(x);
    2091       12287 :   if (is_matvec_t(tx))
    2092             :   {
    2093           7 :     y = cgetg_copy(x, &lx);
    2094          21 :     for (i=1; i<lx; i++) gel(y,i) = gsqrtn(gel(x,i),n,NULL,prec);
    2095           7 :     return y;
    2096             :   }
    2097       12280 :   av = avma;
    2098       12280 :   switch(tx)
    2099             :   {
    2100         182 :   case t_INTMOD:
    2101             :     {
    2102         182 :       GEN p = gel(x,1), s;
    2103         182 :       z = gen_0;
    2104         182 :       y = cgetg(3,t_INTMOD);  gel(y,1) = icopy(p);
    2105         182 :       if (zetan) { z = cgetg(3,t_INTMOD); gel(z,1) = gel(y,1); }
    2106         182 :       s = Fp_sqrtn(gel(x,2),n,p,zetan);
    2107         161 :       if (!s) {
    2108          35 :         if (zetan) return gc_const(av,gen_0);
    2109          28 :         if (!BPSW_psp(p)) pari_err_PRIME("sqrtn [modulus]",p);
    2110          14 :         pari_err_SQRTN("gsqrtn",x);
    2111             :       }
    2112         126 :       gel(y,2) = s;
    2113         126 :       if (zetan) { gel(z,2) = *zetan; *zetan = z; }
    2114         126 :       return y;
    2115             :     }
    2116             : 
    2117          56 :   case t_PADIC:
    2118          56 :     y = Qp_sqrtn(x,n,zetan);
    2119          49 :     if (!y) {
    2120           7 :       if (zetan) return gen_0;
    2121           7 :       pari_err_SQRTN("gsqrtn",x);
    2122             :     }
    2123          42 :     return y;
    2124             : 
    2125         196 :   case t_FFELT: return FF_sqrtn(x,n,zetan);
    2126             : 
    2127       11384 :   case t_INT: case t_FRAC: case t_REAL: case t_COMPLEX:
    2128       11384 :     i = precision(x); if (i) prec = i;
    2129       11384 :     if (isint1(x))
    2130           7 :       y = real_1(prec);
    2131       11377 :     else if (gequal0(x))
    2132             :     {
    2133             :       long b;
    2134          21 :       if (signe(n) < 0) pari_err_INV("gsqrtn",x);
    2135          21 :       if (isinexactreal(x))
    2136          14 :         b = sdivsi(gexpo(x), n);
    2137             :       else
    2138           7 :         b = -prec2nbits(prec);
    2139          21 :       if (typ(x) == t_COMPLEX)
    2140             :       {
    2141           7 :         y = cgetg(3,t_COMPLEX);
    2142           7 :         gel(y,1) = gel(y,2) = real_0_bit(b);
    2143             :       }
    2144             :       else
    2145          14 :         y = real_0_bit(b);
    2146             :     }
    2147             :     else
    2148             :     {
    2149       11356 :       long nn = itos_or_0(n);
    2150       11356 :       if (tx == t_INT) { x = itor(x,prec); tx = t_REAL; }
    2151       11356 :       if (nn > 0 && tx == t_REAL && signe(x) > 0)
    2152        1980 :         y = sqrtnr(x, nn);
    2153             :       else
    2154        9376 :         y = gexp(gdiv(glog(x,prec), n), prec);
    2155       11356 :       y = gerepileupto(av, y);
    2156             :     }
    2157       11384 :     if (zetan) *zetan = rootsof1_cx(n, prec);
    2158       11384 :     return y;
    2159             : 
    2160           7 :   case t_QUAD:
    2161           7 :     return gsqrtn(quadtofp(x, prec), n, zetan, prec);
    2162             : 
    2163         455 :   default:
    2164         455 :     av = avma; if (!(y = toser_i(x))) break;
    2165         455 :     return gerepileupto(av, ser_powfrac(y, ginv(n), prec));
    2166             :   }
    2167           0 :   pari_err_TYPE("sqrtn",x);
    2168             :   return NULL;/* LCOV_EXCL_LINE */
    2169             : }
    2170             : 
    2171             : /********************************************************************/
    2172             : /**                                                                **/
    2173             : /**                             EXP(X) - 1                         **/
    2174             : /**                                                                **/
    2175             : /********************************************************************/
    2176             : /* exp(|x|) - 1, assume x != 0.
    2177             :  * For efficiency, x should be reduced mod log(2): if so, we have a < 0 */
    2178             : GEN
    2179    15711952 : exp1r_abs(GEN x)
    2180             : {
    2181    15711952 :   long l = realprec(x), a = expo(x), b = prec2nbits(l), L, i, n, m, B;
    2182             :   GEN y, p2, X;
    2183             :   pari_sp av;
    2184             :   double d;
    2185             : 
    2186    15711756 :   if (b + a <= 0) return mpabs(x);
    2187             : 
    2188    15698002 :   y = cgetr(l); av = avma;
    2189    15698057 :   B = b/3 + BITS_IN_LONG + (BITS_IN_LONG*BITS_IN_LONG)/ b;
    2190    15698057 :   d = a/2.; m = (long)(d + sqrt(d*d + B)); /* >= 0 */
    2191    15698057 :   if (m < (-a) * 0.1) m = 0; /* not worth it */
    2192             :  /* Multiplication is quadratic in this range (l is small, otherwise we
    2193             :   * use logAGM + Newton). Set Y = 2^(-e-a) x, compute truncated series
    2194             :   * sum_{k <= n} Y^k/k!: this costs roughly
    2195             :   *    m b^2 + sum_{k <= n} (k e + BITS_IN_LONG)^2
    2196             :   * bit operations with n ~ b/e, |x| <  2^(1+a), |Y| < 2^(1-e) , m = e+a and
    2197             :   * b bits of accuracy needed, so
    2198             :   *    B := (b / 3 + BITS_IN_LONG + BITS_IN_LONG^2 / b) ~ m(m-a)
    2199             :   * we want b ~ 3 m (m-a) or m~b+a hence
    2200             :   *     m = min( a/2 + sqrt(a^2/4 + B),  b + a )
    2201             :   * NB: e ~ (b/3)^(1/2) as b -> oo
    2202             :   *
    2203             :   * Truncate the sum at k = n (>= 1), the remainder is
    2204             :   *   sum_{k >= n+1} Y^k / k! < Y^(n+1) / (n+1)! (1-Y) < Y^(n+1) / n!
    2205             :   * We want Y^(n+1) / n! <= Y 2^-b, hence -n log_2 |Y| + log_2 n! >= b
    2206             :   *   log n! ~ (n + 1/2) log(n+1) - (n+1) + log(2Pi)/2,
    2207             :   * error bounded by 1/6(n+1) <= 1/12. Finally, we want
    2208             :   * n (-1/log(2) -log_2 |Y| + log_2(n+1)) >= b  */
    2209    15698057 :   d = m-dbllog2(x)-1/M_LN2; /* ~ -log_2 Y - 1/log(2) */
    2210    15698856 :   while (d <= 0) { d++; m++; } /* d < 0 can occur from expm1 */
    2211    15698850 :   L = l + nbits2extraprec(m);
    2212    15698758 :   b += m;
    2213    15698758 :   n = (long)(b / d); /* > 0 */
    2214    15698758 :   if (n == 1)
    2215      743220 :     n = (long)(b / (d + log2((double)n+1))); /* log ~ const in small ranges */
    2216    17057649 :   while (n*(d+log2((double)n+1)) < b) n++; /* expect few corrections */
    2217             : 
    2218    15698758 :   X = rtor(x,L); shiftr_inplace(X, -m); setsigne(X, 1);
    2219    15699246 :   if (n == 1) p2 = X;
    2220             :   else
    2221             :   {
    2222    15699246 :     long s = 0, l1 = nbits2prec((long)(d + n + 16));
    2223    15699096 :     GEN unr = real_1(L);
    2224             :     pari_sp av2;
    2225             : 
    2226    15698765 :     p2 = cgetr(L); av2 = avma;
    2227   249540334 :     for (i=n; i>=2; i--, set_avma(av2))
    2228             :     { /* compute X^(n-1)/n! + ... + X/2 + 1 */
    2229             :       GEN p1, p3;
    2230   233923484 :       setprec(X,l1); p3 = divru(X,i);
    2231   234141567 :       l1 += nbits2extraprec(dvmdsBIL(s - expo(p3), &s)<<TWOPOTBITS_IN_LONG);
    2232   234114139 :       if (l1>L) l1=L;
    2233   234114139 :       setprec(unr,l1); p1 = addrr_sign(unr,1, i == n? p3: mulrr(p3,p2),1);
    2234   233727723 :       setprec(p2,l1); affrr(p1,p2); /* p2 <- 1 + (X/i)*p2 */
    2235             :     }
    2236    15698011 :     setprec(X,L); p2 = mulrr(X,p2);
    2237             :   }
    2238             : 
    2239    15699395 :   B = prec2nbits(L);
    2240   158095715 :   for (i = 1; i <= m; i++)
    2241             :   {
    2242   142394051 :     if (realprec(p2) > L) setprec(p2,L);
    2243   142394051 :     if (expo(p2) < -B)
    2244           0 :       shiftr_inplace(p2, 1); /* 2 + p2 ~ 2 and may blow up accuracy */
    2245             :     else
    2246   142394051 :       p2 = mulrr(p2, addsr(2,p2));
    2247             :   }
    2248    15701664 :   affrr_fixlg(p2,y); return gc_const(av,y);
    2249             : }
    2250             : 
    2251             : GEN
    2252       10800 : mpexpm1(GEN x)
    2253             : {
    2254       10800 :   const long s = 6;
    2255       10800 :   long B, l, sx = signe(x);
    2256             :   GEN y, z;
    2257             :   pari_sp av;
    2258       10800 :   if (!sx) return real_0_bit(expo(x));
    2259       10793 :   l = realprec(x);
    2260       10793 :   if (l > lg2prec(maxss(EXPNEWTON_LIMIT, (1L<<s) + 2)))
    2261             :   {
    2262           6 :     long e = expo(x);
    2263           6 :     if (e < 0) x = rtor(x, l + nbits2extraprec(-e));
    2264           6 :     return subrs(mpexp(x), 1);
    2265             :   }
    2266       10787 :   if (sx > 0) return exp1r_abs(x);
    2267        4900 :   B = prec2nbits(l);
    2268        4900 :   if (cmpsr(-B, x) > 0) return real_m1(l);
    2269             :   /* compute exp(x) * (1 - exp(-x)) */
    2270        4893 :   av = avma; y = exp1r_abs(x); /* > 0 */
    2271        4893 :   if (expo(y) >= -B) { z = addsr(1, y); y = divrr(y, z); }
    2272        4893 :   setsigne(y, -1);
    2273        4893 :   return gerepileuptoleaf(av, y);
    2274             : }
    2275             : 
    2276             : static GEN serexp(GEN x, long prec);
    2277             : GEN
    2278       12609 : gexpm1(GEN x, long prec)
    2279             : {
    2280       12609 :   switch(typ(x))
    2281             :   {
    2282        4577 :     case t_REAL: return mpexpm1(x);
    2283        5932 :     case t_COMPLEX: return cxexpm1(x,prec);
    2284          14 :     case t_PADIC: return gsubgs(Qp_exp(x), 1);
    2285        2086 :     default:
    2286             :     {
    2287        2086 :       pari_sp av = avma;
    2288             :       long ey;
    2289             :       GEN y;
    2290        2086 :       if (!(y = toser_i(x))) break;
    2291        2065 :       ey = valser(y);
    2292        2065 :       if (ey < 0) pari_err_DOMAIN("expm1","valuation", "<", gen_0, x);
    2293        2065 :       if (gequal0(y)) return gcopy(y);
    2294        2058 :       if (ey)
    2295         504 :         return gerepileupto(av, gsubgs(serexp(y,prec), 1));
    2296             :       else
    2297             :       {
    2298        1554 :         GEN e1 = gexpm1(gel(y,2), prec), e = gaddgs(e1,1);
    2299        1554 :         y = gmul(e, serexp(serchop0(y),prec));
    2300        1554 :         gel(y,2) = e1;
    2301        1554 :         return gerepilecopy(av, y);
    2302             :       }
    2303             :     }
    2304             :   }
    2305          21 :   return trans_eval("expm1",gexpm1,x,prec);
    2306             : }
    2307             : /********************************************************************/
    2308             : /**                                                                **/
    2309             : /**                             EXP(X)                             **/
    2310             : /**                                                                **/
    2311             : /********************************************************************/
    2312             : static GEN
    2313    15649246 : mpexp_basecase(GEN x)
    2314             : {
    2315    15649246 :   pari_sp av = avma;
    2316    15649246 :   long sh, l = realprec(x);
    2317             :   GEN y, z;
    2318             : 
    2319    15649246 :   y = modlog2(x, &sh);
    2320    15649039 :   if (!y) { set_avma(av); return real2n(sh, l); }
    2321    15649039 :   z = addsr(1, exp1r_abs(y));
    2322    15649285 :   if (signe(y) < 0) z = invr(z);
    2323    15649525 :   if (sh) {
    2324    12660648 :     shiftr_inplace(z, sh);
    2325    12660503 :     if (realprec(z) > l) z = rtor(z, l); /* spurious precision increase */
    2326             :   }
    2327             : #ifdef DEBUG
    2328             : {
    2329             :   GEN t = mplog(z), u = divrr(subrr(x, t),x);
    2330             :   if (signe(u) && expo(u) > 5-prec2nbits(minss(l,realprec(t))))
    2331             :     pari_err_BUG("exp");
    2332             : }
    2333             : #endif
    2334    15649612 :   return gerepileuptoleaf(av, z); /* NOT affrr, precision often increases */
    2335             : }
    2336             : 
    2337             : GEN
    2338    15720400 : mpexp(GEN x)
    2339             : {
    2340    15720400 :   const long s = 6; /*Initial steps using basecase*/
    2341    15720400 :   long i, p, l = realprec(x), sh;
    2342             :   GEN a, t, z;
    2343             :   ulong mask;
    2344             : 
    2345    15720400 :   if (l <= lg2prec(maxss(EXPNEWTON_LIMIT, (1L<<s) + 2)))
    2346             :   {
    2347    15720276 :     if (!signe(x)) return mpexp0(x);
    2348    15649199 :     return mpexp_basecase(x);
    2349             :   }
    2350          13 :   z = cgetr(l); /* room for result */
    2351          13 :   x = modlog2(x, &sh);
    2352          13 :   if (!x) { set_avma((pari_sp)(z+lg(z))); return real2n(sh, l); }
    2353          13 :   constpi(l); /* precompute for later logr_abs() */
    2354          13 :   mask = quadratic_prec_mask(prec2nbits(l)+BITS_IN_LONG);
    2355         168 :   for(i=0, p=1; i<s+TWOPOTBITS_IN_LONG; i++) { p <<= 1; if (mask & 1) p-=1; mask >>= 1; }
    2356          13 :   a = mpexp_basecase(rtor(x, nbits2prec(p)));
    2357          13 :   x = addrs(x,1);
    2358          13 :   if (realprec(x) < l+EXTRAPREC64) x = rtor(x, l+EXTRAPREC64);
    2359          13 :   a = rtor(a, l+EXTRAPREC64); /*append 0s */
    2360          13 :   t = NULL;
    2361             :   for(;;)
    2362             :   {
    2363          14 :     p <<= 1; if (mask & 1) p--;
    2364          14 :     mask >>= 1;
    2365          14 :     setprec(x, nbits2prec(p));
    2366          14 :     setprec(a, nbits2prec(p));
    2367          14 :     t = mulrr(a, subrr(x, logr_abs(a))); /* a (x - log(a)) */
    2368          14 :     if (mask == 1) break;
    2369           1 :     affrr(t, a); set_avma((pari_sp)a);
    2370             :   }
    2371          13 :   affrr(t,z);
    2372          13 :   if (sh) shiftr_inplace(z, sh);
    2373          13 :   return gc_const((pari_sp)z, z);
    2374             : }
    2375             : 
    2376             : /* x != 0; k = ceil(tn / (te-1)), t = p-1 */
    2377             : long
    2378          98 : Qp_exp_prec(GEN x)
    2379             : {
    2380          98 :   long e = valp(x), n = precp(x);
    2381             :   ulong a, b, q, r, p, t;
    2382             : 
    2383          98 :   if (e < 1) return -1;
    2384          77 :   if (e > n) return 1;
    2385          77 :   p = itos_or_0(gel(x,2));
    2386          77 :   if (!p) return n / e + 1;
    2387          77 :   if (p == 2) return e < 2? -1: ceildivuu(n, e - 1);
    2388             :   /* n >= e > 0, n = qe + r */
    2389             :   /* tn = q (te-1) + rt + q = (q+1)(te-1) - t(e-r) + q + 1 */
    2390          63 :   t = p - 1;
    2391          63 :   if (e == 1) return n + ceildivuu(n, t - 1);
    2392           0 :   q = n / e;
    2393           0 :   r = n % e; /* k = q + 1 if rt + q < te */
    2394           0 :   a = umuluu_or_0(e - r, t); if (!a || a > q) return q + 1;
    2395           0 :   b = umuluu_or_0(e, t); if (!b) return q + 2;
    2396           0 :   return q + 1 + ceildivuu(q + 1 - a, b - 1);
    2397             : }
    2398             : 
    2399             : static GEN
    2400      108762 : Qp_exp_safe(GEN x)
    2401             : {
    2402      108762 :   pari_sp av = avma;
    2403      108762 :   GEN p = gel(x,2), a = gel(x,4), z;
    2404      108762 :   long d = precp(x), v = valp(x), e = d+v;
    2405      108762 :   if (gequal0(x)) return gaddgs(x,1);
    2406      107257 :   if (v < (equaliu(p,2)? 2:1)) return NULL;
    2407      107250 :   z = Zp_exp(mulii(a,powiu(p,v)), p, e);
    2408      107250 :   return gerepileupto(av, Z_to_padic(z, p, e));
    2409             : }
    2410             : 
    2411             : GEN
    2412      108300 : Qp_exp(GEN x)
    2413             : {
    2414      108300 :   GEN y = Qp_exp_safe(x);
    2415      108303 :   if (!y) pari_err_DOMAIN("gexp(t_PADIC)","argument","",gen_0,x);
    2416      108296 :   return y;
    2417             : }
    2418             : 
    2419             : static GEN
    2420          49 : cos_p(GEN x)
    2421             : {
    2422             :   long k;
    2423             :   pari_sp av;
    2424             :   GEN x2, y;
    2425             : 
    2426          49 :   if (gequal0(x)) return gaddgs(x,1);
    2427          28 :   k = Qp_exp_prec(x);
    2428          28 :   if (k < 0) return NULL;
    2429          21 :   av = avma; x2 = gsqr(x);
    2430          21 :   if (k & 1) k--;
    2431         105 :   for (y=gen_1; k; k-=2)
    2432             :   {
    2433          84 :     GEN t = gdiv(gmul(y,x2), muluu(k, k-1));
    2434          84 :     y = gsubsg(1, t);
    2435             :   }
    2436          21 :   return gerepileupto(av, y);
    2437             : }
    2438             : static GEN
    2439          63 : sin_p(GEN x)
    2440             : {
    2441             :   long k;
    2442             :   pari_sp av;
    2443             :   GEN x2, y;
    2444             : 
    2445          63 :   if (gequal0(x)) return gcopy(x);
    2446          42 :   k = Qp_exp_prec(x);
    2447          42 :   if (k < 0) return NULL;
    2448          28 :   av = avma; x2 = gsqr(x);
    2449          28 :   if (k & 1) k--;
    2450         133 :   for (y=gen_1; k; k-=2)
    2451             :   {
    2452         105 :     GEN t = gdiv(gmul(y,x2), muluu(k, k+1));
    2453         105 :     y = gsubsg(1, t);
    2454             :   }
    2455          28 :   return gerepileupto(av, gmul(y, x));
    2456             : }
    2457             : 
    2458             : static GEN
    2459     3275626 : cxexp(GEN x, long prec)
    2460             : {
    2461     3275626 :   GEN r, p1, p2, y = cgetg(3,t_COMPLEX);
    2462     3275735 :   pari_sp av = avma, tetpil;
    2463             :   long l;
    2464     3275735 :   l = precision(x); if (l > prec) prec = l;
    2465     3275743 :   if (gequal0(gel(x,1)))
    2466             :   {
    2467      344514 :     gsincos(gel(x,2),&gel(y,2),&gel(y,1),prec);
    2468      344535 :     return y;
    2469             :   }
    2470     2931259 :   r = gexp(gel(x,1),prec);
    2471     2931661 :   gsincos(gel(x,2),&p2,&p1,prec);
    2472     2931774 :   tetpil = avma;
    2473     2931774 :   gel(y,1) = gmul(r,p1);
    2474     2931650 :   gel(y,2) = gmul(r,p2);
    2475     2931638 :   gerepilecoeffssp(av,tetpil,y+1,2);
    2476     2931859 :   return y;
    2477             : }
    2478             : 
    2479             : /* given a t_SER x^v s(x), with s(0) != 0, return x^v(s - s(0)), shallow */
    2480             : GEN
    2481       36645 : serchop0(GEN s)
    2482             : {
    2483       36645 :   long i, l = lg(s);
    2484             :   GEN y;
    2485       36645 :   if (l == 2) return s;
    2486       36645 :   if (l == 3 && isexactzero(gel(s,2))) return s;
    2487       36645 :   y = cgetg(l, t_SER); y[1] = s[1];
    2488      164220 :   gel(y,2) = gen_0; for (i=3; i <l; i++) gel(y,i) = gel(s,i);
    2489       36645 :   return normalizeser(y);
    2490             : }
    2491             : 
    2492             : GEN
    2493          42 : serchop_i(GEN s, long n)
    2494             : {
    2495          42 :   long i, m, l = lg(s);
    2496             :   GEN y;
    2497          42 :   if (l == 2 || (l == 3 && isexactzero(gel(s,2))))
    2498             :   {
    2499          14 :     if (valser(s) < n) { s = shallowcopy(s); setvalser(s,n); }
    2500          14 :     return s;
    2501             :   }
    2502          28 :   m = n - valser(s); if (m < 0) return s;
    2503          21 :   if (l-m <= 2) return zeroser(varn(s), n);
    2504          14 :   y = cgetg(l-m, t_SER); y[1] = s[1]; setvalser(y, valser(y)+m);
    2505          42 :   for (i=m+2; i < l; i++) gel(y,i-m) = gel(s,i);
    2506          14 :   return normalizeser(y);
    2507             : }
    2508             : GEN
    2509          42 : serchop(GEN s, long n)
    2510             : {
    2511          42 :   pari_sp av = avma;
    2512          42 :   if (typ(s) != t_SER) pari_err_TYPE("serchop",s);
    2513          42 :   return gerepilecopy(av, serchop_i(s,n));
    2514             : }
    2515             : 
    2516             : static GEN
    2517       80108 : serexp(GEN x, long prec)
    2518             : {
    2519       80108 :   long i, j, lx, ly, mi, e = valser(x);
    2520             :   GEN y, xd, yd;
    2521             :   pari_sp av;
    2522             : 
    2523       80108 :   if (e < 0) pari_err_DOMAIN("exp","valuation", "<", gen_0, x);
    2524       80101 :   if (gequal0(x)) return gaddsg(1,x);
    2525       69482 :   lx = lg(x);
    2526       69482 :   if (e)
    2527             :   {
    2528             :     GEN X;
    2529       55496 :     ly = lx+e; y = cgetg(ly,t_SER);
    2530      566986 :     mi = lx-1; while (mi>=3 && isrationalzero(gel(x,mi))) mi--;
    2531       55496 :     mi += e-2;
    2532       55496 :     y[1] = evalsigne(1) | _evalvalser(0) | evalvarn(varn(x));
    2533             :     /* zd[i] = coefficient of X^i in z */
    2534       55496 :     xd = x+2-e; yd = y+2; ly -= 2;
    2535       55496 :     X = gel(xd,e); if (e != 1) X = gmulgu(X, e); /* left on stack */
    2536       55496 :     X = isint1(X)? NULL: X;
    2537       55496 :     gel(yd,0) = gen_1;
    2538       55867 :     for (i = 1; i < e; i++) gel(yd,i) = gen_0;
    2539      664573 :     for (     ; i < ly; i++)
    2540             :     {
    2541      609077 :       GEN t = gel(yd,i-e);
    2542      609077 :       long J = minss(i, mi);
    2543      609077 :       av = avma; if (X) t = gmul(t, X);
    2544     2579318 :       for (j = e + 1; j <= J; j++)
    2545     1970241 :         t = gadd(t, gmulgu(gmul(gel(xd,j),gel(yd,i-j)), j));
    2546      609077 :       gel(yd,i) = gerepileupto(av, gdivgu(t, i));
    2547             :     }
    2548       55496 :     return y;
    2549             :   }
    2550       13986 :   av = avma;
    2551       13986 :   return gerepileupto(av, gmul(gexp(gel(x,2),prec), serexp(serchop0(x),prec)));
    2552             : }
    2553             : 
    2554             : static GEN
    2555     1468516 : expQ(GEN x, long prec)
    2556             : {
    2557     1468516 :   GEN p, q, z, z0 = NULL;
    2558             :   pari_sp av;
    2559     1468516 :   long n, nmax, s, e, b = prec2nbits(prec);
    2560             :   double ex;
    2561             :   struct abpq_res R;
    2562             :   struct abpq S;
    2563             : 
    2564     1468515 :   if (typ(x) == t_INT)
    2565             :   {
    2566       24626 :     if (!signe(x)) return real_1(prec);
    2567       24604 :     p = x; q = gen_1;
    2568       24604 :     e = expi(p);
    2569       24603 :     if (e > b) return mpexp(itor(x, prec));
    2570             :   }
    2571             :   else
    2572             :   {
    2573     1443889 :     long ep, eq, B = usqrt(b) / 2;
    2574     1443890 :     p = gel(x,1); ep = expi(p);
    2575     1443890 :     q = gel(x,2); eq = expi(q);
    2576     1443890 :     if (ep > B || eq > B) return mpexp(fractor(x, prec));
    2577       14637 :     e = ep - eq;
    2578       14637 :     if (e < -3) prec += nbits2extraprec(-e); /* see addrr 'extend' rule */
    2579             :   }
    2580       39240 :   if (e > 2) { z0 = cgetr(prec); prec += EXTRAPREC64; b += BITS_IN_LONG; }
    2581       39240 :   z = cgetr(prec); av = avma;
    2582       39239 :   if (e > 0)
    2583             :   { /* simplify x/2^e = p / (q * 2^e) */
    2584        2478 :     long v = minss(e, vali(p));
    2585        2478 :     if (v) p = shifti(p, -v);
    2586        2478 :     if (e - v) q = shifti(q, e - v);
    2587             :   }
    2588       39239 :   s = signe(p);
    2589       39239 :   if (s < 0) p = negi(p);
    2590       39245 :   ex = exp2(dbllog2(x) - e) * 2.718281828; /* exp(1) * x / 2^e,  x / 2^e < 2 */
    2591       39240 :   nmax = (long)(1 + exp(dbllambertW0(M_LN2 * b / ex)) * ex);
    2592       39244 :   abpq_init(&S, nmax);
    2593       39279 :   S.a[0] = S.b[0] = S.p[0] = S.q[0] = gen_1;
    2594     3370091 :   for (n = 1; n <= nmax; n++)
    2595             :   {
    2596     3330849 :     S.a[n] = gen_1;
    2597     3330849 :     S.b[n] = gen_1;
    2598     3330849 :     S.p[n] = p;
    2599     3330849 :     S.q[n] = muliu(q, n);
    2600             :   }
    2601       39242 :   abpq_sum(&R, 0, nmax, &S);
    2602       39261 :   if (s > 0) rdiviiz(R.T, R.Q, z); else rdiviiz(R.Q, R.T, z);
    2603       39256 :   if (e > 0)
    2604             :   {
    2605       17136 :     q = z; while (e--) q = sqrr(q);
    2606        2478 :     if (z0) { affrr(q, z0); z = z0; } else affrr(q,z);
    2607             :   }
    2608       39256 :   return gc_const(av,z);
    2609             : }
    2610             : 
    2611             : GEN
    2612    14787583 : gexp(GEN x, long prec)
    2613             : {
    2614    14787583 :   switch(typ(x))
    2615             :   {
    2616     1468515 :     case t_INT: case t_FRAC: return expQ(x, prec);
    2617     8696907 :     case t_REAL: return mpexp(x);
    2618     3275713 :     case t_COMPLEX: return cxexp(x,prec);
    2619          70 :     case t_PADIC: return Qp_exp(x);
    2620     1346378 :     default:
    2621             :     {
    2622     1346378 :       pari_sp av = avma;
    2623             :       GEN y;
    2624     1346378 :       if (!(y = toser_i(x))) break;
    2625       64064 :       return gerepileupto(av, serexp(y,prec));
    2626             :     }
    2627             :   }
    2628     1282921 :   return trans_eval("exp",gexp,x,prec);
    2629             : }
    2630             : 
    2631             : /********************************************************************/
    2632             : /**                                                                **/
    2633             : /**                           AGM(X, Y)                            **/
    2634             : /**                                                                **/
    2635             : /********************************************************************/
    2636             : static int
    2637    18524014 : agmr_gap(GEN a, GEN b, long L)
    2638             : {
    2639    18524014 :   GEN d = subrr(b, a);
    2640    18523811 :   return (signe(d) && expo(d) - expo(b) >= L);
    2641             : }
    2642             : /* assume x > 0 */
    2643             : static GEN
    2644     1294312 : agm1r_abs(GEN x)
    2645             : {
    2646     1294312 :   long l = realprec(x), L = 5-prec2nbits(l);
    2647     1294312 :   GEN a1, b1, y = cgetr(l);
    2648     1294314 :   pari_sp av = avma;
    2649             : 
    2650     1294314 :   a1 = addrr(real_1(l), x); shiftr_inplace(a1, -1);
    2651     1294314 :   b1 = sqrtr_abs(x);
    2652    18524050 :   while (agmr_gap(a1,b1,L))
    2653             :   {
    2654    17229565 :     GEN a = a1;
    2655    17229565 :     a1 = addrr(a,b1); shiftr_inplace(a1, -1);
    2656    17229653 :     b1 = sqrtr_abs(mulrr(a,b1));
    2657             :   }
    2658     1294248 :   affrr_fixlg(a1,y); return gc_const(av,y);
    2659             : }
    2660             : 
    2661             : struct agmcx_gap_t { long L, ex, cnt; };
    2662             : 
    2663             : static void
    2664      284577 : agmcx_init(GEN x, long *prec, struct agmcx_gap_t *S)
    2665             : {
    2666      284577 :   long l = precision(x);
    2667      284577 :   if (l) *prec = l;
    2668      284577 :   S->L = 1-prec2nbits(*prec);
    2669      284577 :   S->cnt = 0;
    2670      284577 :   S->ex = LONG_MAX;
    2671      284577 : }
    2672             : 
    2673             : static long
    2674      284577 : agmcx_a_b(GEN x, GEN *a1, GEN *b1, long prec)
    2675             : {
    2676      284577 :   long rotate = 0;
    2677      284577 :   if (gsigne(real_i(x))<0)
    2678             :   { /* Rotate by +/-Pi/2, so that the choice of the principal square
    2679             :      * root gives the optimal AGM. So a1 = +/-I*a1, b1=sqrt(-x). */
    2680        1561 :     if (gsigne(imag_i(x))<0) { *a1=mulcxI(*a1);  rotate=-1; }
    2681        1043 :     else                     { *a1=mulcxmI(*a1); rotate=1; }
    2682        1561 :     x = gneg(x);
    2683             :   }
    2684      284577 :   *b1 = gsqrt(x, prec);
    2685      284577 :   return rotate;
    2686             : }
    2687             : /* return 0 if we must stop the AGM loop (a=b or a ~ b), 1 otherwise */
    2688             : static int
    2689     4766933 : agmcx_gap(GEN a, GEN b, struct agmcx_gap_t *S)
    2690             : {
    2691     4766933 :   GEN d = gsub(b, a);
    2692     4766933 :   long ex = S->ex;
    2693     4766933 :   S->ex = gexpo(d);
    2694     4766933 :   if (gequal0(d) || S->ex - gexpo(b) < S->L) return 0;
    2695             :   /* if (S->ex >= ex) we're no longer making progress; twice in a row */
    2696     4567059 :   if (S->ex < ex) S->cnt = 0;
    2697             :   else
    2698      169452 :     if (S->cnt++) return 0;
    2699     4482356 :   return 1;
    2700             : }
    2701             : static GEN
    2702      284528 : agm1cx(GEN x, long prec)
    2703             : {
    2704             :   struct agmcx_gap_t S;
    2705             :   GEN a1, b1;
    2706      284528 :   pari_sp av = avma;
    2707             :   long rotate;
    2708      284528 :   agmcx_init(x, &prec, &S);
    2709      284528 :   a1 = gtofp(gmul2n(gadd(real_1(prec), x), -1), prec);
    2710      284528 :   rotate = agmcx_a_b(x, &a1, &b1, prec);
    2711     4766610 :   while (agmcx_gap(a1,b1,&S))
    2712             :   {
    2713     4482082 :     GEN a = a1;
    2714     4482082 :     a1 = gmul2n(gadd(a,b1),-1);
    2715     4482082 :     b1 = gsqrt(gmul(a,b1), prec);
    2716             :   }
    2717      284528 :   if (rotate) a1 = rotate>0 ? mulcxI(a1):mulcxmI(a1);
    2718      284528 :   return gerepilecopy(av,a1);
    2719             : }
    2720             : 
    2721             : GEN
    2722          49 : zellagmcx(GEN a0, GEN b0, GEN r, GEN t, long prec)
    2723             : {
    2724             :   struct agmcx_gap_t S;
    2725          49 :   pari_sp av = avma;
    2726          49 :   GEN x = gdiv(a0, b0), a1, b1;
    2727             :   long rotate;
    2728          49 :   agmcx_init(x, &prec, &S);
    2729          49 :   a1 = gtofp(gmul2n(gadd(real_1(prec), x), -1), prec);
    2730          49 :   r = gsqrt(gdiv(gmul(a1,gaddgs(r, 1)),gadd(r, x)), prec);
    2731          49 :   t = gmul(r, t);
    2732          49 :   rotate = agmcx_a_b(x, &a1, &b1, prec);
    2733         323 :   while (agmcx_gap(a1,b1,&S))
    2734             :   {
    2735         274 :     GEN a = a1, b = b1;
    2736         274 :     a1 = gmul2n(gadd(a,b),-1);
    2737         274 :     b1 = gsqrt(gmul(a,b), prec);
    2738         274 :     r = gsqrt(gdiv(gmul(a1,gaddgs(r, 1)),gadd(gmul(b, r), a )), prec);
    2739         274 :     t = gmul(r, t);
    2740             :   }
    2741          49 :   if (rotate) a1 = rotate>0 ? mulcxI(a1):mulcxmI(a1);
    2742          49 :   a1 = gmul(a1, b0);
    2743          49 :   t = gatan(gdiv(a1,t), prec);
    2744             :   /* send t to the fundamental domain if necessary */
    2745          49 :   if (gsigne(real_i(t))<0) t = gadd(t, mppi(prec));
    2746          49 :   return gerepileupto(av,gdiv(t,a1));
    2747             : }
    2748             : 
    2749             : static long
    2750          49 : ser_cmp_expo(GEN A, GEN B)
    2751             : {
    2752          49 :   long e = -(long)HIGHEXPOBIT, d = valser(B) - valser(A);
    2753          49 :   long i, la = lg(A), v = varn(B);
    2754        9849 :   for (i = 2; i < la; i++)
    2755             :   {
    2756        9800 :     GEN a = gel(A,i), b;
    2757             :     long ei;
    2758        9800 :     if (isexactzero(a)) continue;
    2759        9800 :     b = polcoef_i(B, i-2 + d, v);
    2760        9800 :     ei = gexpo(a);
    2761        9800 :     if (!isexactzero(b)) ei -= gexpo(b);
    2762        9800 :     e = maxss(e, ei);
    2763             :   }
    2764          49 :   return e;
    2765             : }
    2766             : 
    2767             : static GEN
    2768          21 : ser_agm1(GEN y, long prec)
    2769             : {
    2770          21 :   GEN a1 = y, b1 = gen_1;
    2771          21 :   long l = lg(y)-2, l2 = 6-prec2nbits(prec), eold = LONG_MAX;
    2772             :   for(;;)
    2773          84 :   {
    2774         105 :     GEN a = a1, p1;
    2775         105 :     a1 = gmul2n(gadd(a,b1),-1);
    2776         105 :     b1 = gsqrt(gmul(a,b1), prec);
    2777         105 :     p1 = gsub(b1,a1);
    2778         105 :     if (isinexactreal(p1))
    2779             :     {
    2780          49 :       long e = ser_cmp_expo(p1, b1);
    2781          49 :       if (e < l2 || e >= eold) break;
    2782          42 :       eold = e;
    2783             :     }
    2784          56 :     else if (valser(p1)-valser(b1) >= l || gequal0(p1)) break;
    2785             :   }
    2786          21 :   return a1;
    2787             : }
    2788             : 
    2789             : /* agm(1,x) */
    2790             : static GEN
    2791       17707 : agm1(GEN x, long prec)
    2792             : {
    2793             :   GEN y;
    2794             :   pari_sp av;
    2795             : 
    2796       17707 :   if (gequal0(x)) return gcopy(x);
    2797       17707 :   switch(typ(x))
    2798             :   {
    2799          28 :     case t_INT:
    2800          28 :       if (!is_pm1(x)) break;
    2801          21 :       return (signe(x) > 0)? real_1(prec): real_0(prec);
    2802             : 
    2803       11995 :     case t_REAL: return signe(x) > 0? agm1r_abs(x): agm1cx(x, prec);
    2804             : 
    2805        5544 :     case t_COMPLEX:
    2806        5544 :       if (gequal0(gel(x,2))) return agm1(gel(x,1), prec);
    2807        5537 :       return agm1cx(x, prec);
    2808             : 
    2809          14 :     case t_PADIC:
    2810             :     {
    2811          14 :       GEN a1 = x, b1 = gen_1;
    2812          14 :       long l = precp(x);
    2813          14 :       av = avma;
    2814             :       for(;;)
    2815          14 :       {
    2816          28 :         GEN a = a1, p1;
    2817             :         long ep;
    2818          28 :         a1 = gmul2n(gadd(a,b1),-1);
    2819          28 :         a = gmul(a,b1);
    2820          28 :         b1 = Qp_sqrt(a); if (!b1) pari_err_SQRTN("Qp_sqrt",a);
    2821          21 :         p1 = gsub(b1,a1); ep = valp(p1)-valp(b1);
    2822          21 :         if (ep<=0) { b1 = gneg_i(b1); p1 = gsub(b1,a1); ep=valp(p1)-valp(b1); }
    2823          21 :         if (ep >= l || gequal0(p1)) return gerepilecopy(av,a1);
    2824             :       }
    2825             :     }
    2826             : 
    2827         126 :     default:
    2828         126 :       av = avma; if (!(y = toser_i(x))) break;
    2829          21 :       return gerepilecopy(av, ser_agm1(y, prec));
    2830             :   }
    2831         112 :   return trans_eval("agm",agm1,x,prec);
    2832             : }
    2833             : 
    2834             : GEN
    2835       17553 : agm(GEN x, GEN y, long prec)
    2836             : {
    2837             :   pari_sp av;
    2838       17553 :   if (is_matvec_t(typ(y)))
    2839             :   {
    2840          14 :     if (is_matvec_t(typ(x))) pari_err_TYPE2("agm",x,y);
    2841           7 :     swap(x, y);
    2842             :   }
    2843       17546 :   if (gequal0(y)) return gcopy(y);
    2844       17546 :   av = avma;
    2845       17546 :   return gerepileupto(av, gmul(y, agm1(gdiv(x,y), prec)));
    2846             : }
    2847             : 
    2848             : /* b2 != 0 */
    2849             : static GEN
    2850          35 : ellK_i(GEN b2, long prec)
    2851          35 : { return gdiv(Pi2n(-1, prec), agm1(gsqrt(b2, prec), prec)); }
    2852             : GEN
    2853          28 : ellK(GEN k, long prec)
    2854             : {
    2855          28 :   pari_sp av = avma;
    2856          28 :   GEN k2 = gsqr(k), b2 = gsubsg(1, k2);
    2857          28 :   if (gequal0(b2)) pari_err_DOMAIN("ellK", "k^2", "=", gen_1, k2);
    2858          21 :   return gerepileupto(av, ellK_i(b2, prec));
    2859             : }
    2860             : 
    2861             : static int
    2862          84 : magm_gap(GEN a, GEN b, long L)
    2863             : {
    2864          84 :   GEN d = gsub(b, a);
    2865          84 :   return !gequal0(d) && gexpo(d) - gexpo(b) >= L;
    2866             : }
    2867             : 
    2868             : /* http://www.ams.org/notices/201208/rtx120801094p.pdf
    2869             :  * An Eloquent Formula for the Perimeter of an Ellipse
    2870             :  * Semjon Adlaj, Notices of the AMS */
    2871             : static GEN
    2872          14 : magm(GEN a, GEN b, long prec)
    2873             : {
    2874          14 :   long L = -prec2nbits(prec) + 16;
    2875          14 :   GEN c = gen_0;
    2876          84 :   while (magm_gap(a, b, L))
    2877             :   {
    2878          70 :     GEN u = gsqrt(gmul(gsub(a, c), gsub(b, c)), prec);
    2879          70 :     a = gmul2n(gadd(a, b), -1);
    2880          70 :     b = gadd(c, u); c = gsub(c, u);
    2881             :   }
    2882          14 :   return gmul2n(gadd(a, b), -1);
    2883             : }
    2884             : 
    2885             : GEN
    2886          21 : ellE(GEN k, long prec)
    2887             : {
    2888          21 :   pari_sp av = avma;
    2889          21 :   GEN b2 = gsubsg(1, gsqr(k));
    2890          21 :   if (gequal0(b2)) { set_avma(av); return real_1(prec); }
    2891          14 :   return gerepileupto(av, gmul(ellK_i(b2, prec), magm(gen_1, b2, prec)));
    2892             : }
    2893             : 
    2894             : /********************************************************************/
    2895             : /**                                                                **/
    2896             : /**                             LOG(X)                             **/
    2897             : /**                                                                **/
    2898             : /********************************************************************/
    2899             : /* log(2) = 18*atanh(1/26)-2*atanh(1/4801)+8*atanh(1/8749)
    2900             :  * faster than 10*atanh(1/17)+4*atanh(13/499) for all precisions,
    2901             :  * and than Pi/2M(1,4/2^n) ~ n log(2) for bitprec at least up to 10^8 */
    2902             : static GEN
    2903       39149 : log2_split(long prec)
    2904             : {
    2905       39149 :   GEN u = atanhuu(1, 26, prec);
    2906       39166 :   GEN v = atanhuu(1, 4801, prec);
    2907       39160 :   GEN w = atanhuu(1, 8749, prec);
    2908       39162 :   shiftr_inplace(v, 1); setsigne(v, -1);
    2909       39160 :   shiftr_inplace(w, 3);
    2910       39160 :   return addrr(mulur(18, u), addrr(v, w));
    2911             : }
    2912             : GEN
    2913    24720466 : constlog2(long prec)
    2914             : {
    2915             :   pari_sp av;
    2916             :   GEN tmp;
    2917    24720466 :   if (glog2 && realprec(glog2) >= prec) return glog2;
    2918             : 
    2919       38746 :   tmp = cgetr_block(prec);
    2920       39149 :   av = avma;
    2921       39149 :   affrr(log2_split(prec+EXTRAPREC64), tmp);
    2922       39157 :   swap_clone(&glog2,tmp);
    2923       39170 :   return gc_const(av,glog2);
    2924             : }
    2925             : 
    2926             : GEN
    2927    24720438 : mplog2(long prec) { return rtor(constlog2(prec), prec); }
    2928             : 
    2929             : /* dont check that q != 2^expo(q), done in logr_abs */
    2930             : static GEN
    2931     1282361 : logagmr_abs(GEN q)
    2932             : {
    2933     1282361 :   long prec = realprec(q), e = expo(q), lim;
    2934     1282361 :   GEN z = cgetr(prec), y, Q, _4ovQ;
    2935     1282359 :   pari_sp av = avma;
    2936             : 
    2937     1282359 :   incrprec(prec);
    2938     1282359 :   lim = prec2nbits(prec) >> 1;
    2939     1282359 :   Q = rtor(q,prec);
    2940     1282360 :   shiftr_inplace(Q,lim-e); setsigne(Q,1);
    2941             : 
    2942     1282360 :   _4ovQ = invr(Q); shiftr_inplace(_4ovQ, 2); /* 4/Q */
    2943             :   /* Pi / 2agm(1, 4/Q) ~ log(Q), q = Q * 2^(e-lim) */
    2944     1282359 :   y = divrr(Pi2n(-1, prec), agm1r_abs(_4ovQ));
    2945     1282362 :   y = addrr(y, mulsr(e - lim, mplog2(prec)));
    2946     1282359 :   affrr_fixlg(y, z); return gc_const(av,z);
    2947             : }
    2948             : 
    2949             : /* sum_{k >= 0} y^(2k+1) / (2k+1), y close to 0 */
    2950             : static GEN
    2951    10651533 : logr_aux(GEN y)
    2952             : {
    2953    10651533 :   long k, L = realprec(y); /* should be ~ l+1 - (k-2) */
    2954             :   /* log(x) = log(1+y) - log(1-y) = 2 sum_{k odd} y^k / k
    2955             :    * Truncate the sum at k = 2n+1, the remainder is
    2956             :    *   2 sum_{k >= 2n+3} y^k / k < 2y^(2n+3) / (2n+3)(1-y) < y^(2n+3)
    2957             :    * We want y^(2n+3) < y 2^(-prec2nbits(L)), hence
    2958             :    *   n+1 > -prec2nbits(L) /-log_2(y^2) */
    2959    10651533 :   double d = -2*dbllog2r(y); /* ~ -log_2(y^2) */
    2960    10651614 :   k = (long)(2*(prec2nbits(L) / d));
    2961    10651581 :   k |= 1;
    2962    10651581 :   if (k >= 3)
    2963             :   {
    2964    10631357 :     GEN T, S = cgetr(L), y2 = sqrr(y), unr = real_1(L);
    2965    10631473 :     pari_sp av = avma;
    2966    10631473 :     long s = 0, incs = (long)d, l1 = nbits2prec((long)d);
    2967    10631514 :     setprec(S,  l1);
    2968    10631436 :     setprec(unr,l1); affrr(divru(unr,k), S);
    2969   185039711 :     for (k -= 2;; k -= 2) /* k = 2n+1, ..., 1 */
    2970             :     { /* S = y^(2n+1-k)/(2n+1) + ... + 1 / k */
    2971   185039711 :       setprec(y2, l1); T = mulrr(S,y2);
    2972   185063147 :       if (k == 1) break;
    2973             : 
    2974   174431923 :       l1 += nbits2extraprec(dvmdsBIL(s + incs, &s)<<TWOPOTBITS_IN_LONG);
    2975   174407648 :       if (l1>L) l1=L;
    2976   174407648 :       setprec(S, l1);
    2977   174412921 :       setprec(unr,l1);
    2978   174398112 :       affrr(addrr(divru(unr, k), T), S); set_avma(av);
    2979             :     }
    2980             :     /* k = 1 special-cased for eficiency */
    2981    10631224 :     y = mulrr(y, addsr(1,T)); /* = log(X)/2 */
    2982             :   }
    2983    10651664 :   return y;
    2984             : }
    2985             : /*return log(|x|), assuming x != 0 */
    2986             : GEN
    2987    12395220 : logr_abs(GEN X)
    2988             : {
    2989    12395220 :   long EX, L, m, k, a, b, l = lg(X), p = realprec(X);
    2990             :   GEN z, x, y;
    2991             :   ulong u;
    2992             :   double d;
    2993             : 
    2994             :  /* Assuming 1 < x < 2, we want delta = x-1, 1-x/2, 1-1/x, or 2/x-1 small.
    2995             :   * We have 2/x-1 > 1-x/2, 1-1/x < x-1. So one should be choosing between
    2996             :   * 1-1/x and 1-x/2 ( crossover sqrt(2), worse ~ 0.29 ). To avoid an inverse,
    2997             :   * we choose between x-1 and 1-x/2 ( crossover 4/3, worse ~ 0.33 ) */
    2998    12395220 :   EX = expo(X);
    2999    12395220 :   u = uel(X,2);
    3000    12395220 :   k = 2;
    3001    12395220 :   if (u > (~0UL / 3) * 2) { /* choose 1-x/2 */
    3002     7057954 :     EX++; u = ~u;
    3003     7125803 :     while (!u && ++k < l) { u = uel(X,k); u = ~u; }
    3004             :   } else { /* choose x - 1 */
    3005     5337266 :     u &= ~HIGHBIT; /* u - HIGHBIT, assuming HIGHBIT set */
    3006     6499607 :     while (!u && ++k < l) u = uel(X,k);
    3007             :   }
    3008    12395220 :   if (k == l) return EX? mulsr(EX, mplog2(p)): real_0(p);
    3009    11934104 :   a = bit_accuracy(k) + bfffo(u); /* ~ -log2 |1-x| */
    3010    11934192 :   L = p+EXTRAPRECWORD;
    3011    11934192 :   b = prec2nbits(L - (bit_accuracy(k))); /* take loss of accuracy into account */
    3012    11934194 :   if (b > 24*a*log2(prec2lg(L)) && p > lg2prec(LOGAGM_LIMIT)) return logagmr_abs(X);
    3013             : 
    3014    10651890 :   z = cgetr(EX? p: p - bit_accuracy(k));
    3015             : 
    3016             :  /* Multiplication is quadratic in this range (l is small, otherwise we
    3017             :   * use AGM). Set Y = x^(1/2^m), y = (Y - 1) / (Y + 1) and compute truncated
    3018             :   * series sum y^(2k+1)/(2k+1): the costs is less than
    3019             :   *    m b^2 + sum_{k <= n} ((2k+1) e + BITS_IN_LONG)^2
    3020             :   * bit operations with |x-1| <  2^(1-a), |Y| < 2^(1-e) , m = e-a and b bits of
    3021             :   * accuracy needed (+ BITS_IN_LONG since bit accuracies increase by
    3022             :   * increments of BITS_IN_LONG), so
    3023             :   * 4n^3/3 e^2 + n^2 2e BITS_IN_LONG+ n BITS_IN_LONG ~ m b^2, with n ~ b/2e
    3024             :   * or b/6e + BITS_IN_LONG/2e + BITS_IN_LONG/2be ~ m
    3025             :   *    B := (b / 6 + BITS_IN_LONG/2 + BITS_IN_LONG^2 / 2b) ~ m(m+a)
    3026             :   *     m = min( -a/2 + sqrt(a^2/4 + B),  b - a )
    3027             :   * NB: e ~ (b/6)^(1/2) as b -> oo
    3028             :   * Instead of the above pessimistic estimate for the cost of the sum, use
    3029             :   * optimistic estimate (BITS_IN_LONG -> 0) */
    3030    10651824 :   d = -a/2.; m = (long)(d + sqrt(d*d + b/6)); /* >= 0 */
    3031             : 
    3032    10651824 :   if (m > b-a) m = b-a;
    3033    10651824 :   if (m < 0.2*a) m = 0; else L += nbits2extraprec(m);
    3034    10651850 :   x = rtor(X,L);
    3035    10651880 :   setsigne(x,1); shiftr_inplace(x,-EX);
    3036             :   /* 2/3 < x < 4/3 */
    3037    60341286 :   for (k=1; k<=m; k++) x = sqrtr_abs(x);
    3038             : 
    3039    10651760 :   y = divrr(subrs(x,1), addrs(x,1)); /* = (x-1) / (x+1), close to 0 */
    3040    10651519 :   y = logr_aux(y); /* log(1+y) - log(1-y) = log(x) */
    3041    10651600 :   shiftr_inplace(y, m + 1);
    3042    10651501 :   if (EX) y = addrr(y, mulsr(EX, mplog2(p+EXTRAPRECWORD)));
    3043    10651333 :   affrr_fixlg(y, z); return gc_const((pari_sp)z, z);
    3044             : }
    3045             : 
    3046             : /* assume Im(q) != 0 and precision(q) >= prec. Compute log(q) with accuracy
    3047             :  * prec [disregard input accuracy] */
    3048             : GEN
    3049      278949 : logagmcx(GEN q, long prec)
    3050             : {
    3051      278949 :   GEN z = cgetc(prec), y, Q, a, b;
    3052             :   long lim, e, ea, eb;
    3053      278949 :   pari_sp av = avma;
    3054      278949 :   int neg = 0;
    3055             : 
    3056      278949 :   incrprec(prec);
    3057      278949 :   if (gsigne(gel(q,1)) < 0) { q = gneg(q); neg = 1; }
    3058      278949 :   lim = prec2nbits(prec) >> 1;
    3059      278949 :   Q = gtofp(q, prec);
    3060      278949 :   a = gel(Q,1);
    3061      278949 :   b = gel(Q,2);
    3062      278949 :   if (gequal0(a)) {
    3063           0 :     affrr_fixlg(logr_abs(b), gel(z,1));
    3064           0 :     y = Pi2n(-1, prec);
    3065           0 :     if (signe(b) < 0) setsigne(y, -1);
    3066           0 :     affrr_fixlg(y, gel(z,2)); return gc_const(av,z);
    3067             :   }
    3068      278949 :   ea = expo(a);
    3069      278949 :   eb = expo(b);
    3070      278949 :   e = ea <= eb ? lim - eb : lim - ea;
    3071      278949 :   shiftr_inplace(a, e);
    3072      278949 :   shiftr_inplace(b, e);
    3073             : 
    3074             :   /* Pi / 2agm(1, 4/Q) ~ log(Q), q = Q * 2^e */
    3075      278949 :   y = gdiv(Pi2n(-1, prec), agm1cx( gdivsg(4, Q), prec ));
    3076      278949 :   a = gel(y,1);
    3077      278949 :   b = gel(y,2);
    3078      278949 :   a = addrr(a, mulsr(-e, mplog2(prec)));
    3079      278949 :   if (realprec(a) <= LOWDEFAULTPREC) a = real_0_bit(expo(a));
    3080      420171 :   if (neg) b = gsigne(b) <= 0? gadd(b, mppi(prec))
    3081      141222 :                              : gsub(b, mppi(prec));
    3082      278949 :   affrr_fixlg(a, gel(z,1));
    3083      278949 :   affrr_fixlg(b, gel(z,2)); return gc_const(av,z);
    3084             : }
    3085             : 
    3086             : GEN
    3087      146002 : mplog(GEN x)
    3088             : {
    3089      146002 :   if (signe(x)<=0) pari_err_DOMAIN("mplog", "argument", "<=", gen_0, x);
    3090      146002 :   return logr_abs(x);
    3091             : }
    3092             : 
    3093             : /* pe = p^e, p prime, 0 < x < pe a t_INT coprime to p. Return the (p-1)-th
    3094             :  * root of 1 in (Z/pe)^* congruent to x mod p, resp x mod 4 if p = 2.
    3095             :  * Simplified form of Zp_sqrtnlift: 1/(p-1) is trivial to compute */
    3096             : GEN
    3097        9933 : Zp_teichmuller(GEN x, GEN p, long e, GEN pe)
    3098             : {
    3099             :   GEN q, z, p1;
    3100             :   pari_sp av;
    3101             :   ulong mask;
    3102        9933 :   if (absequaliu(p,2)) return (mod4(x) & 2)? subiu(pe,1): gen_1;
    3103        9394 :   if (e == 1) return icopy(x);
    3104        9394 :   av = avma;
    3105        9394 :   p1 = subiu(p, 1);
    3106        9393 :   mask = quadratic_prec_mask(e);
    3107        9393 :   q = p; z = remii(x, p);
    3108       31191 :   while (mask > 1)
    3109             :   { /* Newton iteration solving z^{1 - p} = 1, z = x (mod p) */
    3110       21797 :     GEN w, t, qold = q;
    3111       21797 :     if (mask <= 3) /* last iteration */
    3112        9394 :       q = pe;
    3113             :     else
    3114             :     {
    3115       12403 :       q = sqri(q);
    3116       12403 :       if (mask & 1) q = diviiexact(q, p);
    3117             :     }
    3118       21796 :     mask >>= 1;
    3119             :     /* q <= qold^2 */
    3120       21796 :     if (lgefint(q) == 3)
    3121             :     {
    3122       21648 :       ulong Z = uel(z,2), Q = uel(q,2), P1 = uel(p1,2);
    3123       21648 :       ulong W = (Q-1) / P1; /* -1/(p-1) + O(qold) */
    3124       21648 :       ulong T = Fl_mul(W, Fl_powu(Z,P1,Q) - 1, Q);
    3125       21650 :       Z = Fl_mul(Z, 1 + T, Q);
    3126       21650 :       z = utoi(Z);
    3127             :     }
    3128             :     else
    3129             :     {
    3130         148 :       w = diviiexact(subiu(qold,1),p1); /* -1/(p-1) + O(qold) */
    3131         148 :       t = Fp_mul(w, subiu(Fp_pow(z,p1,q), 1), q);
    3132         148 :       z = Fp_mul(z, addui(1,t), q);
    3133             :     }
    3134             :   }
    3135        9394 :   return gerepileuptoint(av, z);
    3136             : }
    3137             : 
    3138             : GEN
    3139        1225 : teichmullerinit(long p, long n)
    3140             : {
    3141             :   GEN t, pn, g, v;
    3142             :   ulong gp, tp;
    3143             :   long a, m;
    3144             : 
    3145        1225 :   if (p == 2) return mkvec(gen_1);
    3146        1225 :   if (!uisprime(p)) pari_err_PRIME("teichmullerinit",utoipos(p));
    3147             : 
    3148        1225 :   m = p >> 1; /* (p-1)/2 */
    3149        1225 :   tp= gp= pgener_Fl(p); /* order (p-1), gp^m = -1 */
    3150        1225 :   pn = powuu(p, n);
    3151        1225 :   v = cgetg(p, t_VEC);
    3152        1225 :   t = g = Zp_teichmuller(utoipos(gp), utoipos(p), n, pn);
    3153        1225 :   gel(v, 1) = gen_1;
    3154        1225 :   gel(v, p-1) = subiu(pn,1);
    3155        3031 :   for (a = 1; a < m; a++)
    3156             :   {
    3157        1806 :     gel(v, tp) = t;
    3158        1806 :     gel(v, p - tp) = Fp_neg(t, pn); /* g^(m+a) = -g^a */
    3159        1806 :     if (a < m-1)
    3160             :     {
    3161        1029 :       t = Fp_mul(t, g, pn); /* g^(a+1) */
    3162        1029 :       tp = Fl_mul(tp, gp, p); /* t mod p  */
    3163             :     }
    3164             :   }
    3165        1225 :   return v;
    3166             : }
    3167             : 
    3168             : /* tab from teichmullerinit or NULL */
    3169             : GEN
    3170        4977 : teichmuller(GEN x, GEN tab)
    3171             : {
    3172             :   GEN p, q, y, z;
    3173        4977 :   long n, tx = typ(x);
    3174             : 
    3175        4977 :   if (!tab)
    3176             :   {
    3177        4865 :     if (tx == t_VEC && lg(x) == 3)
    3178             :     {
    3179           7 :       p = gel(x,1);
    3180           7 :       q = gel(x,2);
    3181           7 :       if (typ(p) == t_INT && typ(q) == t_INT)
    3182           7 :         return teichmullerinit(itos(p), itos(q));
    3183             :     }
    3184             :   }
    3185         112 :   else if (typ(tab) != t_VEC) pari_err_TYPE("teichmuller",tab);
    3186        4970 :   if (tx!=t_PADIC) pari_err_TYPE("teichmuller",x);
    3187        4970 :   z = gel(x,4);
    3188        4970 :   if (!signe(z)) return gcopy(x);
    3189        4970 :   p = gel(x,2);
    3190        4970 :   q = gel(x,3);
    3191        4970 :   n = precp(x);
    3192        4970 :   y = cgetg(5,t_PADIC);
    3193        4970 :   y[1] = evalprecp(n) | _evalvalp(0);
    3194        4970 :   gel(y,2) = icopy(p);
    3195        4970 :   gel(y,3) = icopy(q);
    3196        4970 :   if (tab)
    3197             :   {
    3198         112 :     ulong pp = itou_or_0(p);
    3199         112 :     if (lg(tab) != (long)pp) pari_err_TYPE("teichmuller",tab);
    3200         112 :     z = gel(tab, umodiu(z, pp));
    3201         112 :     if (typ(z) != t_INT) pari_err_TYPE("teichmuller",tab);
    3202         112 :     z = remii(z, q);
    3203             :   }
    3204             :   else
    3205        4858 :     z = Zp_teichmuller(z, p, n, q);
    3206        4970 :   gel(y,4) = z;
    3207        4970 :   return y;
    3208             : }
    3209             : GEN
    3210        4739 : teich(GEN x) { return teichmuller(x, NULL); }
    3211             : 
    3212             : GEN
    3213    16034559 : glog(GEN x, long prec)
    3214             : {
    3215             :   pari_sp av, tetpil;
    3216             :   GEN y, p1;
    3217             :   long l;
    3218             : 
    3219    16034559 :   switch(typ(x))
    3220             :   {
    3221     9394279 :     case t_REAL:
    3222     9394279 :       if (signe(x) >= 0)
    3223             :       {
    3224     7711622 :         if (!signe(x)) pari_err_DOMAIN("log", "argument", "=", gen_0, x);
    3225     7711608 :         return logr_abs(x);
    3226             :       }
    3227     1682657 :       retmkcomplex(logr_abs(x), mppi(realprec(x)));
    3228             : 
    3229      514377 :     case t_FRAC:
    3230             :     {
    3231             :       GEN a, b;
    3232             :       long e1, e2;
    3233      514377 :       av = avma;
    3234      514377 :       a = gel(x,1);
    3235      514377 :       b = gel(x,2);
    3236      514377 :       e1 = expi(subii(a,b)); e2 = expi(b);
    3237      514376 :       if (e2 > e1) prec += nbits2extraprec(e2 - e1);
    3238      514376 :       x = fractor(x, prec);
    3239      514377 :       return gerepileupto(av, glog(x, prec));
    3240             :     }
    3241     3918663 :     case t_COMPLEX:
    3242     3918663 :       if (ismpzero(gel(x,2))) return glog(gel(x,1), prec);
    3243     3908741 :       l = precision(x); if (l > prec) prec = l;
    3244     3908750 :       if (ismpzero(gel(x,1)))
    3245             :       {
    3246       72770 :         GEN a = gel(x,2), b;
    3247       72770 :         av = avma; b = Pi2n(-1,prec);
    3248       72770 :         if (gsigne(a) < 0) { setsigne(b, -1); a = gabs(a,prec); }
    3249       72770 :         a = isint1(a) ? gen_0: glog(a,prec);
    3250       72770 :         return gerepilecopy(av, mkcomplex(a, b));
    3251             :       }
    3252     3835987 :       if (prec >= lg2prec(LOGAGMCX_LIMIT)) return logagmcx(x, prec);
    3253     3557229 :       y = cgetg(3,t_COMPLEX);
    3254     3557226 :       gel(y,2) = garg(x,prec);
    3255     3557248 :       av = avma; p1 = glog(cxnorm(x),prec); tetpil = avma;
    3256     3557243 :       gel(y,1) = gerepile(av,tetpil,gmul2n(p1,-1)); return y;
    3257             : 
    3258         322 :     case t_PADIC: return Qp_log(x);
    3259     2206918 :     default:
    3260     2206918 :       av = avma; if (!(y = toser_i(x))) break;
    3261         140 :       if (!signe(y)) pari_err_DOMAIN("log", "argument", "=", gen_0, x);
    3262         140 :       if (valser(y)) pari_err_DOMAIN("log", "series valuation", "!=", gen_0, x);
    3263         133 :       p1 = integser(gdiv(derivser(y), y)); /* log(y)' = y'/y */
    3264         133 :       if (!gequal1(gel(y,2))) p1 = gadd(p1, glog(gel(y,2),prec));
    3265         133 :       return gerepileupto(av, p1);
    3266             :   }
    3267     2207339 :   return trans_eval("log",glog,x,prec);
    3268             : }
    3269             : 
    3270             : static GEN
    3271          63 : mplog1p(GEN x)
    3272             : {
    3273             :   long ex, a, b, l, L;
    3274          63 :   if (!signe(x)) return rcopy(x);
    3275          63 :   ex = expo(x); if (ex >= -3) return glog(addrs(x,1), 0);
    3276          42 :   a = -ex;
    3277          42 :   b = realprec(x); L = b+1;
    3278          42 :   if (b > a*log2(L) && b > lg2prec(LOGAGM_LIMIT))
    3279             :   {
    3280           0 :     x = addrs(x,1); l = b + nbits2extraprec(a);
    3281           0 :     if (realprec(x) < l) x = rtor(x,l);
    3282           0 :     return logagmr_abs(x);
    3283             :   }
    3284          42 :   x = rtor(x, L);
    3285          42 :   x = logr_aux(divrr(x, addrs(x,2)));
    3286          42 :   if (realprec(x) > b) fixlg(x, b);
    3287          42 :   shiftr_inplace(x,1); return x;
    3288             : }
    3289             : 
    3290             : static GEN log1p_i(GEN x, long prec);
    3291             : static GEN
    3292          14 : cxlog1p(GEN x, long prec)
    3293             : {
    3294             :   pari_sp av;
    3295          14 :   GEN z, a, b = gel(x,2);
    3296             :   long l;
    3297          14 :   if (ismpzero(b)) return log1p_i(gel(x,1), prec);
    3298          14 :   l = precision(x); if (l > prec) prec = l;
    3299          14 :   if (prec >= lg2prec(LOGAGMCX_LIMIT)) return logagmcx(gaddgs(x,1), prec);
    3300          14 :   a = gel(x,1);
    3301          14 :   z = cgetg(3,t_COMPLEX); av = avma;
    3302          14 :   a = gadd(gadd(gmul2n(a,1), gsqr(a)), gsqr(b));
    3303          14 :   a = log1p_i(a, prec); shiftr_inplace(a,-1);
    3304          14 :   gel(z,1) = gerepileupto(av, a);
    3305          14 :   gel(z,2) = garg(gaddgs(x,1),prec); return z;
    3306             : }
    3307             : static GEN
    3308         133 : log1p_i(GEN x, long prec)
    3309             : {
    3310         133 :   switch(typ(x))
    3311             :   {
    3312          63 :     case t_REAL: return mplog1p(x);
    3313          14 :     case t_COMPLEX: return cxlog1p(x, prec);
    3314           7 :     case t_PADIC: return Qp_log(gaddgs(x,1));
    3315          49 :     default:
    3316             :     {
    3317             :       long ey;
    3318             :       GEN y;
    3319          49 :       if (!(y = toser_i(x))) break;
    3320          21 :       ey = valser(y);
    3321          21 :       if (ey < 0) pari_err_DOMAIN("log1p","valuation", "<", gen_0, x);
    3322          21 :       if (gequal0(y)) return gcopy(y);
    3323          14 :       if (ey)
    3324           7 :         return glog(gaddgs(y,1),prec);
    3325             :       else
    3326             :       {
    3327           7 :         GEN a = gel(y,2), a1 = gaddgs(a,1);
    3328           7 :         y = gdiv(y, a1); gel(y,2) = gen_1;
    3329           7 :         return gadd(glog1p(a,prec), glog(y, prec));
    3330             :       }
    3331             :     }
    3332             :   }
    3333          28 :   return trans_eval("log1p",glog1p,x,prec);
    3334             : }
    3335             : GEN
    3336         119 : glog1p(GEN x, long prec)
    3337             : {
    3338         119 :   pari_sp av = avma;
    3339         119 :   return gerepileupto(av, log1p_i(x, prec));
    3340             : }
    3341             : /********************************************************************/
    3342             : /**                                                                **/
    3343             : /**                        SINE, COSINE                            **/
    3344             : /**                                                                **/
    3345             : /********************************************************************/
    3346             : 
    3347             : /* Reduce x0 mod Pi/2 to x in [-Pi/4, Pi/4]. Return cos(x)-1 */
    3348             : static GEN
    3349    10212570 : mpcosm1(GEN x, long *ptmod8)
    3350             : {
    3351    10212570 :   long a = expo(x), l = realprec(x), b, L, i, n, m, B;
    3352             :   GEN y, u, x2;
    3353             :   double d;
    3354             : 
    3355    10212570 :   n = 0;
    3356    10212570 :   if (a >= 0)
    3357             :   {
    3358             :     long p;
    3359             :     GEN q;
    3360     8345835 :     if (a > 30)
    3361             :     {
    3362           7 :       GEN z, P = Pi2n(-2, nbits2prec(a + 32));
    3363           7 :       z = addrr(x,P); /* = x + Pi/4 */
    3364           7 :       if (expo(z) >= bit_prec(z) + 3) pari_err_PREC("mpcosm1");
    3365           7 :       shiftr_inplace(P, 1);
    3366           7 :       q = floorr(divrr(z, P)); /* round ( x / (Pi/2) ) */
    3367           7 :       p = l+EXTRAPREC64; x = rtor(x,p);
    3368             :     } else {
    3369     8345828 :       q = stoi((long)floor(rtodbl(x) / (M_PI/2) + 0.5));
    3370     8345827 :       p = l;
    3371             :     }
    3372     8345993 :     if (signe(q))
    3373             :     {
    3374     8345838 :       GEN y = subrr(x, mulir(q, Pi2n(-1,p))); /* x mod Pi/2  */
    3375     8345613 :       long b = expo(y);
    3376     8345613 :       if (a - b < 7) x = y;
    3377             :       else
    3378             :       {
    3379     4342392 :         p += nbits2extraprec(a-b); x = rtor(x, p);
    3380     4342412 :         x = subrr(x, mulir(q, Pi2n(-1,p)));
    3381             :       }
    3382     8345555 :       a = b;
    3383     8345555 :       if (!signe(x) && a >= 0) pari_err_PREC("mpcosm1");
    3384     8345555 :       n = Mod4(q);
    3385             :     }
    3386             :   }
    3387             :   /* a < 0 */
    3388    10212502 :   b = signe(x); *ptmod8 = (b < 0)? 4 + n: n;
    3389    10212502 :   if (!b) return real_0_bit(expo(x)*2 - 1);
    3390             : 
    3391    10212502 :   b = prec2nbits(l);
    3392    10212491 :   if (b + 2*a <= 0) {
    3393     1356761 :     y = sqrr(x); shiftr_inplace(y, -1); setsigne(y, -1);
    3394     1356761 :     return y;
    3395             :   }
    3396             : 
    3397     8855730 :   y = cgetr(l);
    3398     8855731 :   B = b/6 + BITS_IN_LONG/2 + (BITS_IN_LONG*BITS_IN_LONG/2)/ b;
    3399     8855731 :   d = a/2.; m = (long)(d + sqrt(d*d + B)); /* >= 0 ,*/
    3400     8855731 :   if (m < (-a) * 0.1) m = 0; /* not worth it */
    3401     8855731 :   L = l + nbits2extraprec(m);
    3402             : 
    3403     8855746 :   b += m;
    3404     8855746 :   d = 2.0 * (m-dbllog2r(x)-1/M_LN2); /* ~ 2( - log_2 Y - 1/log(2) ) */
    3405     8855814 :   n = (long)(b / d);
    3406     8855814 :   if (n > 1)
    3407     8797981 :     n = (long)(b / (d + log2((double)n+1))); /* log~constant in small ranges */
    3408    18737953 :   while (n*(d+log2((double)n+1)) < b) n++; /* expect few corrections */
    3409             : 
    3410             :  /* Multiplication is quadratic in this range (l is small, otherwise we
    3411             :   * use logAGM + Newton). Set Y = 2^(-e-a) x, compute truncated series
    3412             :   * sum Y^2k/(2k)!: this costs roughly
    3413             :   *   m b^2 + sum_{k <= n} (2k e + BITS_IN_LONG)^2
    3414             :   *   ~ (b/2e) b^2 / 3  + m b^2
    3415             :   * bit operations with n ~ b/2e, |x| <  2^(1+a), |Y| < 2^(1-e) , m = e+a and
    3416             :   * b bits of accuracy needed, so
    3417             :   *    B := (b / 6 + BITS_IN_LONG/2 + BITS_IN_LONG^2 / 2b) ~ m(m-a)
    3418             :   * we want b ~ 6 m (m-a) or m~b+a hence
    3419             :   *     m = min( a/2 + sqrt(a^2/4 + b/6),  b/2 + a )
    3420             :   * NB: e ~ (b/6)^(1/2) or b/2.
    3421             :   *
    3422             :   * Truncate the sum at k = n (>= 1), the remainder is
    3423             :   * < sum_{k >= n+1} Y^2k / 2k! < Y^(2n+2) / (2n+2)!(1-Y^2) < Y^(2n+2)/(2n+1)!
    3424             :   * We want ... <= Y^2 2^-b, hence -2n log_2 |Y| + log_2 (2n+1)! >= b
    3425             :   *   log n! ~ (n + 1/2) log(n+1) - (n+1) + log(2Pi)/2,
    3426             :   * error bounded by 1/6(n+1) <= 1/12. Finally, we want
    3427             :   * 2n (-1/log(2) - log_2 |Y| + log_2(2n+2)) >= b  */
    3428     8855814 :   x = rtor(x, L); shiftr_inplace(x, -m); setsigne(x, 1);
    3429     8855742 :   x2 = sqrr(x);
    3430     8855745 :   if (n == 1) { u = x2; shiftr_inplace(u, -1); setsigne(u, -1); } /*-Y^2/2*/
    3431             :   else
    3432             :   {
    3433     8855745 :     GEN un = real_1(L);
    3434             :     pari_sp av;
    3435     8855815 :     long s = 0, l1 = nbits2prec((long)(d + n + 16));
    3436             : 
    3437     8855797 :     u = cgetr(L); av = avma;
    3438   111762910 :     for (i = n; i >= 2; i--)
    3439             :     {
    3440             :       GEN t;
    3441   102907261 :       setprec(x2,l1); t = divrunextu(x2, 2*i-1);
    3442   102908110 :       l1 += nbits2extraprec(dvmdsBIL(s - expo(t), &s)<<TWOPOTBITS_IN_LONG);
    3443   102906857 :       if (l1 > L) l1 = L;
    3444   102906857 :       if (i != n) t = mulrr(t,u);
    3445   102908287 :       setprec(un,l1); t = addrr_sign(un,1, t,-signe(t));
    3446   102895017 :       setprec(u,l1); affrr(t,u); set_avma(av);
    3447             :     }
    3448     8855649 :     shiftr_inplace(u, -1); togglesign(u); /* u := -u/2 */
    3449     8855624 :     setprec(x2,L); u = mulrr(x2,u);
    3450             :   }
    3451             :   /* Now u = sum {1<= i <=n} (-1)^i x^(2i) / (2i)! ~ cos(x) - 1 */
    3452    75560140 :   for (i = 1; i <= m; i++)
    3453             :   { /* u = cos(x)-1 <- cos(2x)-1 = 2cos(x)^2 - 2 = 4u + 2u^2*/
    3454    66706476 :     GEN q = sqrr(u);
    3455    66716023 :     shiftr_inplace(u, 1); u = addrr(u, q);
    3456    66706591 :     shiftr_inplace(u, 1);
    3457    66704187 :     if ((i & 31) == 0) u = gerepileuptoleaf((pari_sp)y, u);
    3458             :   }
    3459     8853664 :   affrr_fixlg(u, y); return y;
    3460             : }
    3461             : 
    3462             : /* sqrt (|1 - (1+x)^2|) = sqrt(|x*(x+2)|). Sends cos(x)-1 to |sin(x)| */
    3463             : static GEN
    3464     8516544 : mpaut(GEN x)
    3465             : {
    3466     8516544 :   GEN t = mulrr(x, addsr(2,x)); /* != 0 */
    3467     8516639 :   if (!signe(t)) return real_0_bit(expo(t) >> 1);
    3468     8516639 :   return sqrtr_abs(t);
    3469             : }
    3470             : 
    3471             : /********************************************************************/
    3472             : /**                            COSINE                              **/
    3473             : /********************************************************************/
    3474             : 
    3475             : GEN
    3476     2745068 : mpcos(GEN x)
    3477             : {
    3478             :   long mod8;
    3479             :   pari_sp av;
    3480             :   GEN y, z;
    3481             : 
    3482     2745068 :   if (!signe(x)) {
    3483          75 :     long l = nbits2prec(-expo(x));
    3484          75 :     if (l < LOWDEFAULTPREC) l = LOWDEFAULTPREC;
    3485          75 :     return real_1(l);
    3486             :   }
    3487     2744993 :   av = avma; z = mpcosm1(x,&mod8);
    3488     2744997 :   switch(mod8)
    3489             :   {
    3490      760058 :     case 0: case 4: y = addsr(1,z); break;
    3491      688608 :     case 1: case 7: y = mpaut(z); togglesign(y); break;
    3492      682288 :     case 2: case 6: y = subsr(-1,z); break;
    3493      614043 :     default:        y = mpaut(z); break; /* case 3: case 5: */
    3494             :   }
    3495     2745017 :   return gerepileuptoleaf(av, y);
    3496             : }
    3497             : 
    3498             : /* convert INT or FRAC to REAL, which is later reduced mod 2Pi : avoid
    3499             :  * cancellation */
    3500             : static GEN
    3501       13258 : tofp_safe(GEN x, long prec)
    3502             : {
    3503       13258 :   return (typ(x) == t_INT || gexpo(x) > 0)? gadd(x, real_0(prec))
    3504       26513 :                                           : fractor(x, prec);
    3505             : }
    3506             : 
    3507             : GEN
    3508      154847 : gcos(GEN x, long prec)
    3509             : {
    3510             :   pari_sp av;
    3511             :   GEN a, b, u, v, y, u1, v1;
    3512             :   long i;
    3513             : 
    3514      154847 :   switch(typ(x))
    3515             :   {
    3516      153581 :     case t_REAL: return mpcos(x);
    3517          28 :     case t_COMPLEX:
    3518          28 :       a = gel(x,1);
    3519          28 :       b = gel(x,2);
    3520          28 :       if (isintzero(a)) return gcosh(b, prec);
    3521          14 :       i = precision(x); if (i) prec = i;
    3522          14 :       y = cgetc(prec); av = avma;
    3523          14 :       if (typ(b) != t_REAL) b = gtofp(b, prec);
    3524          14 :       mpsinhcosh(b, &u1, &v1); u1 = mpneg(u1);
    3525          14 :       if (typ(a) != t_REAL) a = gtofp(a, prec);
    3526          14 :       mpsincos(a, &u, &v);
    3527          14 :       affrr_fixlg(gmul(v1,v), gel(y,1));
    3528          14 :       affrr_fixlg(gmul(u1,u), gel(y,2)); return gc_const(av,y);
    3529             : 
    3530        1156 :     case t_INT: case t_FRAC:
    3531        1156 :       y = cgetr(prec); av = avma;
    3532        1156 :       affrr_fixlg(mpcos(tofp_safe(x,prec)), y); return gc_const(av,y);
    3533             : 
    3534          49 :     case t_PADIC: y = cos_p(x);
    3535          49 :       if (!y) pari_err_DOMAIN("gcos(t_PADIC)","argument","",gen_0,x);
    3536          42 :       return y;
    3537             : 
    3538          33 :     default:
    3539          33 :       av = avma; if (!(y = toser_i(x))) break;
    3540          28 :       if (gequal0(y)) return gerepileupto(av, gaddsg(1,y));
    3541          28 :       if (valser(y) < 0)
    3542           7 :         pari_err_DOMAIN("cos","valuation", "<", gen_0, x);
    3543          21 :       gsincos(y,&u,&v,prec);
    3544          21 :       return gerepilecopy(av,v);
    3545             :   }
    3546           7 :   return trans_eval("cos",gcos,x,prec);
    3547             : }
    3548             : /********************************************************************/
    3549             : /**                             SINE                               **/
    3550             : /********************************************************************/
    3551             : 
    3552             : GEN
    3553      826147 : mpsin(GEN x)
    3554             : {
    3555             :   long mod8;
    3556             :   pari_sp av;
    3557             :   GEN y, z;
    3558             : 
    3559      826147 :   if (!signe(x)) return real_0_bit(expo(x));
    3560      825938 :   av = avma; z = mpcosm1(x,&mod8);
    3561      825926 :   switch(mod8)
    3562             :   {
    3563      309975 :     case 0: case 6: y = mpaut(z); break;
    3564      129042 :     case 1: case 5: y = addsr(1,z); break;
    3565      262405 :     case 2: case 4: y = mpaut(z); togglesign(y); break;
    3566      124504 :     default:        y = subsr(-1,z); break; /* case 3: case 7: */
    3567             :   }
    3568      825956 :   return gerepileuptoleaf(av, y);
    3569             : }
    3570             : 
    3571             : GEN
    3572      859081 : gsin(GEN x, long prec)
    3573             : {
    3574             :   pari_sp av;
    3575             :   GEN a, b, u, v, y, v1, u1;
    3576             :   long i;
    3577             : 
    3578      859081 :   switch(typ(x))
    3579             :   {
    3580      820972 :     case t_REAL: return mpsin(x);
    3581       32711 :     case t_COMPLEX:
    3582       32711 :       a = gel(x,1);
    3583       32711 :       b = gel(x,2);
    3584       32711 :       if (isintzero(a)) retmkcomplex(gen_0,gsinh(b,prec));
    3585       17402 :       i = precision(x); if (i) prec = i;
    3586       17402 :       y = cgetc(prec); av = avma;
    3587       17402 :       if (typ(b) != t_REAL) b = gtofp(b, prec);
    3588       17402 :       mpsinhcosh(b, &u1, &v1);
    3589       17402 :       if (typ(a) != t_REAL) a = gtofp(a, prec);
    3590       17402 :       mpsincos(a, &u, &v);
    3591       17402 :       affrr_fixlg(gmul(v1,u), gel(y,1));
    3592       17402 :       affrr_fixlg(gmul(u1,v), gel(y,2)); return gc_const(av,y);
    3593             : 
    3594        5118 :     case t_INT: case t_FRAC:
    3595        5118 :       y = cgetr(prec); av = avma;
    3596        5118 :       affrr_fixlg(mpsin(tofp_safe(x,prec)), y); return gc_const(av,y);
    3597             : 
    3598          49 :     case t_PADIC: y = sin_p(x);
    3599          49 :       if (!y) pari_err_DOMAIN("gsin(t_PADIC)","argument","",gen_0,x);
    3600          42 :       return y;
    3601             : 
    3602         231 :     default:
    3603         231 :       av = avma; if (!(y = toser_i(x))) break;
    3604         224 :       if (gequal0(y)) return gerepilecopy(av, y);
    3605         224 :       if (valser(y) < 0)
    3606           7 :         pari_err_DOMAIN("sin","valuation", "<", gen_0, x);
    3607         217 :       gsincos(y,&u,&v,prec);
    3608         217 :       return gerepilecopy(av,u);
    3609             :   }
    3610           7 :   return trans_eval("sin",gsin,x,prec);
    3611             : }
    3612             : /********************************************************************/
    3613             : /**                       SINE, COSINE together                    **/
    3614             : /********************************************************************/
    3615             : 
    3616             : void
    3617     6639247 : mpsincos(GEN x, GEN *s, GEN *c)
    3618             : {
    3619             :   long mod8;
    3620             :   pari_sp av, tetpil;
    3621             :   GEN z, *gptr[2];
    3622             : 
    3623     6639247 :   if (!signe(x))
    3624             :   {
    3625        3464 :     long e = expo(x);
    3626        3464 :     *s = real_0_bit(e);
    3627        3464 :     *c = e >= 0? real_0_bit(e): real_1_bit(-e);
    3628        3464 :     return;
    3629             :   }
    3630             : 
    3631     6635783 :   av = avma; z = mpcosm1(x, &mod8); tetpil = avma;
    3632     6635877 :   switch(mod8)
    3633             :   {
    3634     1540177 :     case 0: *c = addsr( 1,z); *s = mpaut(z); break;
    3635      444831 :     case 1: *s = addsr( 1,z); *c = mpaut(z); togglesign(*c); break;
    3636      830365 :     case 2: *c = subsr(-1,z); *s = mpaut(z); togglesign(*s); break;
    3637      418332 :     case 3: *s = subsr(-1,z); *c = mpaut(z); break;
    3638      855067 :     case 4: *c = addsr( 1,z); *s = mpaut(z); togglesign(*s); break;
    3639      425903 :     case 5: *s = addsr( 1,z); *c = mpaut(z); break;
    3640     1657647 :     case 6: *c = subsr(-1,z); *s = mpaut(z); break;
    3641      463580 :     case 7: *s = subsr(-1,z); *c = mpaut(z); togglesign(*c); break;
    3642             :   }
    3643     6635867 :   gptr[0] = s; gptr[1] = c; gerepilemanysp(av,tetpil,gptr,2);
    3644             : }
    3645             : 
    3646             : /* SINE and COSINE - 1 */
    3647             : void
    3648        5890 : mpsincosm1(GEN x, GEN *s, GEN *c)
    3649             : {
    3650             :   long mod8;
    3651             :   pari_sp av, tetpil;
    3652             :   GEN z, *gptr[2];
    3653             : 
    3654        5890 :   if (!signe(x))
    3655             :   {
    3656           0 :     long e = expo(x);
    3657           0 :     *s = real_0_bit(e);
    3658           0 :     *c = real_0_bit(2*e-1);
    3659           0 :     return;
    3660             :   }
    3661        5890 :   av = avma; z = mpcosm1(x,&mod8); tetpil = avma;
    3662        5890 :   switch(mod8)
    3663             :   {
    3664        4924 :     case 0: *c = rcopy(z); *s = mpaut(z); break;
    3665          42 :     case 1: *s = addsr(1,z); *c = addrs(mpaut(z),1); togglesign(*c); break;
    3666           0 :     case 2: *c = subsr(-2,z); *s = mpaut(z); togglesign(*s); break;
    3667           0 :     case 3: *s = subsr(-1,z); *c = subrs(mpaut(z),1); break;
    3668         819 :     case 4: *c = rcopy(z); *s = mpaut(z); togglesign(*s); break;
    3669          91 :     case 5: *s = addsr( 1,z); *c = subrs(mpaut(z),1); break;
    3670           7 :     case 6: *c = subsr(-2,z); *s = mpaut(z); break;
    3671           7 :     case 7: *s = subsr(-1,z); *c = subsr(-1,mpaut(z)); break;
    3672             :   }
    3673        5890 :   gptr[0] = s; gptr[1] = c;
    3674        5890 :   gerepilemanysp(av,tetpil,gptr,2);
    3675             : }
    3676             : 
    3677             : /* return exp(ix), x a t_REAL */
    3678             : GEN
    3679      749548 : expIr(GEN x)
    3680             : {
    3681      749548 :   pari_sp av = avma;
    3682      749548 :   GEN v = cgetg(3,t_COMPLEX);
    3683      749549 :   mpsincos(x, (GEN*)(v+2), (GEN*)(v+1));
    3684      749554 :   if (!signe(gel(v,2))) return gerepilecopy(av, gel(v,1));
    3685      747329 :   return v;
    3686             : }
    3687             : 
    3688             : /* return exp(ix)-1, x a t_REAL */
    3689             : static GEN
    3690        5890 : expm1_Ir(GEN x)
    3691             : {
    3692        5890 :   pari_sp av = avma;
    3693        5890 :   GEN v = cgetg(3,t_COMPLEX);
    3694        5890 :   mpsincosm1(x, (GEN*)(v+2), (GEN*)(v+1));
    3695        5890 :   if (!signe(gel(v,2))) return gerepilecopy(av, gel(v,1));
    3696        5890 :   return v;
    3697             : }
    3698             : 
    3699             : /* return exp(z)-1, z complex */
    3700             : GEN
    3701        5946 : cxexpm1(GEN z, long prec)
    3702             : {
    3703        5946 :   pari_sp av = avma;
    3704        5946 :   GEN X, Y, x = real_i(z), y = imag_i(z);
    3705        5946 :   long l = precision(z);
    3706        5946 :   if (l) prec = l;
    3707        5946 :   if (typ(x) != t_REAL) x = gtofp(x, prec);
    3708        5946 :   if (typ(y) != t_REAL) y = gtofp(y, prec);
    3709        5946 :   if (gequal0(y)) return mpexpm1(x);
    3710        5890 :   if (gequal0(x)) return expm1_Ir(y);
    3711        5757 :   X = mpexpm1(x); /* t_REAL */
    3712        5757 :   Y = expm1_Ir(y);
    3713             :   /* exp(x+iy) - 1 = (exp(x)-1)(exp(iy)-1) + exp(x)-1 + exp(iy)-1 */
    3714        5757 :   return gerepileupto(av, gadd(gadd(X,Y), gmul(X,Y)));
    3715             : }
    3716             : 
    3717             : void
    3718     3285369 : gsincos(GEN x, GEN *s, GEN *c, long prec)
    3719             : {
    3720             :   long i, j, ex, ex2, lx, ly, mi;
    3721             :   pari_sp av, tetpil;
    3722             :   GEN y, r, u, v, u1, v1, p1, p2, p3, p4, ps, pc;
    3723             :   GEN *gptr[4];
    3724             : 
    3725     3285369 :   switch(typ(x))
    3726             :   {
    3727        6952 :     case t_INT: case t_FRAC:
    3728        6952 :       *s = cgetr(prec);
    3729        6949 :       *c = cgetr(prec); av = avma;
    3730        6950 :       mpsincos(tofp_safe(x, prec), &ps, &pc);
    3731        6956 :       affrr_fixlg(ps,*s);
    3732     3285491 :       affrr_fixlg(pc,*c); set_avma(av); return;
    3733             : 
    3734     3273810 :     case t_REAL:
    3735     3273810 :       mpsincos(x,s,c); return;
    3736             : 
    3737        4130 :     case t_COMPLEX:
    3738        4130 :       i = precision(x); if (i) prec = i;
    3739        4130 :       ps = cgetc(prec); *s = ps;
    3740        4130 :       pc = cgetc(prec); *c = pc; av = avma;
    3741        4130 :       r = gexp(gel(x,2),prec);
    3742        4130 :       v1 = gmul2n(addrr(invr(r),r), -1); /* = cos(I*Im(x)) */
    3743        4130 :       u1 = subrr(r, v1); /* = I*sin(I*Im(x)) */
    3744        4130 :       gsincos(gel(x,1), &u,&v, prec);
    3745        4130 :       affrr_fixlg(mulrr(v1,u), gel(ps,1));
    3746        4130 :       affrr_fixlg(mulrr(u1,v), gel(ps,2));
    3747        4130 :       affrr_fixlg(mulrr(v1,v), gel(pc,1));
    3748        4130 :       affrr_fixlg(mulrr(u1,u), gel(pc,2)); togglesign(gel(pc,2));
    3749        4130 :       set_avma(av); return;
    3750             : 
    3751           0 :     case t_QUAD:
    3752           0 :       av = avma; gsincos(quadtofp(x, prec), s, c, prec);
    3753           0 :       gerepileall(av, 2, s, c); return;
    3754             : 
    3755         477 :     default:
    3756         477 :       av = avma; if (!(y = toser_i(x))) break;
    3757         504 :       if (gequal0(y)) { *s = gerepilecopy(av,y); *c = gaddsg(1,*s); return; }
    3758             : 
    3759         504 :       ex = valser(y); lx = lg(y); ex2 = 2*ex+2;
    3760         504 :       if (ex < 0) pari_err_DOMAIN("gsincos","valuation", "<", gen_0, x);
    3761         504 :       if (ex2 > lx)
    3762             :       {
    3763          98 :         *s = x == y? gcopy(y): gerepilecopy(av, y); av = avma;
    3764          98 :         *c = gerepileupto(av, gsubsg(1, gdivgu(gsqr(y),2)));
    3765          98 :         return;
    3766             :       }
    3767         406 :       if (!ex)
    3768             :       {
    3769         105 :         gsincos(serchop0(y),&u,&v,prec);
    3770         105 :         gsincos(gel(y,2),&u1,&v1,prec);
    3771         105 :         p1 = gmul(v1,v);
    3772         105 :         p2 = gmul(u1,u);
    3773         105 :         p3 = gmul(v1,u);
    3774         105 :         p4 = gmul(u1,v); tetpil = avma;
    3775         105 :         *c = gsub(p1,p2);
    3776         105 :         *s = gadd(p3,p4);
    3777         105 :         gptr[0]=s; gptr[1]=c;
    3778         105 :         gerepilemanysp(av,tetpil,gptr,2);
    3779         105 :         return;
    3780             :       }
    3781             : 
    3782         301 :       ly = lx+2*ex;
    3783        2842 :       mi = lx-1; while (mi>=3 && isrationalzero(gel(y,mi))) mi--;
    3784         301 :       mi += ex-2;
    3785         301 :       pc = cgetg(ly,t_SER); *c = pc;
    3786         301 :       ps = cgetg(lx,t_SER); *s = ps;
    3787         301 :       pc[1] = evalsigne(1) | _evalvalser(0) | evalvarn(varn(y));
    3788         301 :       gel(pc,2) = gen_1; ps[1] = y[1];
    3789         609 :       for (i=2; i<ex+2; i++) gel(ps,i) = gcopy(gel(y,i));
    3790         616 :       for (i=3; i< ex2; i++) gel(pc,i) = gen_0;
    3791        3339 :       for (i=ex2; i<ly; i++)
    3792             :       {
    3793        3038 :         long ii = i-ex;
    3794        3038 :         av = avma; p1 = gen_0;
    3795        7028 :         for (j=ex; j<=minss(ii-2,mi); j++)
    3796        3990 :           p1 = gadd(p1, gmulgu(gmul(gel(y,j-ex+2),gel(ps,ii-j)),j));
    3797        3038 :         gel(pc,i) = gerepileupto(av, gdivgs(p1,2-i));
    3798        3038 :         if (ii < lx)
    3799             :         {
    3800        2730 :           av = avma; p1 = gen_0;
    3801        5796 :           for (j=ex; j<=minss(i-ex2,mi); j++)
    3802        3066 :             p1 = gadd(p1,gmulgu(gmul(gel(y,j-ex+2),gel(pc,i-j)),j));
    3803        2730 :           p1 = gdivgu(p1,i-2);
    3804        2730 :           gel(ps,ii) = gerepileupto(av, gadd(p1,gel(y,ii)));
    3805             :         }
    3806             :       }
    3807         301 :       return;
    3808             :   }
    3809           0 :   pari_err_TYPE("gsincos",x);
    3810             : }
    3811             : 
    3812             : /********************************************************************/
    3813             : /**                                                                **/
    3814             : /**                              SINC                              **/
    3815             : /**                                                                **/
    3816             : /********************************************************************/
    3817             : static GEN
    3818     2319450 : mpsinc(GEN x)
    3819             : {
    3820     2319450 :   pari_sp av = avma;
    3821             :   GEN s, c;
    3822             : 
    3823     2319450 :   if (!signe(x)) {
    3824           0 :     long l = nbits2prec(-expo(x));
    3825           0 :     if (l < LOWDEFAULTPREC) l = LOWDEFAULTPREC;
    3826           0 :     return real_1(l);
    3827             :   }
    3828             : 
    3829     2319450 :   mpsincos(x,&s,&c);
    3830     2319450 :   return gerepileuptoleaf(av, divrr(s,x));
    3831             : }
    3832             : 
    3833             : GEN
    3834     2319562 : gsinc(GEN x, long prec)
    3835             : {
    3836             :   pari_sp av;
    3837             :   GEN r, u, v, y, u1, v1;
    3838             :   long i;
    3839             : 
    3840     2319562 :   switch(typ(x))
    3841             :   {
    3842     2319429 :     case t_REAL: return mpsinc(x);
    3843          49 :     case t_COMPLEX:
    3844          49 :       if (isintzero(gel(x,1)))
    3845             :       {
    3846          28 :         av = avma; x = gel(x,2);
    3847          28 :         if (gequal0(x)) return gcosh(x,prec);
    3848          14 :         return gerepileuptoleaf(av,gdiv(gsinh(x,prec),x));
    3849             :       }
    3850          21 :       i = precision(x); if (i) prec = i;
    3851          21 :       y = cgetc(prec); av = avma;
    3852          21 :       r = gexp(gel(x,2),prec);
    3853          21 :       v1 = gmul2n(addrr(invr(r),r), -1); /* = cos(I*Im(x)) */
    3854          21 :       u1 = subrr(r, v1); /* = I*sin(I*Im(x)) */
    3855          21 :       gsincos(gel(x,1),&u,&v,prec);
    3856          21 :       affc_fixlg(gdiv(mkcomplex(gmul(v1,u), gmul(u1,v)), x), y);
    3857          21 :       return gc_const(av,y);
    3858             : 
    3859          14 :     case t_INT:
    3860          14 :       if (!signe(x)) return real_1(prec); /*fall through*/
    3861             :     case t_FRAC:
    3862          21 :       y = cgetr(prec); av = avma;
    3863          21 :       affrr_fixlg(mpsinc(tofp_safe(x,prec)), y); return gc_const(av,y);
    3864             : 
    3865          21 :     case t_PADIC:
    3866          21 :       if (gequal0(x)) return cvtop(gen_1, gel(x,2), valp(x));
    3867          14 :       av = avma; y = sin_p(x);
    3868          14 :       if (!y) pari_err_DOMAIN("gsinc(t_PADIC)","argument","",gen_0,x);
    3869           7 :       return gerepileupto(av,gdiv(y,x));
    3870             : 
    3871          35 :     default:
    3872             :     {
    3873             :       long ex;
    3874          35 :       av = avma; if (!(y = toser_i(x))) break;
    3875          35 :       if (gequal0(y)) return gerepileupto(av, gaddsg(1,y));
    3876          35 :       ex = valser(y);
    3877          35 :       if (ex < 0) pari_err_DOMAIN("sinc","valuation", "<", gen_0, x);
    3878          28 :       if (ex)
    3879             :       {
    3880          28 :         gsincos(y,&u,&v,prec);
    3881          28 :         y = gerepileupto(av, gdiv(u,y));
    3882          28 :         if (lg(y) > 2) gel(y,2) = gen_1;
    3883          28 :         return y;
    3884             :       }
    3885             :       else
    3886             :       {
    3887           0 :         GEN z0, y0 = gel(y,2), y1 = serchop0(y), y10 = y1;
    3888           0 :         if (!gequal1(y0)) y10 = gdiv(y10, y0);
    3889           0 :         gsincos(y1,&u,&v,prec);
    3890           0 :         z0 = gdiv(gcos(y0,prec), y0);
    3891           0 :         y = gaddsg(1, y10);
    3892           0 :         u = gadd(gmul(gsinc(y0, prec),v), gmul(z0, u));
    3893           0 :         return gerepileupto(av,gdiv(u,y));
    3894             :       }
    3895             :     }
    3896             :   }
    3897           0 :   return trans_eval("sinc",gsinc,x,prec);
    3898             : }
    3899             : 
    3900             : /********************************************************************/
    3901             : /**                                                                **/
    3902             : /**                     TANGENT and COTANGENT                      **/
    3903             : /**                                                                **/
    3904             : /********************************************************************/
    3905             : static GEN
    3906         133 : mptan(GEN x)
    3907             : {
    3908         133 :   pari_sp av = avma;
    3909             :   GEN s, c;
    3910             : 
    3911         133 :   mpsincos(x,&s,&c);
    3912         133 :   if (!signe(c))
    3913           0 :     pari_err_DOMAIN("tan", "argument", "=", strtoGENstr("Pi/2 + kPi"),x);
    3914         133 :   return gerepileuptoleaf(av, divrr(s,c));
    3915             : }
    3916             : 
    3917             : /* If exp(-|im(x)|) << 1, avoid overflow in sincos(x) */
    3918             : static int
    3919        4018 : tan_huge_im(GEN ix, long prec)
    3920             : {
    3921        4018 :   long b, p = precision(ix);
    3922        4018 :   if (!p) p = prec;
    3923        4018 :   b = prec2nbits(p);
    3924        4018 :   return (gexpo(ix) > b || fabs(gtodouble(ix)) > (M_LN2 / 2) * b);
    3925             : }
    3926             : /* \pm I */
    3927             : static GEN
    3928          35 : real_I(long s, long prec)
    3929             : {
    3930          35 :   GEN z = cgetg(3, t_COMPLEX);
    3931          35 :   gel(z,1) = real_0(prec);
    3932          35 :   gel(z,2) = s > 0? real_1(prec): real_m1(prec); return z;
    3933             : }
    3934             : 
    3935             : GEN
    3936         217 : gtan(GEN x, long prec)
    3937             : {
    3938             :   pari_sp av;
    3939             :   GEN y, s, c;
    3940             : 
    3941         217 :   switch(typ(x))
    3942             :   {
    3943         126 :     case t_REAL: return mptan(x);
    3944             : 
    3945          42 :     case t_COMPLEX: {
    3946          42 :       if (isintzero(gel(x,1))) retmkcomplex(gen_0,gtanh(gel(x,2),prec));
    3947          28 :       if (tan_huge_im(gel(x,2), prec)) return real_I(gsigne(gel(x,2)), prec);
    3948          14 :       av = avma; y = mulcxmI(gtanh(mulcxI(x), prec)); /* tan x = -I th(I x) */
    3949          14 :       gel(y,1) = gcopy(gel(y,1)); return gerepileupto(av, y);
    3950             :     }
    3951           7 :     case t_INT: case t_FRAC:
    3952           7 :       y = cgetr(prec); av = avma;
    3953           7 :       affrr_fixlg(mptan(tofp_safe(x,prec)), y); return gc_const(av,y);
    3954             : 
    3955          14 :     case t_PADIC:
    3956          14 :       av = avma;
    3957          14 :       return gerepileupto(av, gdiv(gsin(x,prec), gcos(x,prec)));
    3958             : 
    3959          28 :     default:
    3960          28 :       av = avma; if (!(y = toser_i(x))) break;
    3961          21 :       if (gequal0(y)) return gerepilecopy(av, y);
    3962          21 :       if (valser(y) < 0)
    3963           7 :         pari_err_DOMAIN("tan","valuation", "<", gen_0, x);
    3964          14 :       gsincos(y,&s,&c,prec);
    3965          14 :       return gerepileupto(av, gdiv(s,c));
    3966             :   }
    3967           7 :   return trans_eval("tan",gtan,x,prec);
    3968             : }
    3969             : 
    3970             : static GEN
    3971          70 : mpcotan(GEN x)
    3972             : {
    3973          70 :   pari_sp av=avma, tetpil;
    3974             :   GEN s,c;
    3975             : 
    3976          70 :   mpsincos(x,&s,&c); tetpil=avma;
    3977          70 :   return gerepile(av,tetpil,divrr(c,s));
    3978             : }
    3979             : 
    3980             : GEN
    3981        4207 : gcotan(GEN x, long prec)
    3982             : {
    3983             :   pari_sp av;
    3984             :   GEN y, s, c;
    3985             : 
    3986        4207 :   switch(typ(x))
    3987             :   {
    3988          63 :     case t_REAL:
    3989          63 :       return mpcotan(x);
    3990             : 
    3991        4011 :     case t_COMPLEX:
    3992        4011 :       if (isintzero(gel(x,1))) {
    3993          21 :         GEN z = cgetg(3, t_COMPLEX);
    3994          21 :         gel(z,1) = gen_0; av = avma;
    3995          21 :         gel(z,2) = gerepileupto(av, gneg(ginv(gtanh(gel(x,2),prec))));
    3996          21 :         return z;
    3997             :       }
    3998        3990 :       if (tan_huge_im(gel(x,2), prec)) return real_I(-gsigne(gel(x,2)), prec);
    3999        3969 :       av = avma; gsincos(x,&s,&c,prec);
    4000        3969 :       return gerepileupto(av, gdiv(c,s));
    4001             : 
    4002           7 :     case t_INT: case t_FRAC:
    4003           7 :       y = cgetr(prec); av = avma;
    4004           7 :       affrr_fixlg(mpcotan(tofp_safe(x,prec)), y); return gc_const(av,y);
    4005             : 
    4006          14 :     case t_PADIC:
    4007          14 :       av = avma;
    4008          14 :       return gerepileupto(av, gdiv(gcos(x,prec), gsin(x,prec)));
    4009             : 
    4010         112 :     default:
    4011         112 :       av = avma; if (!(y = toser_i(x))) break;
    4012         105 :       if (gequal0(y)) pari_err_DOMAIN("cotan", "argument", "=", gen_0, y);
    4013         105 :       if (valser(y) < 0) pari_err_DOMAIN("cotan","valuation", "<", gen_0, x);
    4014          98 :       gsincos(y,&s,&c,prec);
    4015          98 :       return gerepileupto(av, gdiv(c,s));
    4016             :   }
    4017           7 :   return trans_eval("cotan",gcotan,x,prec);
    4018             : }

Generated by: LCOV version 1.14