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 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 - buch2.c (source / functions) Hit Total Coverage
Test: PARI/GP v2.10.0 lcov report (development 20079-8a65571) Lines: 2334 2492 93.7 %
Date: 2017-01-18 05:50:33 Functions: 142 150 94.7 %
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. It is distributed in the hope that it will be useful, but WITHOUT
       8             : ANY WARRANTY WHATSOEVER.
       9             : 
      10             : Check the License for details. You should have received a copy of it, along
      11             : with the package; see the file 'COPYING'. If not, write to the Free Software
      12             : Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */
      13             : #include "pari.h"
      14             : #include "paripriv.h"
      15             : /*******************************************************************/
      16             : /*                                                                 */
      17             : /*         CLASS GROUP AND REGULATOR (McCURLEY, BUCHMANN)          */
      18             : /*                    GENERAL NUMBER FIELDS                        */
      19             : /*                                                                 */
      20             : /*******************************************************************/
      21             : /* get_random_ideal */
      22             : static const long RANDOM_BITS = 4;
      23             : /* Buchall */
      24             : static const double BNF_C1 = 0.0, BNF_C2 = 0.0;
      25             : static const long RELSUP = 5;
      26             : static const long FAIL_DIVISOR = 32;
      27             : static const long MINFAIL = 10;
      28             : /* small_norm */
      29             : static const long BNF_RELPID = 4;
      30             : static const long BMULT = 8;
      31             : static const long maxtry_ELEMENT = 1000*1000;
      32             : static const long maxtry_DEP = 20;
      33             : static const long maxtry_FACT = 500;
      34             : /* rnd_rel */
      35             : static const long RND_REL_RELPID = 1;
      36             : static const long PREVENT_LLL_IN_RND_REL = 1;
      37             : /* random relations */
      38             : static const long MINSFB = 3;
      39             : static const long SFB_MAX = 3;
      40             : static const long DEPSIZESFBMULT = 16;
      41             : static const long DEPSFBDIV = 10;
      42             : /* add_rel_i */
      43             : static const ulong mod_p = 27449UL;
      44             : /* be_honest */
      45             : static const long maxtry_HONEST = 50;
      46             : 
      47             : typedef struct FACT {
      48             :     long pr, ex;
      49             : } FACT;
      50             : 
      51             : typedef struct subFB_t {
      52             :   GEN subFB;
      53             :   struct subFB_t *old;
      54             : } subFB_t;
      55             : 
      56             : /* a factor base contains only non-inert primes
      57             :  * KC = # of P in factor base (p <= n, NP <= n2)
      58             :  * KC2= # of P assumed to generate class group (NP <= n2)
      59             :  *
      60             :  * KCZ = # of rational primes under ideals counted by KC
      61             :  * KCZ2= same for KC2 */
      62             : 
      63             : typedef struct FB_t {
      64             :   GEN FB; /* FB[i] = i-th rational prime used in factor base */
      65             :   GEN LP; /* vector of all prime ideals in FB */
      66             :   GEN *LV; /* LV[p] = vector of P|p, NP <= n2
      67             :             * isclone() is set for LV[p] iff all P|p are in FB
      68             :             * LV[i], i not prime or i > n2, is undefined! */
      69             :   GEN iLP; /* iLP[p] = i such that LV[p] = [LP[i],...] */
      70             :   GEN id2; /* id2[i] = powers of ideal i */
      71             :   GEN L_jid; /* indexes of "useful" prime ideals for rnd_rel */
      72             :   long KC, KCZ, KCZ2;
      73             :   GEN subFB; /* LP o subFB =  part of FB used to build random relations */
      74             :   int sfb_chg; /* need to change subFB ? */
      75             :   int newpow; /* need to compute powFB */
      76             :   GEN perm; /* permutation of LP used to represent relations [updated by
      77             :                hnfspec/hnfadd: dense rows come first] */
      78             :   GEN vecG, G0;
      79             :   GEN idealperm; /* permutation of ideals under field automorphisms */
      80             :   GEN minidx; /* minidx[i] min ideal in orbit of LP[i] under field autom */
      81             :   subFB_t *allsubFB; /* all subFB's used */
      82             :   GEN embperm; /* permutations of the complex embeddings */
      83             :   GEN invs; /* inverse of automorphism */
      84             : } FB_t;
      85             : 
      86             : enum { sfb_CHANGE = 1, sfb_INCREASE = 2 };
      87             : 
      88             : typedef struct REL_t {
      89             :   GEN R; /* relation vector as t_VECSMALL; clone */
      90             :   long nz; /* index of first non-zero elt in R (hash) */
      91             :   GEN m; /* pseudo-minimum yielding the relation; clone */
      92             :   long relorig; /* relation this one is an image of */
      93             :   long relaut; /* automorphim used to compute this relation from the original */
      94             :   GEN junk[3]; /*make sure sizeof(struct) is a power of two.*/
      95             : } REL_t;
      96             : 
      97             : typedef struct RELCACHE_t {
      98             :   REL_t *chk; /* last checkpoint */
      99             :   REL_t *base; /* first rel found */
     100             :   REL_t *last; /* last rel found so far */
     101             :   REL_t *end; /* target for last relation. base <= last <= end */
     102             :   size_t len; /* number of rels pre-allocated in base */
     103             :   long relsup; /* how many linearly dependent relations we allow */
     104             :   GEN basis; /* mod p basis (generating family actually) */
     105             :   ulong missing; /* missing vectors in generating family above */
     106             : } RELCACHE_t;
     107             : 
     108             : typedef struct FP_t {
     109             :   double **q;
     110             :   GEN x;
     111             :   double *y;
     112             :   double *z;
     113             :   double *v;
     114             : } FP_t;
     115             : 
     116             : typedef struct RNDREL_t {
     117             :   GEN Nideal;
     118             :   long jid;
     119             :   GEN ex;
     120             :   GEN m1;
     121             : } RNDREL_t;
     122             : 
     123             : static void
     124           0 : wr_rel(GEN col)
     125             : {
     126           0 :   long i, l = lg(col);
     127           0 :   err_printf("\nrel = ");
     128           0 :   for (i=1; i<l; i++)
     129           0 :     if (col[i]) err_printf("%ld^%ld ",i,col[i]);
     130           0 :   err_printf("\n");
     131           0 : }
     132             : static void
     133           0 : dbg_newrel(RELCACHE_t *cache)
     134             : {
     135           0 :   if (DEBUGLEVEL > 1)
     136             :   {
     137           0 :     err_printf("\n++++ cglob = %ld", cache->last - cache->base);
     138           0 :     wr_rel(cache->last->R);
     139             :   }
     140             :   else
     141           0 :     err_printf("%ld ", cache->last - cache->base);
     142           0 : }
     143             : 
     144             : static void
     145           0 : dbg_cancelrel(long jid, long jdir, GEN col)
     146             : {
     147           0 :   err_printf("relation cancelled: ");
     148           0 :   if (DEBUGLEVEL>3) err_printf("(jid=%ld,jdir=%ld)",jid,jdir);
     149           0 :   wr_rel(col); err_flush();
     150           0 : }
     151             : 
     152             : 
     153             : static void
     154        2044 : delete_cache(RELCACHE_t *M)
     155             : {
     156             :   REL_t *rel;
     157       68743 :   for (rel = M->base+1; rel <= M->last; rel++)
     158             :   {
     159       66699 :     gunclone(rel->R);
     160       66699 :     if (!rel->m) continue;
     161       28181 :     gunclone(rel->m);
     162             :   }
     163        2044 :   pari_free((void*)M->base); M->base = NULL;
     164        2044 : }
     165             : 
     166             : static void
     167        2044 : unclone_subFB(FB_t *F)
     168             : {
     169             :   subFB_t *sub, *subold;
     170        2044 :   GEN id2 = F->id2;
     171             :   long i;
     172             : 
     173        4234 :   for (sub = F->allsubFB; sub; sub = subold)
     174             :   {
     175        2190 :     GEN subFB = sub->subFB;
     176        7445 :     for (i = 1; i < lg(subFB); i++)
     177             :     {
     178        5255 :       long id = subFB[i];
     179        5255 :       if (gel(id2, id) == gen_0) continue;
     180             : 
     181        1208 :       gunclone(gel(id2, id));
     182        1208 :       gel(id2, id) = gen_0;
     183             :     }
     184        2190 :     subold = sub->old;
     185        2190 :     pari_free(sub);
     186             :   }
     187        2044 : }
     188             : 
     189             : static void
     190        2044 : delete_FB(FB_t *F)
     191             : {
     192        2044 :   unclone_subFB(F);
     193        2044 :   gunclone(F->minidx);
     194        2044 :   gunclone(F->idealperm);
     195        2044 : }
     196             : 
     197             : static void
     198        2065 : reallocate(RELCACHE_t *M, long len)
     199             : {
     200        2065 :   REL_t *old = M->base;
     201        2065 :   M->len = len;
     202        2065 :   M->base = (REL_t*)pari_realloc((void*)old, (len+1) * sizeof(REL_t));
     203        2065 :   if (old)
     204             :   {
     205          21 :     size_t last = M->last - old, chk = M->chk - old, end = M->end - old;
     206          21 :     M->last = M->base + last;
     207          21 :     M->chk  = M->base + chk;
     208          21 :     M->end  = M->base + end;
     209             :   }
     210        2065 : }
     211             : 
     212             : #define pr_get_smallp(pr) gel(pr,1)[2]
     213             : 
     214             : /* don't take P|p all other Q|p are already there */
     215             : static int
     216        9086 : bad_subFB(FB_t *F, long t)
     217             : {
     218        9086 :   GEN LP, P = gel(F->LP,t);
     219        9086 :   long p = pr_get_smallp(P);
     220        9086 :   LP = F->LV[p];
     221        9086 :   return (isclone(LP) && t == F->iLP[p] + lg(LP)-1);
     222             : }
     223             : 
     224             : static void
     225        2190 : assign_subFB(FB_t *F, GEN yes, long iyes)
     226             : {
     227             :   subFB_t *sub;
     228             :   long i, lv;
     229             : 
     230             :   /* single malloc for struct + GEN */
     231        2190 :   lv = sizeof(subFB_t) + iyes*sizeof(long);
     232        2190 :   sub = (subFB_t *)pari_malloc(lv);
     233        2190 :   sub->subFB = (GEN)&sub[1];
     234        2190 :   sub->old = F->allsubFB;
     235        2190 :   F->allsubFB = sub;
     236        2190 :   for (i = 0; i < iyes; i++) sub->subFB[i] = yes[i];
     237        2190 :   F->subFB = sub->subFB;
     238        2190 :   F->newpow = 1;
     239        2190 : }
     240             : 
     241             : /*
     242             :  * Determine the permutation of the ideals made by each field automorphism.
     243             :  */
     244             : static void
     245        2044 : FB_aut_perm(FB_t *F, GEN auts, GEN cyclic)
     246             : {
     247        2044 :   pari_sp av0 = avma;
     248        2044 :   long i, KC = F->KC, nauts = lg(auts);
     249        2044 :   GEN minidx = zero_Flv(KC), perm = zero_Flm_copy(KC, nauts-1);
     250             : 
     251        2044 :   if (nauts == 1)
     252             :   {
     253         440 :     for (i = 1; i <= KC; i++) minidx[i] = i;
     254             :   }
     255             :   else
     256             :   {
     257             :     long j, m;
     258        4050 :     for (m = 1; m < lg(cyclic); m++)
     259             :     {
     260        2446 :       GEN thiscyc = gel(cyclic, m);
     261        2446 :       long k0 = thiscyc[1];
     262        2446 :       GEN aut = gel(auts, k0), permk0 = gel(perm, k0), ppermk;
     263        2446 :       i = 1;
     264       22003 :       while (i <= KC)
     265             :       {
     266       17111 :         pari_sp av2 = avma;
     267       17111 :         GEN seen = zero_Flv(KC), P = gel(F->LP, i);
     268       17111 :         long imin = i, p, f, l;
     269       17111 :         p = pr_get_p(P)[2];
     270       17111 :         f = pr_get_f(P);
     271             :         do
     272             :         {
     273       68575 :           if (++i > KC) break;
     274       66129 :           P = gel(F->LP, i);
     275             :         }
     276       66129 :         while (p == pr_get_p(P)[2] && f == pr_get_f(P));
     277       85686 :         for (j = imin; j < i; j++)
     278             :         {
     279       68575 :           GEN img = ZM_ZC_mul(aut, pr_get_gen(gel(F->LP, j)));
     280      288200 :           for (l = imin; l < i; l++)
     281      288200 :             if (!seen[l] && ZC_prdvd(img, gel(F->LP, l)))
     282             :             {
     283       68575 :               seen[l] = 1; permk0[j] = l; break;
     284             :             }
     285             :         }
     286       17111 :         avma = av2;
     287             :       }
     288        3118 :       for (ppermk = permk0, i = 2; i < lg(thiscyc); i++)
     289             :       {
     290         672 :         GEN permk = gel(perm, thiscyc[i]);
     291         672 :         for (j = 1; j <= KC; j++) permk[j] = permk0[ppermk[j]];
     292         672 :         ppermk = permk;
     293             :       }
     294             :     }
     295       27183 :     for (j = 1; j <= KC; j++)
     296             :     {
     297       25579 :       if (minidx[j]) continue;
     298        9367 :       minidx[j] = j;
     299        9367 :       for (i = 1; i < nauts; i++) minidx[coeff(perm, j, i)] = j;
     300             :     }
     301             :   }
     302        2044 :   F->minidx = gclone(minidx);
     303        2044 :   F->idealperm = gclone(perm);
     304        2044 :   avma = av0;
     305        2044 : }
     306             : 
     307             : /* set subFB.
     308             :  * Fill F->perm (if != NULL): primes ideals sorted by increasing norm (except
     309             :  * the ones in subFB come first [dense rows for hnfspec]) */
     310             : static int
     311        2044 : subFBgen(FB_t *F, GEN auts, GEN cyclic, double PROD, long minsFB)
     312             : {
     313             :   GEN y, perm, yes, no;
     314        2044 :   long i, j, k, iyes, ino, lv = F->KC + 1;
     315             :   double prod;
     316             :   pari_sp av;
     317             : 
     318        2044 :   F->LP   = cgetg(lv, t_VEC);
     319        2044 :   F->L_jid = F->perm = cgetg(lv, t_VECSMALL);
     320        2044 :   av = avma;
     321        2044 :   y = cgetg(lv,t_COL); /* Norm P */
     322       16631 :   for (k=0, i=1; i <= F->KCZ; i++)
     323             :   {
     324       14587 :     GEN LP = F->LV[F->FB[i]];
     325       14587 :     long l = lg(LP);
     326       48759 :     for (j = 1; j < l; j++)
     327             :     {
     328       34172 :       GEN P = gel(LP,j);
     329       34172 :       k++;
     330       34172 :       gel(y,k) = pr_norm(P);
     331       34172 :       gel(F->LP,k) = P;
     332             :     }
     333             :   }
     334             :   /* perm sorts LP by increasing norm */
     335        2044 :   perm = indexsort(y);
     336        2044 :   no  = cgetg(lv, t_VECSMALL); ino  = 1;
     337        2044 :   yes = cgetg(lv, t_VECSMALL); iyes = 1;
     338        2044 :   prod = 1.0;
     339        9954 :   for (i = 1; i < lv; i++)
     340             :   {
     341        9086 :     long t = perm[i];
     342        9086 :     if (bad_subFB(F, t)) { no[ino++] = t; continue; }
     343             : 
     344        4789 :     yes[iyes++] = t;
     345        4789 :     prod *= (double)itos(gel(y,t));
     346        4789 :     if (iyes > minsFB && prod > PROD) break;
     347             :   }
     348        2044 :   setlg(yes, iyes);
     349        2044 :   for (j=1; j<iyes; j++)     F->perm[j] = yes[j];
     350        2044 :   for (i=1; i<ino; i++, j++) F->perm[j] =  no[i];
     351        2044 :   for (   ; j<lv; j++)       F->perm[j] =  perm[j];
     352        2044 :   F->allsubFB = NULL;
     353        2044 :   FB_aut_perm(F, auts, cyclic);
     354        2044 :   if (iyes) assign_subFB(F, yes, iyes);
     355        2044 :   avma = av; return 1;
     356             : }
     357             : static int
     358         461 : subFB_change(FB_t *F)
     359             : {
     360         461 :   long i, iyes, minsFB, lv = F->KC + 1, l = lg(F->subFB)-1;
     361         461 :   pari_sp av = avma;
     362         461 :   GEN yes, L_jid = F->L_jid, present = zero_zv(lv-1);
     363             : 
     364         461 :   switch (F->sfb_chg)
     365             :   {
     366          21 :     case sfb_INCREASE: minsFB = l + 1; break;
     367         440 :     default: minsFB = l; break;
     368             :   }
     369             : 
     370         461 :   yes = cgetg(minsFB+1, t_VECSMALL); iyes = 1;
     371         461 :   if (L_jid)
     372             :   {
     373        1432 :     for (i = 1; i < lg(L_jid); i++)
     374             :     {
     375        1236 :       long l = L_jid[i];
     376        1236 :       yes[iyes++] = l;
     377        1236 :       present[l] = 1;
     378        1236 :       if (iyes > minsFB) break;
     379             :     }
     380             :   }
     381           0 :   else i = 1;
     382         461 :   if (iyes <= minsFB)
     383             :   {
     384         315 :     for ( ; i < lv; i++)
     385             :     {
     386         315 :       long l = F->perm[i];
     387         315 :       if (present[l]) continue;
     388         315 :       yes[iyes++] = l;
     389         315 :       if (iyes > minsFB) break;
     390             :     }
     391         196 :     if (i == lv) return 0;
     392             :   }
     393         461 :   if (zv_equal(F->subFB, yes))
     394             :   {
     395         315 :     if (DEBUGLEVEL) err_printf("\n*** NOT Changing sub factor base\n");
     396             :   }
     397             :   else
     398             :   {
     399         146 :     if (DEBUGLEVEL) err_printf("\n*** Changing sub factor base\n");
     400         146 :     assign_subFB(F, yes, iyes);
     401             :   }
     402         461 :   F->sfb_chg = 0;
     403         461 :   avma = av; return 1;
     404             : }
     405             : 
     406             : static GEN
     407       15225 : init_famat(GEN x) { return mkvec2(x, cgetg(1,t_MAT)); }
     408             : 
     409             : static GEN
     410        3071 : red(GEN nf, GEN I, GEN G0, GEN *pm)
     411             : {
     412             :   GEN m, y, norm, norm2;
     413        3071 :   norm = typ(I) == t_MAT ? ZM_det_triangular(I) : idealnorm(nf, I);
     414        3071 :   y = idealred0(nf, init_famat(I), G0);
     415        3071 :   m = gel(y,2);
     416        3071 :   y = gel(y,1); *pm = lg(m)==1? gen_1: Q_primpart(gmael(m, 1, 1));
     417        3071 :   norm2 = typ(y) == t_MAT ? ZM_det_triangular(y) : idealnorm(nf, y);
     418        3071 :   if (gcmp(norm, norm2) < 0 || is_pm1(gcoeff(y,1,1)))
     419             :   {
     420        1231 :     *pm = gen_1;
     421        1231 :     y = I;
     422             :   }
     423        3071 :   return idealtwoelt(nf,y);
     424             : }
     425             : 
     426             : /* make sure enough room to store n more relations */
     427             : static void
     428       19415 : pre_allocate(RELCACHE_t *cache, size_t n)
     429             : {
     430       19415 :   size_t len = (cache->last - cache->base) + n;
     431       19415 :   if (len >= cache->len) reallocate(cache, len << 1);
     432       19415 : }
     433             : 
     434             : void
     435       42832 : init_GRHcheck(GRHcheck_t *S, long N, long R1, double LOGD)
     436             : {
     437       42832 :   const double c1 = M_PI*M_PI/2;
     438       42832 :   const double c2 = 3.663862376709;
     439       42832 :   const double c3 = 3.801387092431; /* Euler + log(8*Pi)*/
     440       42832 :   S->clone = 0;
     441       42832 :   S->cN = R1*c2 + N*c1;
     442       42832 :   S->cD = LOGD - N*c3 - R1*M_PI/2;
     443       42832 :   S->maxprimes = 16000; /* sufficient for LIMC=176081*/
     444       42832 :   S->primes = (GRHprime_t*)pari_malloc(S->maxprimes*sizeof(*S->primes));
     445       42832 :   S->nprimes = 0;
     446       42832 :   S->limp = 0;
     447       42832 :   u_forprime_init(&S->P, 2, ULONG_MAX);
     448       42832 : }
     449             : 
     450             : void
     451       42832 : free_GRHcheck(GRHcheck_t *S)
     452             : {
     453       42832 :   if (S->clone)
     454             :   {
     455        1897 :     long i = S->nprimes;
     456             :     GRHprime_t *pr;
     457        1897 :     for (pr = S->primes, i = S->nprimes; i > 0; pr++, i--) gunclone(pr->dec);
     458             :   }
     459       42832 :   pari_free(S->primes);
     460       42832 : }
     461             : 
     462             : int
     463      423301 : GRHok(GRHcheck_t *S, double L, double SA, double SB)
     464             : {
     465      423301 :   return (S->cD + (S->cN + 2*SB) / L - 2*SA < -1e-8);
     466             : }
     467             : 
     468             : /* Return factorization pattern of p: [f,n], where n[i] primes of
     469             :  * residue degree f[i] */
     470             : static GEN
     471      306712 : get_fs(GEN nf, GEN P, GEN index, ulong p)
     472             : {
     473             :   long j, k, f, n, l;
     474             :   GEN fs, ns;
     475             : 
     476      306712 :   if (umodiu(index, p))
     477             :   { /* easy case: p does not divide index */
     478      305088 :     GEN F = Flx_degfact(ZX_to_Flx(P,p), p);
     479      305088 :     fs = gel(F,1); l = lg(fs);
     480             :   }
     481             :   else
     482             :   {
     483        1624 :     GEN F = idealprimedec(nf, utoipos(p));
     484        1624 :     l = lg(F);
     485        1624 :     fs = cgetg(l, t_VECSMALL);
     486        1624 :     for (j = 1; j < l; j++) fs[j] = pr_get_f(gel(F,j));
     487             :   }
     488      306712 :   ns = cgetg(l, t_VECSMALL);
     489      306712 :   f = fs[1]; n = 1;
     490      704847 :   for (j = 2, k = 1; j < l; j++)
     491      398135 :     if (fs[j] == f)
     492      345023 :       n++;
     493             :     else
     494             :     {
     495       53112 :       ns[k] = n; fs[k] = f; k++;
     496       53112 :       f = fs[j]; n = 1;
     497             :     }
     498      306712 :   ns[k] = n; fs[k] = f; k++;
     499      306712 :   setlg(fs, k);
     500      306712 :   setlg(ns, k); return mkvec2(fs,ns);
     501             : }
     502             : 
     503             : /* cache data for all rational primes up to the LIM */
     504             : static void
     505       37159 : cache_prime_dec(GRHcheck_t *S, ulong LIM, GEN nf)
     506             : {
     507       37159 :   pari_sp av = avma;
     508             :   GRHprime_t *pr;
     509             :   GEN index, P;
     510             :   double nb;
     511             : 
     512       74318 :   if (S->limp >= LIM) return;
     513       11335 :   S->clone = 1;
     514       11335 :   nb = primepi_upper_bound((double)LIM); /* #{p <= LIM} <= nb */
     515       11335 :   GRH_ensure(S, nb+1); /* room for one extra prime */
     516       11335 :   P = nf_get_pol(nf);
     517       11335 :   index = nf_get_index(nf);
     518       11335 :   for (pr = S->primes + S->nprimes;;)
     519             :   {
     520      306712 :     ulong p = u_forprime_next(&(S->P));
     521      306712 :     pr->p = p;
     522      306712 :     pr->logp = log((double)p);
     523      306712 :     pr->dec = gclone(get_fs(nf, P, index, p));
     524      306712 :     S->nprimes++;
     525      306712 :     pr++;
     526      306712 :     avma = av;
     527             :     /* store up to nextprime(LIM) included */
     528      306712 :     if (p >= LIM) { S->limp = p; break; }
     529      295377 :   }
     530             : }
     531             : 
     532             : static double
     533       69304 : tailresback(long R1, long R2, double rK, long C, double C2, double C3, double r1K, double r2K, double logC, double logC2, double logC3)
     534             : {
     535       69304 :   const double  rQ = 1.83787706641;
     536       69304 :   const double r1Q = 1.98505372441;
     537       69304 :   const double r2Q = 1.07991541347;
     538      138608 :   return fabs((R1+R2-1)*(12*logC3+4*logC2-9*logC-6)/(2*C*logC3)
     539       69304 :          + (rK-rQ)*(6*logC2 + 5*logC + 2)/(C*logC3)
     540       69304 :          - R2*(6*logC2+11*logC+6)/(C2*logC2)
     541       69304 :          - 2*(r1K-r1Q)*(3*logC2 + 4*logC + 2)/(C2*logC3)
     542       69304 :          + (R1+R2-1)*(12*logC3+40*logC2+45*logC+18)/(6*C3*logC3)
     543       69304 :          + (r2K-r2Q)*(2*logC2 + 3*logC + 2)/(C3*logC3));
     544             : }
     545             : 
     546             : static double
     547       34652 : tailres(long R1, long R2, double al2K, double rKm, double rKM, double r1Km,
     548             :         double r1KM, double r2Km, double r2KM, double C, long i)
     549             : {
     550             :   /* C >= 3*2^i, lower bound for eint1(log(C)/2) */
     551             :   /* for(i=0,30,print(eint1(log(3*2^i)/2))) */
     552             :   static double tab[] = {
     553             :     0.50409264803,
     554             :     0.26205336997,
     555             :     0.14815491171,
     556             :     0.08770540561,
     557             :     0.05347651832,
     558             :     0.03328934284,
     559             :     0.02104510690,
     560             :     0.01346475900,
     561             :     0.00869778586,
     562             :     0.00566279855,
     563             :     0.00371111950,
     564             :     0.00244567837,
     565             :     0.00161948049,
     566             :     0.00107686891,
     567             :     0.00071868750,
     568             :     0.00048119961,
     569             :     0.00032312188,
     570             :     0.00021753772,
     571             :     0.00014679818,
     572             :     9.9272855581E-5,
     573             :     6.7263969995E-5,
     574             :     4.5656812967E-5,
     575             :     3.1041124593E-5,
     576             :     2.1136011590E-5,
     577             :     1.4411645381E-5,
     578             :     9.8393304088E-6,
     579             :     6.7257395409E-6,
     580             :     4.6025878272E-6,
     581             :     3.1529719271E-6,
     582             :     2.1620490021E-6,
     583             :     1.4839266071E-6
     584             :   };
     585       34652 :   const double logC = log(C), logC2 = logC*logC, logC3 = logC*logC2;
     586       34652 :   const double C2 = C*C, C3 = C*C2;
     587       34652 :   double E1 = i >30? 0: tab[i];
     588       69304 :   return al2K*((33*logC2+22*logC+8)/(8*logC3*sqrt(C))+15*E1/16)
     589       69304 :     + maxdd(tailresback(rKm,r1KM,r2Km, C,C2,C3,R1,R2,logC,logC2,logC3),
     590       34652 :             tailresback(rKM,r1Km,r2KM, C,C2,C3,R1,R2,logC,logC2,logC3))/2
     591       34652 :     + ((R1+R2-1)*4*C+R2)*(C2+6*logC)/(4*C2*C2*logC2);
     592             : }
     593             : 
     594             : static long
     595        1897 : primeneeded(long N, long R1, long R2, double LOGD)
     596             : {
     597        1897 :   const double lim = 0.25; /* should be log(2)/2 == 0.34657... */
     598        1897 :   const double al2K =  0.3526*LOGD - 0.8212*N + 4.5007;
     599        1897 :   const double  rKm = -1.0155*LOGD + 2.1042*N - 8.3419;
     600        1897 :   const double  rKM = -0.5   *LOGD + 1.2076*N + 1;
     601        1897 :   const double r1Km = -       LOGD + 1.4150*N;
     602        1897 :   const double r1KM = -       LOGD + 1.9851*N;
     603        1897 :   const double r2Km = -       LOGD + 0.9151*N;
     604        1897 :   const double r2KM = -       LOGD + 1.0800*N;
     605        1897 :   long Cmin = 3, Cmax = 3, i = 0;
     606       19468 :   while (tailres(R1, R2, al2K, rKm, rKM, r1Km, r1KM, r2Km, r2KM, Cmax, i) > lim)
     607             :   {
     608       15674 :     Cmin = Cmax;
     609       15674 :     Cmax *= 2;
     610       15674 :     i++;
     611             :   }
     612        1897 :   i--;
     613       20875 :   while (Cmax - Cmin > 1)
     614             :   {
     615       17081 :     long t = (Cmin + Cmax)/2;
     616       17081 :     if (tailres(R1, R2, al2K, rKm, rKM, r1Km, r1KM, r2Km, r2KM, t, i) > lim)
     617       11577 :       Cmin = t;
     618             :     else
     619        5504 :       Cmax = t;
     620             :   }
     621        1897 :   return Cmax;
     622             : }
     623             : 
     624             : /*
     625             :   for (; i > 0; pr++, i--)
     626             :   {
     627             :     GEN dec, a = NULL, b = NULL, fs, ns;
     628             :     long j, k, limp = (long)(llimc/pr->logp);
     629             :     ulong p = pr->p;
     630             :     dec = pr->dec;
     631             :     fs = gel(dec, 1); ns = gel(dec, 2);
     632             :     k = lg(fs);
     633             :     for (j = 1; j < k; j++)
     634             :     {
     635             :       long f, nb;
     636             :       GEN nor;
     637             :       f = fs[j]; if (f > limp) continue;
     638             :       nb = ns[j];
     639             :       nor = powuu(p, f);
     640             :       if (a)
     641             :       {
     642             :         a = mulii(a, powiu(nor, nb));
     643             :         b = mulii(b, powiu(subii(nor, gen_1), nb));
     644             :       }
     645             :       else
     646             :       {
     647             :         a = powuu(p, f*nb-1);
     648             :         b = diviuexact(powiu(subii(nor, gen_1), nb), p-1);
     649             :       }
     650             :     }
     651             :     if (a)
     652             :       invres = divri(mulir(b, invres), a);
     653             :     else
     654             :       invres = divru(mulur(p, invres), p-1);
     655             :   }
     656             : */
     657             : 
     658             : static GEN
     659        1897 : compute_invres(GRHcheck_t *S, long LIMC)
     660             : {
     661        1897 :   pari_sp av = avma;
     662        1897 :   double loginvres = 0.;
     663             :   GRHprime_t *pr;
     664             :   long i;
     665        1897 :   double logLIMC = log((double)LIMC);
     666        1897 :   double logLIMC2 = logLIMC*logLIMC, denc;
     667             :   double c0, c1, c2;
     668        1897 :   denc = 1/(pow((double)LIMC, 3.) * logLIMC * logLIMC2);
     669        1897 :   c2 = (    logLIMC2 + 3 * logLIMC / 2 + 1) * denc;
     670        1897 :   denc *= LIMC;
     671        1897 :   c1 = (3 * logLIMC2 + 4 * logLIMC     + 2) * denc;
     672        1897 :   denc *= LIMC;
     673        1897 :   c0 = (3 * logLIMC2 + 5 * logLIMC / 2 + 1) * denc;
     674      306908 :   for (pr = S->primes, i = S->nprimes; i > 0; pr++, i--)
     675             :   {
     676             :     GEN dec, fs, ns;
     677             :     long addpsi;
     678             :     double addpsi1, addpsi2;
     679      306712 :     double logp = pr->logp, NPk;
     680      306712 :     long j, k, limp = logLIMC/logp;
     681      306712 :     ulong p = pr->p, p2 = p*p;
     682      306712 :     if (limp < 1) break;
     683      305011 :     dec = pr->dec;
     684      305011 :     fs = gel(dec, 1); ns = gel(dec, 2);
     685      305011 :     loginvres += 1./p;
     686             :     /*
     687             :      * note for optimization: limp == 1 nearly always and limp >= 3 for
     688             :      * only very few primes.
     689             :      */
     690      349006 :     for (k = 2, NPk = p; k <= limp; k++)
     691             :     {
     692       43995 :       NPk *= p;
     693       43995 :       loginvres += 1/(k * NPk);
     694             :     }
     695      305011 :     addpsi = limp;
     696      305011 :     addpsi1 = p *(pow((double)p , (double)limp)-1)/(p -1);
     697      305011 :     addpsi2 = p2*(pow((double)p2, (double)limp)-1)/(p2-1);
     698      305011 :     j = lg(fs);
     699      967872 :     while (--j > 0)
     700             :     {
     701             :       long f, nb, kmax;
     702             :       double NP, NP2, addinvres;
     703      357850 :       f = fs[j]; if (f > limp) continue;
     704      138469 :       nb = ns[j];
     705      138469 :       NP = pow((double)p, (double)f);
     706      138469 :       addinvres = 1/NP;
     707      138469 :       kmax = limp / f;
     708      164991 :       for (k = 2, NPk = NP; k <= kmax; k++)
     709             :       {
     710       26522 :         NPk *= NP;
     711       26522 :         addinvres += 1/(k*NPk);
     712             :       }
     713      138469 :       NP2 = NP*NP;
     714      138469 :       loginvres -= nb * addinvres;
     715      138469 :       addpsi -= nb * f * kmax;
     716      138469 :       addpsi1 -= nb*(f*NP *(pow(NP ,(double)kmax)-1)/(NP -1));
     717      138469 :       addpsi2 -= nb*(f*NP2*(pow(NP2,(double)kmax)-1)/(NP2-1));
     718             :     }
     719      305011 :     loginvres -= (addpsi*c0 - addpsi1*c1 + addpsi2*c2)*logp;
     720             :   }
     721        1897 :   return gerepileuptoleaf(av, mpexp(dbltor(loginvres)));
     722             : }
     723             : 
     724             : static long
     725        3794 : nthideal(GRHcheck_t *S, GEN nf, long n)
     726             : {
     727        3794 :   pari_sp av = avma;
     728        3794 :   GEN P = nf_get_pol(nf);
     729        3794 :   ulong p = 0, *vecN = (ulong*)const_vecsmall(n, LONG_MAX);
     730        3794 :   long i, res, N = poldegree(P, -1);
     731       15630 :   for (i = 0; ; i++)
     732             :   {
     733             :     GRHprime_t *pr;
     734             :     GEN fs;
     735       15630 :     cache_prime_dec(S, p+1, nf);
     736       15630 :     pr = S->primes + i;
     737       15630 :     fs = gel(pr->dec, 1);
     738       15630 :     p = pr->p;
     739       15630 :     if (fs[1] != N)
     740             :     {
     741       12218 :       GEN ns = gel(pr->dec, 2);
     742       12218 :       long k, l, j = lg(fs);
     743       38737 :       while (--j > 0)
     744             :       {
     745       14301 :         ulong NP = upowuu(p, fs[j]);
     746             :         long nf;
     747       14301 :         if (!NP) continue;
     748       14301 :         for (k = 1; k <= n; k++) if (vecN[k] > NP) break;
     749       14301 :         if (k > n) continue;
     750             :         /* vecN[k] <= NP */
     751        7629 :         nf = ns[j]; /*#{primes of norme NP} = nf, insert them here*/
     752        7629 :         for (l = k+nf; l <= n; l++) vecN[l] = vecN[l-nf];
     753        7629 :         for (l = 0; l < nf && k+l <= n; l++) vecN[k+l] = NP;
     754        7629 :         while (l <= k) vecN[l++] = NP;
     755             :       }
     756             :     }
     757       15630 :     if (p > vecN[n]) break;
     758       11836 :   }
     759        3794 :   res = vecN[n]; avma = av; return res;
     760             : }
     761             : 
     762             : 
     763             : /* Compute FB, LV, iLP + KC*. Reset perm
     764             :  * C2: bound for norm of tested prime ideals (includes be_honest())
     765             :  * C1: bound for p, such that P|p (NP <= C2) used to build relations */
     766             : static void
     767        2044 : FBgen(FB_t *F, GEN nf, long N, ulong C1, ulong C2, GRHcheck_t *S)
     768             : {
     769             :   GRHprime_t *pr;
     770             :   long i, ip;
     771             :   GEN prim;
     772        2044 :   const double L = log((double)C2 + 0.5);
     773             : 
     774        2044 :   cache_prime_dec(S, C2, nf);
     775        2044 :   pr = S->primes;
     776        2044 :   F->sfb_chg = 0;
     777        2044 :   F->FB  = cgetg(C2+1, t_VECSMALL);
     778        2044 :   F->iLP = cgetg(C2+1, t_VECSMALL);
     779        2044 :   F->LV = (GEN*)const_vec(C2, NULL);
     780             : 
     781        2044 :   prim = icopy(gen_1);
     782        2044 :   i = ip = 0;
     783        2044 :   F->KC = F->KCZ = 0;
     784       34335 :   for (;; pr++) /* p <= C2 */
     785             :   {
     786       36379 :     ulong p = pr->p;
     787             :     long k, l, m;
     788             :     GEN LP, nb, f;
     789             : 
     790       36379 :     if (!F->KC && p > C1) { F->KCZ = i; F->KC = ip; }
     791       36379 :     if (p > C2) break;
     792             : 
     793       35224 :     if (DEBUGLEVEL>1) { err_printf(" %ld",p); err_flush(); }
     794             : 
     795       35224 :     f = gel(pr->dec, 1); nb = gel(pr->dec, 2);
     796       35224 :     if (f[1] == N)
     797             :     {
     798        7304 :       if (p == C2) break;
     799        7108 :       continue; /* p inert */
     800             :     }/* compute l such that p^f <= C2  <=> f <= l */
     801       27920 :     l = (long)(L/pr->logp);
     802       27920 :     for (k=0, m=1; m < lg(f) && f[m]<=l; m++) k += nb[m];
     803       27920 :     if (!k) /* p too inert to appear in FB */
     804             :     {
     805       13326 :       if (p == C2) break;
     806       13284 :       continue;
     807             :     }
     808       14594 :     prim[2] = p; LP = idealprimedec_limit_f(nf,prim, l);
     809             :     /* keep non-inert ideals with Norm <= C2 */
     810       14594 :     if (m == lg(f)) setisclone(LP); /* flag it: all prime divisors in FB */
     811       14594 :     F->FB[++i]= p;
     812       14594 :     F->LV[p]  = LP;
     813       14594 :     F->iLP[p] = ip; ip += k;
     814       14594 :     if (p == C2) break;
     815       34335 :   }
     816        2044 :   if (!F->KC) { F->KCZ = i; F->KC = ip; }
     817             :   /* Note F->KC > 0 otherwise GRHchk is false */
     818        2044 :   setlg(F->FB, F->KCZ+1); F->KCZ2 = i;
     819        2044 :   if (DEBUGLEVEL>1)
     820             :   {
     821           0 :     err_printf("\n");
     822           0 :     if (DEBUGLEVEL>6)
     823             :     {
     824           0 :       err_printf("########## FACTORBASE ##########\n\n");
     825           0 :       err_printf("KC2=%ld, KC=%ld, KCZ=%ld, KCZ2=%ld\n",
     826             :                   ip, F->KC, F->KCZ, F->KCZ2);
     827           0 :       for (i=1; i<=F->KCZ; i++) err_printf("++ LV[%ld] = %Ps",i,F->LV[F->FB[i]]);
     828             :     }
     829             :   }
     830        2044 :   F->perm = NULL; F->L_jid = NULL;
     831        2044 : }
     832             : 
     833             : static int
     834       17588 : GRHchk(GEN nf, GRHcheck_t *S, ulong LIMC)
     835             : {
     836       17588 :   double logC = log((double)LIMC), SA = 0, SB = 0;
     837       17588 :   GRHprime_t *pr = S->primes;
     838             : 
     839       17588 :   cache_prime_dec(S, LIMC, nf);
     840      343675 :   for (pr = S->primes;; pr++)
     841             :   {
     842      343675 :     ulong p = pr->p;
     843             :     GEN dec, fs, ns;
     844             :     double logCslogp;
     845             :     long j;
     846             : 
     847      343675 :     if (p > LIMC) break;
     848      329160 :     dec = pr->dec; fs = gel(dec, 1); ns = gel(dec,2);
     849      329160 :     logCslogp = logC/pr->logp;
     850      469551 :     for (j = 1; j < lg(fs); j++)
     851             :     {
     852      381387 :       long f = fs[j], M, nb;
     853             :       double logNP, q, A, B;
     854      381387 :       if (f > logCslogp) break;
     855      140391 :       logNP = f * pr->logp;
     856      140391 :       q = 1/sqrt((double)upowuu(p, f));
     857      140391 :       A = logNP * q; B = logNP * A; M = (long)(logCslogp/f);
     858      140391 :       if (M > 1)
     859             :       {
     860       21846 :         double inv1_q = 1 / (1-q);
     861       21846 :         A *= (1 - pow(q, (double)M)) * inv1_q;
     862       21846 :         B *= (1 - pow(q, (double)M)*(M+1 - M*q)) * inv1_q * inv1_q;
     863             :       }
     864      140391 :       nb = ns[j];
     865      140391 :       SA += nb * A;
     866      140391 :       SB += nb * B;
     867             :     }
     868      329160 :     if (p == LIMC) break;
     869      326087 :   }
     870       17588 :   return GRHok(S, logC, SA, SB);
     871             : }
     872             : 
     873             : /*  SMOOTH IDEALS */
     874             : static void
     875     2220628 : store(long i, long e, FACT *fact)
     876             : {
     877     2220628 :   ++fact[0].pr;
     878     2220628 :   fact[fact[0].pr].pr = i; /* index */
     879     2220628 :   fact[fact[0].pr].ex = e; /* exponent */
     880     2220628 : }
     881             : 
     882             : /* divide out x by all P|p, where x as in can_factor().  k = v_p(Nx) */
     883             : static int
     884     1046719 : divide_p_elt(GEN LP, long ip, long k, GEN m, FACT *fact)
     885             : {
     886     1046719 :   long j, l = lg(LP);
     887     4361280 :   for (j=1; j<l; j++)
     888             :   {
     889     4359760 :     GEN P = gel(LP,j);
     890     4359760 :     long v = ZC_nfval(m, P);
     891     4359760 :     if (!v) continue;
     892     1933878 :     store(ip + j, v, fact); /* v = v_P(m) > 0 */
     893     1933878 :     k -= v * pr_get_f(P);
     894     1933878 :     if (!k) return 1;
     895             :   }
     896        1520 :   return 0;
     897             : }
     898             : static int
     899       51368 : divide_p_id(GEN LP, long ip, long k, GEN nf, GEN I, FACT *fact)
     900             : {
     901       51368 :   long j, l = lg(LP);
     902       76583 :   for (j=1; j<l; j++)
     903             :   {
     904       70101 :     GEN P = gel(LP,j);
     905       70101 :     long v = idealval(nf,I, P);
     906       70101 :     if (!v) continue;
     907       45712 :     store(ip + j, v, fact); /* v = v_P(I) > 0 */
     908       45712 :     k -= v * pr_get_f(P);
     909       45712 :     if (!k) return 1;
     910             :   }
     911        6482 :   return 0;
     912             : }
     913             : static int
     914      222202 : divide_p_quo(GEN LP, long ip, long k, GEN nf, GEN I, GEN m, FACT *fact)
     915             : {
     916      222202 :   long j, l = lg(LP);
     917      313850 :   for (j=1; j<l; j++)
     918             :   {
     919      313703 :     GEN P = gel(LP,j);
     920      313703 :     long v = ZC_nfval(m, P);
     921      313703 :     if (!v) continue;
     922      230244 :     v -= idealval(nf,I, P);
     923      230244 :     if (!v) continue;
     924      227322 :     store(ip + j, v, fact); /* v = v_P(m / I) > 0 */
     925      227322 :     k -= v * pr_get_f(P);
     926      227322 :     if (!k) return 1;
     927             :   }
     928         147 :   return 0;
     929             : }
     930             : 
     931             : /* |*N| != 0 is the norm of a primitive ideal, in particular not divisible by
     932             :  * any inert prime. Is |*N| a smooth rational integer wrt F ? (put the
     933             :  * exponents in *ex) */
     934             : static int
     935     1354171 : smooth_norm(FB_t *F, GEN *N, GEN *ex)
     936             : {
     937     1354171 :   GEN FB = F->FB;
     938     1354171 :   const long KCZ = F->KCZ;
     939     1354171 :   const ulong limp = uel(FB,KCZ); /* last p in FB */
     940             :   long i;
     941             : 
     942     1354171 :   *ex = new_chunk(KCZ+1);
     943    67155432 :   for (i=1; ; i++)
     944             :   {
     945             :     int stop;
     946    67155432 :     ulong p = uel(FB,i);
     947    67155432 :     long v = Z_lvalrem_stop(N, p, &stop);
     948    67155432 :     (*ex)[i] = v;
     949    67155432 :     if (v)
     950             :     {
     951     2320413 :       GEN LP = F->LV[p];
     952     2320413 :       if(!LP) pari_err_BUG("can_factor");
     953     2829639 :       if (lg(LP) == 1) return 0;
     954     3165358 :       if (stop) break;
     955             :     }
     956    66310487 :     if (i == KCZ) return 0;
     957    65801261 :   }
     958      844945 :   (*ex)[0] = i;
     959      844945 :   return (abscmpiu(*N,limp) <= 0);
     960             : }
     961             : 
     962             : static int
     963     1320289 : divide_p(FB_t *F, long p, long k, GEN nf, GEN I, GEN m, FACT *fact)
     964             : {
     965     1320289 :   GEN LP = F->LV[p];
     966     1320289 :   long ip = F->iLP[p];
     967     1320289 :   if (!m) return divide_p_id (LP,ip,k,nf,I,fact);
     968     1268921 :   if (!I) return divide_p_elt(LP,ip,k,m,fact);
     969      222202 :   return divide_p_quo(LP,ip,k,nf,I,m,fact);
     970             : }
     971             : 
     972             : /* Let x = m if I == NULL,
     973             :  *         I if m == NULL,
     974             :  *         m/I otherwise.
     975             :  * Can we factor the integral primitive ideal x ? |N| = Norm x > 0 */
     976             : static long
     977     1473521 : can_factor(FB_t *F, GEN nf, GEN I, GEN m, GEN N, FACT *fact)
     978             : {
     979             :   GEN ex;
     980     1473521 :   long i, res = 0;
     981     1473521 :   fact[0].pr = 0;
     982     1473521 :   if (is_pm1(N)) return 1;
     983     1354171 :   if (!smooth_norm(F, &N, &ex)) goto END;
     984     7933933 :   for (i=1; i<=ex[0]; i++)
     985     7231558 :     if (ex[i] && !divide_p(F, F->FB[i], ex[i], nf, I, m, fact)) goto END;
     986      702375 :   res = is_pm1(N) || divide_p(F, itou(N), 1, nf, I, m, fact);
     987             : END:
     988     1354171 :   if (!res && DEBUGLEVEL > 1) { err_printf("."); err_flush(); }
     989     1354171 :   return res;
     990             : }
     991             : 
     992             : /* can we factor m/I ? [m in I from idealpseudomin_nonscalar], NI = norm I */
     993             : static long
     994      326830 : factorgen(FB_t *F, GEN nf, GEN I, GEN NI, GEN m, FACT *fact)
     995             : {
     996      326830 :   long e, r1 = nf_get_r1(nf);
     997      326830 :   GEN M = nf_get_M(nf);
     998      326830 :   GEN N = divri(embed_norm(RgM_RgC_mul(M,m), r1), NI); /* ~ N(m/I) */
     999      326830 :   N = grndtoi(N, &e);
    1000      326830 :   if (e > -1)
    1001             :   {
    1002           0 :     if (DEBUGLEVEL > 1) { err_printf("+"); err_flush(); }
    1003           0 :     return 0;
    1004             :   }
    1005      326830 :   return can_factor(F, nf, I, m, N, fact);
    1006             : }
    1007             : 
    1008             : /*  FUNDAMENTAL UNITS */
    1009             : 
    1010             : /* a, m real. Return  (Re(x) + a) + I * (Im(x) % m) */
    1011             : static GEN
    1012      728335 : addRe_modIm(GEN x, GEN a, GEN m)
    1013             : {
    1014             :   GEN re, im, z;
    1015      728335 :   if (typ(x) == t_COMPLEX)
    1016             :   {
    1017      519219 :     im = modRr_safe(gel(x,2), m);
    1018      519219 :     if (!im) return NULL;
    1019      519219 :     re = gadd(gel(x,1), a);
    1020      519219 :     z = gequal0(im)? re: mkcomplex(re, im);
    1021             :   }
    1022             :   else
    1023      209116 :     z = gadd(x, a);
    1024      728335 :   return z;
    1025             : }
    1026             : 
    1027             : /* clean archimedean components */
    1028             : static GEN
    1029      279058 : cleanarch(GEN x, long N, long prec)
    1030             : {
    1031      279058 :   long i, R1, RU, tx = typ(x);
    1032             :   GEN s, y, pi2;
    1033             : 
    1034      279058 :   if (tx == t_MAT)
    1035             :   {
    1036        3896 :     y = cgetg(lg(x), tx);
    1037       40688 :     for (i=1; i < lg(x); i++) {
    1038       36792 :       gel(y,i) = cleanarch(gel(x,i), N, prec);
    1039       36792 :       if (!gel(y,i)) return NULL;
    1040             :     }
    1041        3896 :     return y;
    1042             :   }
    1043      275162 :   if (!is_vec_t(tx)) pari_err_TYPE("cleanarch",x);
    1044      275162 :   RU = lg(x)-1; R1 = (RU<<1)-N;
    1045      275162 :   s = gdivgs(RgV_sum(real_i(x)), -N); /* -log |norm(x)| / N */
    1046      275162 :   y = cgetg(RU+1,tx);
    1047      275162 :   pi2 = Pi2n(1, prec);
    1048      783658 :   for (i=1; i<=R1; i++) {
    1049      508496 :     gel(y,i) = addRe_modIm(gel(x,i), s, pi2);
    1050      508496 :     if (!gel(y,i)) return NULL;
    1051             :   }
    1052      275162 :   if (i <= RU)
    1053             :   {
    1054      102963 :     GEN pi4 = Pi2n(2, prec), s2 = gmul2n(s, 1);
    1055      322802 :     for (   ; i<=RU; i++) {
    1056      219839 :       gel(y,i) = addRe_modIm(gel(x,i), s2, pi4);
    1057      219839 :       if (!gel(y,i)) return NULL;
    1058             :     }
    1059             :   }
    1060      275162 :   return y;
    1061             : }
    1062             : 
    1063             : static GEN
    1064         109 : not_given(long reason)
    1065             : {
    1066         109 :   if (DEBUGLEVEL)
    1067           0 :     switch(reason)
    1068             :     {
    1069             :       case fupb_LARGE:
    1070           0 :         pari_warn(warner,"fundamental units too large, not given");
    1071           0 :         break;
    1072             :       case fupb_PRECI:
    1073           0 :         pari_warn(warner,"insufficient precision for fundamental units, not given");
    1074           0 :         break;
    1075             :     }
    1076         109 :   return NULL;
    1077             : }
    1078             : 
    1079             : /* check whether exp(x) will 1) get too big (real(x) large), 2) require
    1080             :  * large accuracy for argument reduction (imag(x) large) */
    1081             : static int
    1082        1621 : exp_OK(GEN x, long *pte)
    1083             : {
    1084        1621 :   long i,I,j,J, e = - (long)HIGHEXPOBIT;
    1085        1621 :   RgM_dimensions(x, &I,&J);
    1086        4556 :   for (j=1; j<=J; j++)
    1087       14735 :     for (i=1; i<=I; i++)
    1088             :     {
    1089       11800 :       GEN c = gcoeff(x,i,j), re;
    1090       11800 :       if (typ(c)!=t_COMPLEX) re = c;
    1091             :       else
    1092             :       {
    1093       10047 :         GEN im = gel(c,2);
    1094       10047 :         e = maxss(e, expo(im) + 5 - bit_prec(im));
    1095       10047 :         re = gel(c,1);
    1096             :       }
    1097       11800 :       if (expo(re) > 20) { *pte = LONG_MAX; return 0; }
    1098             :     }
    1099        1621 :   *pte = -e; return (e < 0);
    1100             : }
    1101             : 
    1102             : static GEN
    1103        1512 : log_m1(long r1, long ru, long prec)
    1104             : {
    1105        1512 :   GEN v = cgetg(ru+1,t_COL);
    1106        1512 :   GEN a = r1? PiI2n(0,prec): NULL;
    1107        1512 :   GEN a2 = (r1 != ru)? PiI2n(1,prec): NULL;
    1108             :   long i;
    1109        1512 :   for (i=1; i<=r1; i++) gel(v,i) = a;
    1110        1512 :   for (   ; i<=ru; i++) gel(v,i) = a2;
    1111        1512 :   return v;
    1112             : }
    1113             : static GEN
    1114        1999 : getfu(GEN nf, GEN *ptA, long *pte, long prec)
    1115             : {
    1116        1999 :   GEN u, y, matep, A, vec, T = nf_get_pol(nf), M = nf_get_M(nf);
    1117        1999 :   long e, i, j, R1, RU, N = degpol(T);
    1118             : 
    1119        1999 :   if (DEBUGLEVEL) err_printf("\n#### Computing fundamental units\n");
    1120        1999 :   R1 = nf_get_r1(nf); RU = (N+R1)>>1;
    1121        1999 :   if (RU==1) { *pte=LONG_MAX; return cgetg(1,t_VEC); }
    1122             : 
    1123        1621 :   *pte = 0; A = *ptA;
    1124        1621 :   matep = cgetg(RU,t_MAT);
    1125        4556 :   for (j=1; j<RU; j++)
    1126             :   {
    1127        2935 :     GEN c = cgetg(RU+1,t_COL), Aj = gel(A,j);
    1128        2935 :     GEN s = gdivgs(RgV_sum(real_i(Aj)), -N); /* -log |norm(Aj)| / N */
    1129        2935 :     gel(matep,j) = c;
    1130        2935 :     for (i=1; i<=R1; i++) gel(c,i) = gadd(s, gel(Aj,i));
    1131        2935 :     for (   ; i<=RU; i++) gel(c,i) = gadd(s, gmul2n(gel(Aj,i),-1));
    1132             :   }
    1133        1621 :   u = lll(real_i(matep));
    1134        1621 :   if (lg(u) < RU) return not_given(fupb_PRECI);
    1135             : 
    1136        1621 :   y = RgM_mul(matep,u);
    1137        1621 :   if (!exp_OK(y, pte))
    1138           0 :     return not_given(*pte == LONG_MAX? fupb_LARGE: fupb_PRECI);
    1139        1621 :   if (prec <= 0) prec = gprecision(A);
    1140        1621 :   y = RgM_solve_realimag(M, gexp(y,prec));
    1141        1621 :   if (!y) return not_given(fupb_PRECI);
    1142        1621 :   y = grndtoi(y, &e);
    1143        1621 :   *pte = -e;
    1144        1621 :   if (e >= 0) return not_given(fupb_PRECI);
    1145        4239 :   for (j=1; j<RU; j++)
    1146        2727 :     if (!is_pm1(nfnorm(nf, gel(y,j)))) { *pte=0; return not_given(fupb_PRECI); }
    1147        1512 :   A = RgM_mul(A,u);
    1148        1512 :   settyp(y, t_VEC);
    1149             :   /* y[i] are unit generators. Normalize: smallest T2 norm + lead coeff > 0 */
    1150        1512 :   vec = log_m1(R1,RU,prec);
    1151        4169 :   for (j=1; j<RU; j++)
    1152             :   {
    1153        2657 :     GEN u = gel(y,j), v = zk_inv(nf, u);
    1154        2657 :     if (gcmp(RgC_fpnorml2(v,DEFAULTPREC),
    1155             :              RgC_fpnorml2(u,DEFAULTPREC)) < 0)
    1156             :     {
    1157         901 :       gel(A,j) = RgC_neg(gel(A,j));
    1158         901 :       u = v;
    1159             :     }
    1160        2657 :     u = coltoliftalg(nf,u);
    1161        2657 :     if (gsigne(leading_coeff(u)) < 0)
    1162             :     {
    1163        1253 :       gel(A,j) = RgC_add(gel(A,j), vec);
    1164        1253 :       u = RgX_neg(u);
    1165             :     }
    1166        2657 :     gel(y,j) = u;
    1167             :   }
    1168        1512 :   *ptA = A; return y;
    1169             : }
    1170             : 
    1171             : static GEN
    1172        1562 : makeunits(GEN BNF)
    1173             : {
    1174        1562 :   GEN bnf = checkbnf(BNF), fu = bnf_get_fu_nocheck(bnf), v;
    1175        1562 :   GEN nf = bnf_get_nf(bnf);
    1176             :   long i, l;
    1177        1562 :   if (typ(fu) == t_MAT)
    1178             :   {
    1179           0 :     pari_sp av = avma;
    1180           0 :     GEN A = bnf_get_logfu(bnf);
    1181           0 :     fu = getfu(nf, &A, &l, 0);
    1182           0 :     if (!fu)
    1183           0 :       pari_err_PREC("makeunits [cannot compute units, use bnfinit(,1)]");
    1184           0 :     fu = gerepilecopy(av, fu);
    1185             :   }
    1186        1562 :   l = lg(fu) + 1; v = cgetg(l, t_VEC);
    1187        1562 :   gel(v,1) = nf_to_scalar_or_basis(nf,bnf_get_tuU(bnf));
    1188        1562 :   for (i = 2; i < l; i++) gel(v,i) = algtobasis(nf, gel(fu,i-1));
    1189        1562 :   return v;
    1190             : }
    1191             : 
    1192             : /*******************************************************************/
    1193             : /*                                                                 */
    1194             : /*           PRINCIPAL IDEAL ALGORITHM (DISCRETE LOG)              */
    1195             : /*                                                                 */
    1196             : /*******************************************************************/
    1197             : 
    1198             : /* G: prime ideals, E: vector of non-negative exponents.
    1199             :  * C = possible extra prime (^1) or NULL
    1200             :  * Return Norm (product) */
    1201             : static GEN
    1202         775 : get_norm_fact_primes(GEN G, GEN E, GEN C)
    1203             : {
    1204         775 :   pari_sp av=avma;
    1205         775 :   GEN N = gen_1, P, p;
    1206         775 :   long i, c = lg(E);
    1207        1784 :   for (i=1; i<c; i++)
    1208             :   {
    1209        1009 :     GEN ex = gel(E,i);
    1210        1009 :     long s = signe(ex);
    1211        1009 :     if (!s) continue;
    1212             : 
    1213         587 :     P = gel(G,i); p = pr_get_p(P);
    1214         587 :     N = mulii(N, powii(p, mului(pr_get_f(P), ex)));
    1215             :   }
    1216         775 :   if (C) N = mulii(N, pr_norm(C));
    1217         775 :   return gerepileuptoint(av, N);
    1218             : }
    1219             : 
    1220             : /* gen: HNF ideals */
    1221             : static GEN
    1222      235371 : get_norm_fact(GEN gen, GEN ex, GEN *pd)
    1223             : {
    1224      235371 :   long i, c = lg(ex);
    1225             :   GEN d,N,I,e,n,ne,de;
    1226      235371 :   d = N = gen_1;
    1227      383650 :   for (i=1; i<c; i++)
    1228      148279 :     if (signe(gel(ex,i)))
    1229             :     {
    1230       94056 :       I = gel(gen,i); e = gel(ex,i); n = ZM_det_triangular(I);
    1231       94056 :       ne = powii(n,e);
    1232       94056 :       de = equalii(n, gcoeff(I,1,1))? ne: powii(gcoeff(I,1,1), e);
    1233       94056 :       N = mulii(N, ne);
    1234       94056 :       d = mulii(d, de);
    1235             :     }
    1236      235371 :   *pd = d; return N;
    1237             : }
    1238             : 
    1239             : static GEN
    1240      287535 : get_pr_lists(GEN FB, long N, int list_pr)
    1241             : {
    1242             :   GEN pr, L;
    1243      287535 :   long i, l = lg(FB), p, pmax;
    1244             : 
    1245      287535 :   pmax = 0;
    1246     2742709 :   for (i=1; i<l; i++)
    1247             :   {
    1248     2455174 :     pr = gel(FB,i); p = pr_get_smallp(pr);
    1249     2455174 :     if (p > pmax) pmax = p;
    1250             :   }
    1251      287535 :   L = const_vec(pmax, NULL);
    1252      287535 :   if (list_pr)
    1253             :   {
    1254          56 :     for (i=1; i<l; i++)
    1255             :     {
    1256          49 :       pr = gel(FB,i); p = pr_get_smallp(pr);
    1257          49 :       if (!L[p]) gel(L,p) = vectrunc_init(N+1);
    1258          49 :       vectrunc_append(gel(L,p), pr);
    1259             :     }
    1260          98 :     for (p=1; p<=pmax; p++)
    1261          91 :       if (L[p]) gen_sort_inplace(gel(L,p), (void*)&cmp_prime_over_p,
    1262             :                                  &cmp_nodata, NULL);
    1263             :   }
    1264             :   else
    1265             :   {
    1266     2742653 :     for (i=1; i<l; i++)
    1267             :     {
    1268     2455125 :       pr = gel(FB,i); p = pr_get_smallp(pr);
    1269     2455125 :       if (!L[p]) gel(L,p) = vecsmalltrunc_init(N+1);
    1270     2455125 :       vecsmalltrunc_append(gel(L,p), i);
    1271             :     }
    1272             :   }
    1273      287535 :   return L;
    1274             : }
    1275             : 
    1276             : /* recover FB, LV, iLP, KCZ from Vbase */
    1277             : static GEN
    1278      287528 : recover_partFB(FB_t *F, GEN Vbase, long N)
    1279             : {
    1280      287528 :   GEN FB, LV, iLP, L = get_pr_lists(Vbase, N, 0);
    1281      287528 :   long l = lg(L), p, ip, i;
    1282             : 
    1283      287528 :   i = ip = 0;
    1284      287528 :   FB = cgetg(l, t_VECSMALL);
    1285      287528 :   iLP= cgetg(l, t_VECSMALL);
    1286      287528 :   LV = cgetg(l, t_VEC);
    1287     6244603 :   for (p = 2; p < l; p++)
    1288             :   {
    1289     5957075 :     if (!L[p]) continue;
    1290     1386608 :     FB[++i] = p;
    1291     1386608 :     gel(LV,p) = vecpermute(Vbase, gel(L,p));
    1292     1386608 :     iLP[p]= ip; ip += lg(gel(L,p))-1;
    1293             :   }
    1294      287528 :   F->KCZ = i;
    1295      287528 :   F->KC = ip;
    1296      287528 :   F->FB = FB; setlg(FB, i+1);
    1297      287528 :   F->LV = (GEN*)LV;
    1298      287528 :   F->iLP= iLP; return L;
    1299             : }
    1300             : 
    1301             : /* add v^e to factorization */
    1302             : static void
    1303       14613 : add_to_fact(long v, long e, FACT *fact)
    1304             : {
    1305       14613 :   long i, l = fact[0].pr;
    1306       14613 :   for (i=1; i<=l && fact[i].pr < v; i++)/*empty*/;
    1307       14613 :   if (i <= l && fact[i].pr == v) fact[i].ex += e; else store(v, e, fact);
    1308       14613 : }
    1309             : 
    1310             : /* L (small) list of primes above the same p including pr. Return pr index */
    1311             : static int
    1312        9919 : pr_index(GEN L, GEN pr)
    1313             : {
    1314        9919 :   long j, l = lg(L);
    1315        9919 :   GEN al = pr_get_gen(pr);
    1316        9947 :   for (j=1; j<l; j++)
    1317        9947 :     if (ZV_equal(al, pr_get_gen(gel(L,j)))) return j;
    1318           0 :   pari_err_BUG("codeprime");
    1319             :   return 0; /* LCOV_EXCL_LINE */
    1320             : }
    1321             : 
    1322             : static long
    1323        9870 : Vbase_to_FB(FB_t *F, GEN pr)
    1324             : {
    1325        9870 :   long p = pr_get_smallp(pr);
    1326        9870 :   return F->iLP[p] + pr_index(F->LV[p], pr);
    1327             : }
    1328             : 
    1329             : /* x, y 2 extended ideals whose first component is an integral HNF and second
    1330             :  * a famat */
    1331             : static GEN
    1332       18742 : idealHNF_mulred(GEN nf, GEN x, GEN y)
    1333             : {
    1334       18742 :   GEN A = idealHNF_mul(nf, gel(x,1), gel(y,1));
    1335       18742 :   GEN F = famat_mul_shallow(gel(x,2), gel(y,2));
    1336       18742 :   return idealred(nf, mkvec2(A, F));
    1337             : }
    1338             : 
    1339             : /* return famat y (principal ideal) such that y / x is smooth [wrt Vbase] */
    1340             : static GEN
    1341      302858 : SPLIT(FB_t *F, GEN nf, GEN x, GEN Vbase, FACT *fact)
    1342             : {
    1343      302858 :   GEN vecG, z, ex, y, x0, Nx = ZM_det_triangular(x);
    1344             :   long nbtest_lim, nbtest, i, j, ru, lgsub;
    1345             :   pari_sp av;
    1346             : 
    1347      302858 :   if (nf_get_degree(nf) != lg(x)-1)
    1348           0 :     pari_err_TYPE("idealtyp [dimension != degree]", x);
    1349             : 
    1350             :   /* try without reduction if x is small */
    1351      605695 :   if (gexpo(gcoeff(x,1,1)) < 100 &&
    1352      371546 :       can_factor(F, nf, x, NULL, Nx, fact)) return NULL;
    1353             : 
    1354      234149 :   av = avma;
    1355      234149 :   y = idealpseudomin_nonscalar(x, nf_get_roundG(nf));
    1356      234149 :   if (factorgen(F, nf, x, Nx, y, fact)) return y;
    1357       17378 :   avma = av;
    1358             : 
    1359             :   /* reduce in various directions */
    1360       17378 :   ru = lg(nf_get_roots(nf));
    1361       17378 :   vecG = cgetg(ru, t_VEC);
    1362       32051 :   for (j=1; j<ru; j++)
    1363             :   {
    1364       26941 :     gel(vecG,j) = nf_get_Gtwist1(nf, j);
    1365       26941 :     av = avma;
    1366       26941 :     y = idealpseudomin_nonscalar(x, gel(vecG,j));
    1367       26941 :     if (factorgen(F, nf, x, Nx, y, fact)) return y;
    1368       14673 :     avma = av;
    1369             :   }
    1370             : 
    1371             :   /* tough case, multiply by random products */
    1372        5110 :   lgsub = 3;
    1373        5110 :   ex = cgetg(lgsub, t_VECSMALL);
    1374        5110 :   z  = init_famat(NULL);
    1375        5110 :   x0 = init_famat(x);
    1376        5110 :   nbtest = 1; nbtest_lim = 4;
    1377             :   for(;;)
    1378             :   {
    1379        9303 :     GEN I, NI, id = x0;
    1380        9303 :     av = avma;
    1381        9303 :     if (DEBUGLEVEL>2) err_printf("# ideals tried = %ld\n",nbtest);
    1382       28406 :     for (i=1; i<lgsub; i++)
    1383             :     {
    1384       19103 :       ex[i] = random_bits(RANDOM_BITS);
    1385       19103 :       if (ex[i])
    1386             :       { /* avoid prec pb: don't let id become too large as lgsub increases */
    1387       17941 :         gel(z,1) = gel(Vbase,i);
    1388       17941 :         id = idealHNF_mulred(nf, id, idealpowred(nf,z,utoipos(ex[i])));
    1389             :       }
    1390             :     }
    1391        9303 :     if (id == x0) continue;
    1392             : 
    1393        9261 :     I = gel(id,1); NI = ZM_det_triangular(I);
    1394       19579 :     for (j=1; j<ru; j++)
    1395             :     {
    1396       15428 :       pari_sp av2 = avma;
    1397       15428 :       y = idealpseudomin_nonscalar(I, gel(vecG,j));
    1398       15428 :       if (factorgen(F, nf, I, NI, y, fact))
    1399             :       {
    1400       15547 :         for (i=1; i<lgsub; i++)
    1401       10437 :           if (ex[i]) add_to_fact(Vbase_to_FB(F,gel(Vbase,i)), ex[i], fact);
    1402        5110 :         return famat_mul_shallow(gel(id,2), y);
    1403             :       }
    1404       10318 :       avma = av2;
    1405             :     }
    1406        4151 :     avma = av;
    1407        4151 :     if (++nbtest > nbtest_lim)
    1408             :     {
    1409         217 :       nbtest = 0;
    1410         217 :       if (++lgsub < minss(7, lg(Vbase)-1))
    1411             :       {
    1412         217 :         nbtest_lim <<= 1;
    1413         217 :         ex = cgetg(lgsub, t_VECSMALL);
    1414             :       }
    1415           0 :       else nbtest_lim = LONG_MAX; /* don't increase further */
    1416         217 :       if (DEBUGLEVEL>2) err_printf("SPLIT: increasing factor base [%ld]\n",lgsub);
    1417             :     }
    1418        4193 :   }
    1419             : }
    1420             : 
    1421             : /* return principal y such that y / x is smooth. Store factorization of latter*/
    1422             : static GEN
    1423      286520 : split_ideal(GEN nf, FB_t *F, GEN x, GEN Vbase, GEN L, FACT *fact)
    1424             : {
    1425      286520 :   GEN y = SPLIT(F, nf, x, Vbase, fact);
    1426      286520 :   long p,j, i, l = lg(F->FB);
    1427             : 
    1428      286520 :   p = j = 0; /* -Wall */
    1429      502620 :   for (i=1; i<=fact[0].pr; i++)
    1430             :   { /* decode index C = ip+j --> (p,j) */
    1431      216100 :     long q,k,t, C = fact[i].pr;
    1432      732765 :     for (t=1; t<l; t++)
    1433             :     {
    1434      718759 :       q = F->FB[t];
    1435      718759 :       k = C - F->iLP[q];
    1436      718759 :       if (k <= 0) break;
    1437      516665 :       p = q;
    1438      516665 :       j = k;
    1439             :     }
    1440      216100 :     fact[i].pr = gel(L, p)[j];
    1441             :   }
    1442      286520 :   return y;
    1443             : }
    1444             : 
    1445             : INLINE GEN
    1446      287544 : bnf_get_W(GEN bnf) { return gel(bnf,1); }
    1447             : INLINE GEN
    1448      287514 : bnf_get_B(GEN bnf) { return gel(bnf,2); }
    1449             : INLINE GEN
    1450      603091 : bnf_get_C(GEN bnf) { return gel(bnf,4); }
    1451             : INLINE GEN
    1452      287593 : bnf_get_vbase(GEN bnf) { return gel(bnf,5); }
    1453             : 
    1454             : /**** logarithmic embeddings ****/
    1455             : static GEN famat_to_arch(GEN nf, GEN fa, long prec);
    1456             : static GEN
    1457        1789 : triv_arch(GEN nf) { return zerovec(lg(nf_get_roots(nf))-1); }
    1458             : 
    1459             : /* Get archimedean components: [e_i Log( sigma_i(X) )], where X = primpart(x),
    1460             :  * and e_i = 1 (resp 2.) for i <= R1 (resp. > R1) */
    1461             : static GEN
    1462      199252 : get_arch(GEN nf, GEN x, long prec)
    1463             : {
    1464             :   long i, l, R1;
    1465             :   GEN v;
    1466      199252 :   if (typ(x) == t_MAT) return famat_to_arch(nf,x,prec);
    1467      199102 :   x = nf_to_scalar_or_basis(nf,x);
    1468      199102 :   if (typ(x) != t_COL) return triv_arch(nf);
    1469      198470 :   x = RgM_RgC_mul(nf_get_M(nf), Q_primpart(x));
    1470      198470 :   l = lg(x);
    1471      198470 :   for (i=1; i < l; i++) if (gequal0(gabs(gel(x,i),prec))) return NULL;
    1472      198442 :   v = cgetg(l,t_VEC); R1 = nf_get_r1(nf);
    1473      198442 :   for (i=1; i<=R1; i++) gel(v,i) = glog(gel(x,i),prec);
    1474      198442 :   for (   ; i < l; i++) gel(v,i) = gmul2n(glog(gel(x,i),prec),1);
    1475      198442 :   return v;
    1476             : }
    1477             : static GEN
    1478        1931 : famat_to_arch(GEN nf, GEN fa, long prec)
    1479             : {
    1480        1931 :   GEN g,e, y = NULL;
    1481             :   long i,l;
    1482             : 
    1483        1931 :   if (typ(fa) != t_MAT) pari_err_TYPE("famat_to_arch",fa);
    1484        1931 :   if (lg(fa) == 1) return triv_arch(nf);
    1485        1114 :   g = gel(fa,1);
    1486        1114 :   e = gel(fa,2); l = lg(e);
    1487        5363 :   for (i=1; i<l; i++)
    1488             :   {
    1489        4253 :     GEN t, x = nf_to_scalar_or_basis(nf, gel(g,i));
    1490             :     /* multiplicative arch would be better (save logs), but exponents overflow
    1491             :      * [ could keep track of expo separately, but not worth it ] */
    1492        4253 :     t = get_arch(nf,x,prec); if (!t) return NULL;
    1493        4249 :     if (gel(t,1) == gen_0) continue; /* rational */
    1494        3636 :     t = RgV_Rg_mul(t, gel(e,i));
    1495        3636 :     y = y? RgV_add(y,t): t;
    1496             :   }
    1497        1110 :   return y ? y: triv_arch(nf);
    1498             : }
    1499             : 
    1500             : static GEN
    1501        1334 : famat_get_arch_real(GEN nf,GEN x,GEN *emb,long prec)
    1502             : {
    1503        1334 :   GEN A, T, a, t, g = gel(x,1), e = gel(x,2);
    1504        1334 :   long i, l = lg(e);
    1505             : 
    1506        1334 :   if (l <= 1)
    1507           0 :     return get_arch_real(nf, gen_1, emb, prec);
    1508        1334 :   A = T = NULL; /* -Wall */
    1509        5604 :   for (i=1; i<l; i++)
    1510             :   {
    1511        4274 :     a = get_arch_real(nf, gel(g,i), &t, prec);
    1512        4274 :     if (!a) return NULL;
    1513        4270 :     a = RgC_Rg_mul(a, gel(e,i));
    1514        4270 :     t = vecpow(t, gel(e,i));
    1515        4270 :     if (i == 1) { A = a;          T = t; }
    1516        2940 :     else        { A = gadd(A, a); T = vecmul(T, t); }
    1517             :   }
    1518        1330 :   *emb = T; return A;
    1519             : }
    1520             : 
    1521             : static GEN
    1522        1323 : scalar_get_arch_real(GEN nf, GEN u, GEN *emb)
    1523             : {
    1524             :   GEN v, logu;
    1525        1323 :   long i, s = signe(u), RU = lg(nf_get_roots(nf))-1, R1 = nf_get_r1(nf);
    1526             : 
    1527        1323 :   if (!s) pari_err_DOMAIN("get_arch_real","argument","=",gen_0,u);
    1528        1323 :   v = cgetg(RU+1, t_COL);
    1529        1323 :   logu = logr_abs(u);
    1530        1323 :   for (i=1; i<=R1; i++) gel(v,i) = logu;
    1531        1323 :   if (i <= RU)
    1532             :   {
    1533         581 :     GEN logu2 = shiftr(logu,1);
    1534         581 :     for (   ; i<=RU; i++) gel(v,i) = logu2;
    1535             :   }
    1536        1323 :   *emb = const_col(RU, u); return v;
    1537             : }
    1538             : 
    1539             : static int
    1540       13980 : low_prec(GEN x) { return gequal0(x) || (typ(x) == t_REAL && realprec(x) <= DEFAULTPREC); }
    1541             : 
    1542             : /* For internal use. Get archimedean components: [e_i log( | sigma_i(x) | )],
    1543             :  * with e_i = 1 (resp 2.) for i <= R1 (resp. > R1)
    1544             :  * Return NULL if precision problem, and set *emb to the embeddings of x */
    1545             : GEN
    1546        6959 : get_arch_real(GEN nf, GEN x, GEN *emb, long prec)
    1547             : {
    1548             :   long i, lx, R1;
    1549             :   GEN v, t;
    1550             : 
    1551        6959 :   if (typ(x) == t_MAT) return famat_get_arch_real(nf,x,emb,prec);
    1552        5625 :   x = nf_to_scalar_or_basis(nf,x);
    1553        5625 :   if (typ(x) != t_COL) return scalar_get_arch_real(nf, gtofp(x,prec), emb);
    1554        4302 :   R1 = nf_get_r1(nf);
    1555        4302 :   x = RgM_RgC_mul(nf_get_M(nf), x);
    1556        4302 :   lx = lg(x);
    1557        4302 :   v = cgetg(lx,t_COL);
    1558        8131 :   for (i=1; i<=R1; i++)
    1559             :   {
    1560        3836 :     t = gabs(gel(x,i),prec); if (low_prec(t)) return NULL;
    1561        3829 :     gel(v,i) = glog(t,prec);
    1562             :   }
    1563       14379 :   for (   ; i< lx; i++)
    1564             :   {
    1565       10144 :     t = gnorm(gel(x,i)); if (low_prec(t)) return NULL;
    1566       10084 :     gel(v,i) = glog(t,prec);
    1567             :   }
    1568        4235 :   *emb = x; return v;
    1569             : }
    1570             : 
    1571             : 
    1572             : GEN
    1573      233556 : init_red_mod_units(GEN bnf, long prec)
    1574             : {
    1575      233556 :   GEN s = gen_0, p1,s1,mat, logfu = bnf_get_logfu(bnf);
    1576      233556 :   long i,j, RU = lg(logfu);
    1577             : 
    1578      233556 :   if (RU == 1) return NULL;
    1579      233556 :   mat = cgetg(RU,t_MAT);
    1580      588773 :   for (j=1; j<RU; j++)
    1581             :   {
    1582      355217 :     p1 = cgetg(RU+1,t_COL); gel(mat,j) = p1;
    1583      355217 :     s1 = gen_0;
    1584      985966 :     for (i=1; i<RU; i++)
    1585             :     {
    1586      630749 :       gel(p1,i) = real_i(gcoeff(logfu,i,j));
    1587      630749 :       s1 = mpadd(s1, mpsqr(gel(p1,i)));
    1588             :     }
    1589      355217 :     gel(p1,RU) = gen_0; if (mpcmp(s1,s) > 0) s = s1;
    1590             :   }
    1591      233556 :   s = gsqrt(gmul2n(s,RU),prec);
    1592      233556 :   if (expo(s) < 27) s = utoipos(1UL << 27);
    1593      233556 :   return mkvec2(mat, s);
    1594             : }
    1595             : 
    1596             : /* z computed above. Return unit exponents that would reduce col (arch) */
    1597             : GEN
    1598      233556 : red_mod_units(GEN col, GEN z)
    1599             : {
    1600             :   long i,RU;
    1601             :   GEN x,mat,N2;
    1602             : 
    1603      233556 :   if (!z) return NULL;
    1604      233556 :   mat= gel(z,1);
    1605      233556 :   N2 = gel(z,2);
    1606      233556 :   RU = lg(mat); x = cgetg(RU+1,t_COL);
    1607      233556 :   for (i=1; i<RU; i++) gel(x,i) = real_i(gel(col,i));
    1608      233556 :   gel(x,RU) = N2;
    1609      233556 :   x = lll(shallowconcat(mat,x));
    1610      233556 :   if (typ(x) != t_MAT) return NULL;
    1611      233556 :   x = gel(x,RU);
    1612      233556 :   if (signe(gel(x,RU)) < 0) x = gneg_i(x);
    1613      233556 :   if (!gequal1(gel(x,RU))) pari_err_BUG("red_mod_units");
    1614      233556 :   setlg(x,RU); return x;
    1615             : }
    1616             : 
    1617             : /* [x] archimedian components, A column vector. return [x] A
    1618             :  * x may be a translated GEN (y + k) */
    1619             : static GEN
    1620      531992 : act_arch(GEN A, GEN x)
    1621             : {
    1622             :   GEN a;
    1623      531992 :   long i,l = lg(A), tA = typ(A);
    1624      531992 :   if (tA == t_MAT)
    1625             :   { /* assume lg(x) >= l */
    1626        7736 :     a = cgetg(l, t_VEC);
    1627        7736 :     for (i=1; i<l; i++) gel(a,i) = act_arch(gel(A,i), x);
    1628        7736 :     return a;
    1629             :   }
    1630      524256 :   if (l==1) return cgetg(1, t_VEC);
    1631      524256 :   a = NULL;
    1632      524256 :   if (tA == t_VECSMALL)
    1633             :   {
    1634     1805446 :     for (i=1; i<l; i++)
    1635             :     {
    1636     1570180 :       long c = A[i];
    1637     1570180 :       if (!c) continue;
    1638      114346 :       if (!a) { a = gmulsg(c, gel(x,i)); continue; }
    1639       20435 :       a = gadd(a, gmulsg(c, gel(x,i)));
    1640             :     }
    1641             :   }
    1642             :   else
    1643             :   { /* A a t_COL of t_INT. Assume lg(A)==lg(x) */
    1644      605183 :     for (i=1; i<l; i++)
    1645             :     {
    1646      316193 :       GEN c = gel(A,i);
    1647      316193 :       if (!signe(c)) continue;
    1648      163400 :       if (!a) { a = gmul(c, gel(x,i)); continue; }
    1649        6188 :       a = gadd(a, gmul(gel(A,i), gel(x,i)));
    1650             :     }
    1651             :   }
    1652      524256 :   if (!a) return zerovec(lgcols(x)-1);
    1653      251123 :   settyp(a, t_VEC); return a;
    1654             : }
    1655             : 
    1656             : static long
    1657      315554 : prec_arch(GEN bnf)
    1658             : {
    1659      315554 :   GEN a = bnf_get_C(bnf);
    1660      315554 :   long i, l = lg(a), prec;
    1661             : 
    1662      316380 :   for (i=1; i<l; i++)
    1663      316156 :     if ( (prec = gprecision(gel(a,i))) ) return prec;
    1664         224 :   return DEFAULTPREC;
    1665             : }
    1666             : 
    1667             : static long
    1668        1075 : needed_bitprec(GEN x)
    1669             : {
    1670        1075 :   long i, e = 0, l = lg(x);
    1671        6150 :   for (i = 1; i < l; i++)
    1672             :   {
    1673        5075 :     GEN c = gel(x,i);
    1674        5075 :     long f = gexpo(c) - prec2nbits(gprecision(c));
    1675        5075 :     if (f > e) e = f;
    1676             :   }
    1677        1075 :   return e;
    1678             : }
    1679             : 
    1680             : /* col = archimedian components of x, Nx = kNx^e its norm (e > 0, usually = 1),
    1681             :  * dx a bound for its denominator. Return x or NULL (fail) */
    1682             : GEN
    1683      236818 : isprincipalarch(GEN bnf, GEN col, GEN kNx, GEN e, GEN dx, long *pe)
    1684             : {
    1685             :   GEN nf, x, y, logfu, s, M;
    1686      236818 :   long N, R1, RU, i, prec = gprecision(col);
    1687      236818 :   bnf = checkbnf(bnf); nf = bnf_get_nf(bnf); M = nf_get_M(nf);
    1688      236818 :   if (!prec) prec = prec_arch(bnf);
    1689      236818 :   logfu = bnf_get_logfu(bnf);
    1690      236818 :   N = nf_get_degree(nf);
    1691      236818 :   R1 = nf_get_r1(nf);
    1692      236818 :   RU = (N + R1)>>1;
    1693      236818 :   col = cleanarch(col,N,prec); settyp(col, t_COL);
    1694      236818 :   if (!col) pari_err_PREC( "isprincipalarch");
    1695      236818 :   if (RU > 1)
    1696             :   { /* reduce mod units */
    1697      233556 :     GEN u, z = init_red_mod_units(bnf,prec);
    1698      233556 :     u = red_mod_units(col,z);
    1699      233556 :     if (!u && z) return NULL;
    1700      233556 :     if (u) col = RgC_add(col, RgM_RgC_mul(logfu, u));
    1701             :   }
    1702      236818 :   s = divru(mulir(e, glog(kNx,prec)), N);
    1703      236818 :   for (i=1; i<=R1; i++) gel(col,i) = gexp(gadd(s, gel(col,i)),prec);
    1704      236818 :   for (   ; i<=RU; i++) gel(col,i) = gexp(gadd(s, gmul2n(gel(col,i),-1)),prec);
    1705             :   /* d.alpha such that x = alpha \prod gj^ej */
    1706      236818 :   x = RgM_solve_realimag(M,col); if (!x) return NULL;
    1707      236818 :   x = RgC_Rg_mul(x, dx);
    1708      236818 :   y = grndtoi(x, pe);
    1709      236818 :   if (*pe > -5)
    1710             :   {
    1711        1075 :     *pe = needed_bitprec(x);
    1712        1075 :     return NULL;
    1713             :   }
    1714      235743 :   return RgC_Rg_div(y, dx);
    1715             : }
    1716             : 
    1717             : /* y = C \prod g[i]^e[i] ? */
    1718             : static int
    1719      235743 : fact_ok(GEN nf, GEN y, GEN C, GEN g, GEN e)
    1720             : {
    1721      235743 :   pari_sp av = avma;
    1722      235743 :   long i, c = lg(e);
    1723      235743 :   GEN z = C? C: gen_1;
    1724      384457 :   for (i=1; i<c; i++)
    1725      148714 :     if (signe(gel(e,i))) z = idealmul(nf, z, idealpow(nf, gel(g,i), gel(e,i)));
    1726      235743 :   if (typ(z) != t_MAT) z = idealhnf_shallow(nf,z);
    1727      235743 :   if (typ(y) != t_MAT) y = idealhnf_shallow(nf,y);
    1728      235743 :   i = ZM_equal(y, z); avma = av; return i;
    1729             : }
    1730             : 
    1731             : /* assume x in HNF. cf class_group_gen for notations.
    1732             :  * Return NULL iff flag & nf_FORCE and computation of principal ideal generator
    1733             :  * fails */
    1734             : static GEN
    1735      287479 : isprincipalall(GEN bnf, GEN x, long *ptprec, long flag)
    1736             : {
    1737      287479 :   long i,nW,nB,e,c, prec = *ptprec;
    1738             :   GEN Q,xar,Wex,Bex,U,p1,gen,cyc,xc,ex,d,col,A;
    1739      287479 :   GEN W  = bnf_get_W(bnf);
    1740      287479 :   GEN B  = bnf_get_B(bnf);
    1741      287479 :   GEN C  = bnf_get_C(bnf);
    1742      287479 :   GEN nf = bnf_get_nf(bnf);
    1743      287479 :   GEN clg2 = gel(bnf,9);
    1744             :   FB_t F;
    1745      287479 :   GEN Vbase = bnf_get_vbase(bnf);
    1746      287479 :   GEN L = recover_partFB(&F, Vbase, lg(x)-1);
    1747             :   pari_sp av;
    1748             :   FACT *fact;
    1749             : 
    1750      287479 :   U = gel(clg2,1);
    1751      287479 :   cyc = bnf_get_cyc(bnf); c = lg(cyc)-1;
    1752      287479 :   gen = bnf_get_gen(bnf);
    1753      287479 :   ex = cgetg(c+1,t_COL);
    1754      287479 :   if (c == 0 && !(flag & (nf_GEN|nf_GENMAT|nf_GEN_IF_PRINCIPAL))) return ex;
    1755             : 
    1756             :   /* factor x */
    1757      286520 :   x = Q_primitive_part(x, &xc);
    1758      286520 :   av = avma;
    1759             : 
    1760      286520 :   fact = (FACT*)stack_malloc((F.KC+1)*sizeof(FACT));
    1761      286520 :   xar = split_ideal(nf, &F, x, Vbase, L, fact);
    1762      286520 :   nW = lg(W)-1; Wex = zero_zv(nW);
    1763      286520 :   nB = lg(B)-1; Bex = zero_zv(nB);
    1764      502620 :   for (i=1; i<=fact[0].pr; i++)
    1765             :   {
    1766      216100 :     long k = fact[i].pr;
    1767      216100 :     long l = k - nW;
    1768      216100 :     if (l <= 0) Wex[k] = fact[i].ex;
    1769      154757 :     else        Bex[l] = fact[i].ex;
    1770             :   }
    1771             : 
    1772             :   /* x = -g_W Wex - g_B Bex + [xar]  | x = g_W Wex + g_B Bex if xar = NULL
    1773             :    *   = g_W A + [xar] - [C_B]Bex    |   = g_W A + [C_B]Bex
    1774             :    * since g_W B + g_B = [C_B] */
    1775      286520 :   if (xar)
    1776             :   {
    1777      217811 :     if (!nB) /*treat specially B = matrix(n,0): PARI can't represent it*/
    1778          14 :       A = zc_to_ZC(zv_neg(Wex));
    1779             :     else
    1780             :     {
    1781      217797 :       A = ZC_sub(ZM_zc_mul(B,Bex), zc_to_ZC(Wex));
    1782      217797 :       Bex = zv_neg(Bex);
    1783             :     }
    1784             :   }
    1785             :   else
    1786             :   {
    1787       68709 :     if (!nB)
    1788         105 :       A = zc_to_ZC(Wex);
    1789             :     else
    1790       68604 :       A = ZC_sub(zc_to_ZC(Wex), ZM_zc_mul(B,Bex));
    1791             :   }
    1792      286520 :   Q = ZM_ZC_mul(U, A);
    1793      514550 :   for (i=1; i<=c; i++)
    1794      228030 :     gel(Q,i) = truedvmdii(gel(Q,i), gel(cyc,i), (GEN*)(ex+i));
    1795      286520 :   if ((flag & nf_GEN_IF_PRINCIPAL))
    1796       43496 :     { if (!ZV_equal0(ex)) return gen_0; }
    1797      243024 :   else if (!(flag & (nf_GEN|nf_GENMAT)))
    1798       51142 :     return ZC_copy(ex);
    1799             : 
    1800             :   /* compute arch component of the missing principal ideal */
    1801             :   { /* g A = G Ur A + [ga]A, Ur A = D Q + R as above (R = ex)
    1802             :            = G R + [GD]Q + [ga]A */
    1803      235371 :     GEN ga = gel(clg2,2), GD = gel(clg2,3);
    1804      235371 :     if (nB) col = act_arch(Bex, C + nW); else col = triv_arch(nf);
    1805      235371 :     if (nW) col = gadd(col, act_arch(A, ga));
    1806      235371 :     if (c)  col = gadd(col, act_arch(Q, GD));
    1807             :   }
    1808      235371 :   if (xar)
    1809             :   {
    1810      193332 :     GEN t = get_arch(nf, xar, prec);
    1811      193332 :     col = t? gadd(col, t):NULL;
    1812             :   }
    1813             : 
    1814             :   /* find coords on Zk; Q = N (x / \prod gj^ej) = N(alpha), denom(alpha) | d */
    1815      235371 :   Q = gdiv(ZM_det_triangular(x), get_norm_fact(gen, ex, &d));
    1816      235371 :   col = col?isprincipalarch(bnf, col, Q, gen_1, d, &e):NULL;
    1817      235371 :   if (col && !fact_ok(nf,x, col,gen,ex)) col = NULL;
    1818      235371 :   if (!col && !ZV_equal0(ex))
    1819             :   {
    1820             :     /* in case isprincipalfact calls bnfinit() due to prec trouble...*/
    1821        1022 :     ex = gerepilecopy(av, ex);
    1822        1022 :     p1 = isprincipalfact(bnf, x, gen, ZC_neg(ex), flag);
    1823        1022 :     if (typ(p1) != t_VEC) return p1;
    1824        1022 :     col = gel(p1,2);
    1825             :   }
    1826      235371 :   if (col)
    1827             :   { /* add back missing content */
    1828      239792 :     if (xc) col = (typ(col)==t_MAT)? famat_mul_shallow(col,xc)
    1829        4459 :                                    : RgC_Rg_mul(col,xc);
    1830             :   }
    1831             :   else
    1832             :   {
    1833          38 :     if (e < 0) e = 0;
    1834          38 :     *ptprec = prec + nbits2extraprec(e + 128);
    1835          38 :     if (flag & nf_FORCE)
    1836             :     {
    1837          31 :       if (DEBUGLEVEL) pari_warn(warner,"precision too low for generators, e = %ld",e);
    1838          31 :       return NULL;
    1839             :     }
    1840           7 :     pari_warn(warner,"precision too low for generators, not given");
    1841           7 :     col = cgetg(1, t_COL);
    1842             :   }
    1843      235340 :   return (flag & nf_GEN_IF_PRINCIPAL)? col: mkvec2(ex, col);
    1844             : }
    1845             : 
    1846             : static GEN
    1847       12558 : triv_gen(GEN bnf, GEN x, long flag)
    1848             : {
    1849       12558 :   GEN y, nf = bnf_get_nf(bnf);
    1850             :   long c;
    1851       12558 :   if (flag & nf_GEN_IF_PRINCIPAL) return algtobasis(nf,x);
    1852       12558 :   c = lg(bnf_get_cyc(bnf)) - 1;
    1853       12558 :   if (!(flag & (nf_GEN|nf_GENMAT))) return zerocol(c);
    1854       11494 :   y = cgetg(3,t_VEC);
    1855       11494 :   gel(y,1) = zerocol(c);
    1856       11494 :   gel(y,2) = algtobasis(nf,x); return y;
    1857             : }
    1858             : 
    1859             : GEN
    1860      252580 : bnfisprincipal0(GEN bnf,GEN x,long flag)
    1861             : {
    1862             :   GEN arch, c;
    1863             :   long pr;
    1864      252580 :   pari_sp av = avma;
    1865             : 
    1866      252580 :   bnf = checkbnf(bnf);
    1867      252580 :   switch( idealtyp(&x, &arch) )
    1868             :   {
    1869             :     case id_PRINCIPAL:
    1870        6279 :       if (gequal0(x)) pari_err_DOMAIN("bnfisprincipal","ideal","=",gen_0,x);
    1871        6279 :       return triv_gen(bnf, x, flag);
    1872             :     case id_PRIME:
    1873      243354 :       if (pr_is_inert(x))
    1874        6279 :         return gerepileupto(av, triv_gen(bnf, gel(x,1), flag));
    1875      237075 :       x = idealhnf_two(bnf_get_nf(bnf), x);
    1876      237075 :       break;
    1877             :     case id_MAT:
    1878        2947 :       if (lg(x)==1) pari_err_DOMAIN("bnfisprincipal","ideal","=",gen_0,x);
    1879             :   }
    1880      240022 :   pr = prec_arch(bnf); /* precision of unit matrix */
    1881      240022 :   c = getrand();
    1882             :   for (;;)
    1883             :   {
    1884      240022 :     pari_sp av1 = avma;
    1885      240022 :     GEN y = isprincipalall(bnf,x,&pr,flag);
    1886      240022 :     if (y) return gerepilecopy(av, y);
    1887             : 
    1888           0 :     if (DEBUGLEVEL) pari_warn(warnprec,"isprincipal",pr);
    1889           0 :     avma = av1; bnf = bnfnewprec_shallow(bnf,pr); setrand(c);
    1890           0 :   }
    1891             : }
    1892             : GEN
    1893       53123 : isprincipal(GEN bnf,GEN x) { return bnfisprincipal0(bnf,x,0); }
    1894             : 
    1895             : /* FIXME: OBSOLETE */
    1896             : GEN
    1897           0 : isprincipalgen(GEN bnf,GEN x)
    1898           0 : { return bnfisprincipal0(bnf,x,nf_GEN); }
    1899             : GEN
    1900           0 : isprincipalforce(GEN bnf,GEN x)
    1901           0 : { return bnfisprincipal0(bnf,x,nf_FORCE); }
    1902             : GEN
    1903           0 : isprincipalgenforce(GEN bnf,GEN x)
    1904           0 : { return bnfisprincipal0(bnf,x,nf_GEN | nf_FORCE); }
    1905             : 
    1906             : /* lg(u) > 1 */
    1907             : static int
    1908       15499 : RgV_is1(GEN u) { return isint1(gel(u,1)) && RgV_isscalar(u); }
    1909             : static GEN
    1910       47426 : add_principal_part(GEN nf, GEN u, GEN v, long flag)
    1911             : {
    1912       47426 :   if (flag & nf_GENMAT)
    1913       15499 :     return (typ(u) == t_COL && RgV_is1(u))? v: famat_mul_shallow(v,u);
    1914             :   else
    1915       31927 :     return nfmul(nf, v, u);
    1916             : }
    1917             : 
    1918             : #if 0
    1919             : /* compute C prod P[i]^e[i],  e[i] >=0 for all i. C may be NULL (omitted)
    1920             :  * e destroyed ! */
    1921             : static GEN
    1922             : expand(GEN nf, GEN C, GEN P, GEN e)
    1923             : {
    1924             :   long i, l = lg(e), done = 1;
    1925             :   GEN id = C;
    1926             :   for (i=1; i<l; i++)
    1927             :   {
    1928             :     GEN ei = gel(e,i);
    1929             :     if (signe(ei))
    1930             :     {
    1931             :       if (mod2(ei)) id = id? idealmul(nf, id, gel(P,i)): gel(P,i);
    1932             :       ei = shifti(ei,-1);
    1933             :       if (signe(ei)) done = 0;
    1934             :       gel(e,i) = ei;
    1935             :     }
    1936             :   }
    1937             :   if (id != C) id = idealred(nf, id);
    1938             :   if (done) return id;
    1939             :   return idealmulred(nf, id, idealsqr(nf, expand(nf,id,P,e)));
    1940             : }
    1941             : /* C is an extended ideal, possibly with C[1] = NULL */
    1942             : static GEN
    1943             : expandext(GEN nf, GEN C, GEN P, GEN e)
    1944             : {
    1945             :   long i, l = lg(e), done = 1;
    1946             :   GEN A = gel(C,1);
    1947             :   for (i=1; i<l; i++)
    1948             :   {
    1949             :     GEN ei = gel(e,i);
    1950             :     if (signe(ei))
    1951             :     {
    1952             :       if (mod2(ei)) A = A? idealmul(nf, A, gel(P,i)): gel(P,i);
    1953             :       ei = shifti(ei,-1);
    1954             :       if (signe(ei)) done = 0;
    1955             :       gel(e,i) = ei;
    1956             :     }
    1957             :   }
    1958             :   if (A == gel(C,1))
    1959             :     A = C;
    1960             :   else
    1961             :     A = idealred(nf, mkvec2(A, gel(C,2)));
    1962             :   if (done) return A;
    1963             :   return idealmulred(nf, A, idealsqr(nf, expand(nf,A,P,e)));
    1964             : }
    1965             : #endif
    1966             : 
    1967             : static GEN
    1968           0 : expand(GEN nf, GEN C, GEN P, GEN e)
    1969             : {
    1970           0 :   long i, l = lg(e);
    1971           0 :   GEN B, A = C;
    1972           0 :   for (i=1; i<l; i++) /* compute prod P[i]^e[i] */
    1973           0 :     if (signe(gel(e,i)))
    1974             :     {
    1975           0 :       B = idealpowred(nf, gel(P,i), gel(e,i));
    1976           0 :       A = A? idealmulred(nf,A,B): B;
    1977             :     }
    1978           0 :   return A;
    1979             : }
    1980             : static GEN
    1981       47448 : expandext(GEN nf, GEN C, GEN P, GEN e)
    1982             : {
    1983       47448 :   long i, l = lg(e);
    1984       47448 :   GEN B, A = gel(C,1), C1 = A;
    1985      171565 :   for (i=1; i<l; i++) /* compute prod P[i]^e[i] */
    1986      124117 :     if (signe(gel(e,i)))
    1987             :     {
    1988       46843 :       gel(C,1) = gel(P,i);
    1989       46843 :       B = idealpowred(nf, C, gel(e,i));
    1990       46843 :       A = A? idealmulred(nf,A,B): B;
    1991             :     }
    1992       47448 :   return A == C1? C: A;
    1993             : }
    1994             : 
    1995             : /* isprincipal for C * \prod P[i]^e[i] (C omitted if NULL) */
    1996             : GEN
    1997       47418 : isprincipalfact(GEN bnf, GEN C, GEN P, GEN e, long flag)
    1998             : {
    1999       47418 :   const long gen = flag & (nf_GEN|nf_GENMAT|nf_GEN_IF_PRINCIPAL);
    2000             :   long prec;
    2001       47418 :   pari_sp av = avma;
    2002       47418 :   GEN C0, Cext, c, id, nf = checknf(bnf);
    2003             : 
    2004       47418 :   if (gen)
    2005             :   {
    2006       47418 :     Cext = (flag & nf_GENMAT)? cgetg(1, t_MAT): mkpolmod(gen_1,nf_get_pol(nf));
    2007       47418 :     C0 = mkvec2(C, Cext);
    2008       47418 :     id = expandext(nf, C0, P, e);
    2009             :   } else {
    2010           0 :     Cext = NULL;
    2011           0 :     C0 = C;
    2012           0 :     id = expand(nf, C, P, e);
    2013             :   }
    2014       47418 :   if (id == C0) /* e = 0 */
    2015             :   {
    2016       15190 :     if (!C) return bnfisprincipal0(bnf, gen_1, flag);
    2017       15183 :     C = idealhnf_shallow(nf,C);
    2018             :   }
    2019             :   else
    2020             :   {
    2021       32228 :     if (gen) { C = gel(id,1); Cext = gel(id,2); } else C = id;
    2022             :   }
    2023       47411 :   prec = prec_arch(bnf);
    2024       47411 :   c = getrand();
    2025             :   for (;;)
    2026             :   {
    2027       47427 :     pari_sp av1 = avma;
    2028       47427 :     GEN y = isprincipalall(bnf, C, &prec, flag);
    2029       47427 :     if (y)
    2030             :     {
    2031       47411 :       if (flag & nf_GEN_IF_PRINCIPAL)
    2032             :       {
    2033       43449 :         if (typ(y) == t_INT) { avma = av; return NULL; }
    2034       43449 :         y = add_principal_part(nf, y, Cext, flag);
    2035             :       }
    2036             :       else
    2037             :       {
    2038        3962 :         GEN u = gel(y,2);
    2039        3962 :         if (!gen || typ(y) != t_VEC) return gerepileupto(av,y);
    2040        3962 :         if (lg(u) != 1) gel(y,2) = add_principal_part(nf, u, Cext, flag);
    2041             :       }
    2042       47411 :       return gerepilecopy(av, y);
    2043             :     }
    2044          16 :     if (DEBUGLEVEL) pari_warn(warnprec,"isprincipal",prec);
    2045          16 :     avma = av1; bnf = bnfnewprec_shallow(bnf,prec); setrand(c);
    2046          16 :   }
    2047             : }
    2048             : GEN
    2049          30 : isprincipalfact_or_fail(GEN bnf, GEN C, GEN P, GEN e)
    2050             : {
    2051          30 :   const long flag = nf_GENMAT|nf_FORCE;
    2052             :   long prec;
    2053          30 :   pari_sp av = avma;
    2054          30 :   GEN u, y, id, C0, Cext, nf = bnf_get_nf(bnf);
    2055             : 
    2056          30 :   Cext = cgetg(1, t_MAT);
    2057          30 :   C0 = mkvec2(C, Cext);
    2058          30 :   id = expandext(nf, C0, P, e);
    2059          30 :   if (id == C0) /* e = 0 */
    2060          12 :     C = idealhnf_shallow(nf,C);
    2061             :   else {
    2062          18 :     C = gel(id,1); Cext = gel(id,2);
    2063             :   }
    2064          30 :   prec = prec_arch(bnf);
    2065          30 :   y = isprincipalall(bnf, C, &prec, flag);
    2066          30 :   if (!y) { avma = av; return utoipos(prec); }
    2067          15 :   u = gel(y,2);
    2068          15 :   if (lg(u) != 1) gel(y,2) = add_principal_part(nf, u, Cext, flag);
    2069          15 :   return gerepilecopy(av, y);
    2070             : }
    2071             : 
    2072             : /* if x a famat, assume it is an algebraic integer (very costly to check) */
    2073             : GEN
    2074        2310 : bnfisunit(GEN bnf,GEN x)
    2075             : {
    2076        2310 :   long tx = typ(x), i, R1, RU, e, n, prec;
    2077        2310 :   pari_sp av = avma;
    2078             :   GEN p1, v, rlog, logunit, ex, nf, pi2_sur_w, emb;
    2079             : 
    2080        2310 :   bnf = checkbnf(bnf); nf = bnf_get_nf(bnf);
    2081        2310 :   logunit = bnf_get_logfu(bnf); RU = lg(logunit);
    2082        2310 :   n = bnf_get_tuN(bnf); /* # { roots of 1 } */
    2083        2310 :   if (tx == t_MAT)
    2084             :   { /* famat, assumed integral */
    2085        1330 :     if (lg(x) != 3) pari_err_TYPE("bnfisunit [not a factorization]", x);
    2086             :   } else {
    2087         980 :     x = nf_to_scalar_or_basis(nf,x);
    2088         980 :     if (typ(x) != t_COL)
    2089             :     { /* rational unit ? */
    2090             :       long s;
    2091         126 :       if (typ(x) != t_INT || !is_pm1(x)) return cgetg(1,t_COL);
    2092         126 :       s = signe(x); avma = av; v = zerocol(RU);
    2093         126 :       gel(v,RU) = mkintmodu((s > 0)? 0: n>>1, n);
    2094         126 :       return v;
    2095             :     }
    2096         854 :     if (!isint1(Q_denom(x))) { avma = av; return cgetg(1,t_COL); }
    2097             :   }
    2098             : 
    2099        2184 :   R1 = nf_get_r1(nf); v = cgetg(RU+1,t_COL);
    2100        2184 :   for (i=1; i<=R1; i++) gel(v,i) = gen_1;
    2101        2184 :   for (   ; i<=RU; i++) gel(v,i) = gen_2;
    2102        2184 :   logunit = shallowconcat(logunit, v);
    2103             :   /* ex = fundamental units exponents */
    2104        2184 :   rlog = real_i(logunit);
    2105        2184 :   prec = nf_get_prec(nf);
    2106        2230 :   for (i=1;; i++)
    2107             :   {
    2108        2230 :     GEN rx = get_arch_real(nf,x,&emb, MEDDEFAULTPREC);
    2109        2230 :     if (rx)
    2110             :     {
    2111        2184 :       GEN logN = RgV_sum(rx); /* log(Nx), should be ~ 0 */
    2112        2184 :       if (gexpo(logN) > -20)
    2113             :       { /* precision problem ? */
    2114           7 :         if (typ(logN) != t_REAL) { avma = av; return cgetg(1,t_COL); } /*no*/
    2115           7 :         if (i == 1)
    2116             :         {
    2117           7 :           GEN N = nfnorm(nf, x);
    2118           7 :           if (!is_pm1(N)) { avma = av; return cgetg(1, t_COL); }
    2119             :         }
    2120             :       }
    2121             :       else
    2122             :       {
    2123        2177 :         ex = RgM_solve(rlog, rx);
    2124        2177 :         if (ex)
    2125             :         {
    2126        2177 :           ex = grndtoi(ex, &e);
    2127        2177 :           if (!signe(gel(ex,RU)) && e < -4) break;
    2128             :         }
    2129             :       }
    2130             :     }
    2131          46 :     if (i == 1)
    2132          23 :       prec = nbits2prec(gexpo(x) + 128);
    2133             :     else
    2134             :     {
    2135          23 :       if (i > 4) pari_err_PREC("bnfisunit");
    2136          23 :       prec = precdbl(prec);
    2137             :     }
    2138          46 :     if (DEBUGLEVEL) pari_warn(warnprec,"bnfisunit",prec);
    2139          46 :     nf = nfnewprec_shallow(nf, prec);
    2140          46 :   }
    2141             : 
    2142        2177 :   setlg(ex, RU); /* ZC */
    2143        2177 :   p1 = imag_i( row_i(logunit,1, 1,RU-1) );
    2144        2177 :   p1 = RgV_dotproduct(p1, ex); if (!R1) p1 = gmul2n(p1, -1);
    2145        2177 :   p1 = gsub(garg(gel(emb,1),prec), p1);
    2146             :   /* p1 = arg(the missing root of 1) */
    2147             : 
    2148        2177 :   pi2_sur_w = divru(mppi(prec), n>>1); /* 2pi / n */
    2149        2177 :   e = umodiu(roundr(divrr(p1, pi2_sur_w)), n);
    2150        2177 :   if (n > 2)
    2151             :   {
    2152         826 :     GEN z = algtobasis(nf, bnf_get_tuU(bnf)); /* primitive root of 1 */
    2153         826 :     GEN ro = RgV_dotproduct(row(nf_get_M(nf), 1), z);
    2154         826 :     GEN p2 = roundr(divrr(garg(ro, prec), pi2_sur_w));
    2155         826 :     e *= Fl_inv(umodiu(p2,n), n);
    2156         826 :     e %= n;
    2157             :   }
    2158             : 
    2159        2177 :   gel(ex,RU) = mkintmodu(e, n);
    2160        2177 :   setlg(ex, RU+1); return gerepilecopy(av, ex);
    2161             : }
    2162             : 
    2163             : GEN
    2164        5887 : nfsign_from_logarch(GEN LA, GEN invpi, GEN archp)
    2165             : {
    2166        5887 :   long l = lg(archp), i;
    2167        5887 :   GEN y = cgetg(l, t_VECSMALL);
    2168        5887 :   pari_sp av = avma;
    2169             : 
    2170       13804 :   for (i=1; i<l; i++)
    2171             :   {
    2172        7917 :     GEN c = ground( gmul(imag_i(gel(LA,archp[i])), invpi) );
    2173        7917 :     y[i] = mpodd(c)? 1: 0;
    2174             :   }
    2175        5887 :   avma = av; return y;
    2176             : }
    2177             : 
    2178             : GEN
    2179        5670 : nfsign_units(GEN bnf, GEN archp, int add_zu)
    2180             : {
    2181        5670 :   GEN invpi, y, A = bnf_get_logfu(bnf), nf = bnf_get_nf(bnf);
    2182        5670 :   long j = 1, RU = lg(A);
    2183             : 
    2184        5670 :   invpi = invr( mppi(nf_get_prec(nf)) );
    2185        5670 :   if (!archp) archp = identity_perm( nf_get_r1(nf) );
    2186        5670 :   if (add_zu) { RU++; A--; }
    2187        5670 :   y = cgetg(RU,t_MAT);
    2188        5670 :   if (add_zu)
    2189             :   {
    2190        4515 :     long w = bnf_get_tuN(bnf);
    2191       13307 :     gel(y, j++) = (w == 2)? const_vecsmall(lg(archp)-1, 1)
    2192        8792 :                           : cgetg(1, t_VECSMALL);
    2193             :   }
    2194        5670 :   for ( ; j < RU; j++) gel(y,j) = nfsign_from_logarch(gel(A,j), invpi, archp);
    2195        5670 :   return y;
    2196             : }
    2197             : 
    2198             : /* obsolete */
    2199             : GEN
    2200           7 : signunits(GEN bnf)
    2201             : {
    2202             :   pari_sp av;
    2203             :   GEN S, y, nf;
    2204             :   long i, j, r1, r2;
    2205             : 
    2206           7 :   bnf = checkbnf(bnf); nf = bnf_get_nf(bnf);
    2207           7 :   nf_get_sign(nf, &r1,&r2);
    2208           7 :   S = zeromatcopy(r1, r1+r2-1); av = avma;
    2209           7 :   y = nfsign_units(bnf, NULL, 0);
    2210          14 :   for (j = 1; j < lg(y); j++)
    2211             :   {
    2212           7 :     GEN Sj = gel(S,j), yj = gel(y,j);
    2213           7 :     for (i = 1; i <= r1; i++) gel(Sj,i) = yj[i]? gen_m1: gen_1;
    2214             :   }
    2215           7 :   avma = av; return S;
    2216             : }
    2217             : 
    2218             : static GEN
    2219       49017 : get_log_embed(REL_t *rel, GEN M, long RU, long R1, long prec)
    2220             : {
    2221       49017 :   GEN arch, C, z = rel->m;
    2222             :   long i;
    2223       49017 :   if (!z) return zerocol(RU);
    2224       36521 :   arch = typ(z) == t_COL? RgM_RgC_mul(M, z): RgC_Rg_mul(gel(M,1), z);
    2225       36521 :   C = cgetg(RU+1, t_COL); arch = glog(arch, prec);
    2226       36521 :   for (i=1; i<=R1; i++) gel(C,i) = gel(arch,i);
    2227       36521 :   for (   ; i<=RU; i++) gel(C,i) = gmul2n(gel(arch,i), 1);
    2228       36521 :   return C;
    2229             : }
    2230             : 
    2231             : static GEN
    2232       32017 : perm_log_embed(GEN C, GEN perm)
    2233             : {
    2234             :   long i, n;
    2235       32017 :   GEN Cnew = cgetg_copy(C, &n);
    2236      170849 :   for (i = 1; i < n; i++)
    2237             :   {
    2238      138832 :     long v = perm[i];
    2239      138832 :     if (v > 0)
    2240       95066 :       gel(Cnew, i) = gel(C, v);
    2241             :     else
    2242       43766 :       gel(Cnew, i) = gconj(gel(C, -v));
    2243             :   }
    2244       32017 :   return Cnew;
    2245             : }
    2246             : 
    2247             : static GEN
    2248      518853 : set_fact(FB_t *F, FACT *fact, GEN ex, long *pnz)
    2249             : {
    2250      518853 :   long i, n = fact[0].pr;
    2251             :   long nz;
    2252      518853 :   GEN c = zero_Flv(F->KC);
    2253      518853 :   if (!n) /* trivial factorization */
    2254           0 :     *pnz = F->KC+1;
    2255             :   else {
    2256      518853 :     nz = fact[1].pr;
    2257      518853 :     if (fact[n].pr < nz) /* Possible with jid in rnd_rel */
    2258         308 :       nz = fact[n].pr;
    2259      518853 :     for (i=1; i<=n; i++) c[fact[i].pr] = fact[i].ex;
    2260      518853 :     if (ex)
    2261             :     {
    2262       20903 :       for (i=1; i<lg(ex); i++)
    2263       16160 :         if (ex[i]) {
    2264       15213 :           long v = F->subFB[i];
    2265       15213 :           c[v] += ex[i];
    2266       15213 :           if (v < nz) nz = v;
    2267             :         }
    2268             :     }
    2269      518853 :     *pnz = nz;
    2270             :   }
    2271      518853 :   return c;
    2272             : }
    2273             : 
    2274             : /* Is cols already in the cache ? bs = index of first non zero coeff in cols
    2275             :  * General check for colinearity useless since exceedingly rare */
    2276             : static int
    2277      589687 : already_known(RELCACHE_t *cache, long bs, GEN cols)
    2278             : {
    2279             :   REL_t *r;
    2280      589687 :   long l = lg(cols);
    2281    45091460 :   for (r = cache->last; r > cache->base; r--)
    2282    44584079 :     if (bs == r->nz)
    2283             :     {
    2284     4014132 :       GEN coll = r->R;
    2285     4014132 :       long b = bs;
    2286     4014132 :       while (b < l && cols[b] == coll[b]) b++;
    2287     4014132 :       if (b == l) return 1;
    2288             :     }
    2289      507381 :   return 0;
    2290             : }
    2291             : 
    2292             : /* Add relation R to cache, nz = index of first non zero coeff in R.
    2293             :  * If relation is a linear combination of the previous ones, return 0.
    2294             :  * Otherwise, update basis and return > 0. Compute mod p (much faster)
    2295             :  * so some kernel vector might not be genuine. */
    2296             : static int
    2297      589827 : add_rel_i(RELCACHE_t *cache, GEN R, long nz, GEN m, long orig, long aut, REL_t **relp, long in_rnd_rel)
    2298             : {
    2299      589827 :   long i, k, n = lg(R)-1;
    2300             : 
    2301      589827 :   if (nz == n+1) { k = 0; goto ADD_REL; }
    2302      589687 :   if (already_known(cache, nz, R)) return -1;
    2303      507381 :   if (cache->last >= cache->base + cache->len) return 0;
    2304      507381 :   if (DEBUGLEVEL>6)
    2305             :   {
    2306           0 :     err_printf("adding vector = %Ps\n",R);
    2307           0 :     err_printf("generators =\n%Ps\n", cache->basis);
    2308             :   }
    2309      507381 :   if (cache->missing)
    2310             :   {
    2311      482959 :     GEN a = leafcopy(R), basis = cache->basis;
    2312      482959 :     k = lg(a);
    2313    23542539 :     do --k; while (!a[k]);
    2314     2082321 :     while (k)
    2315             :     {
    2316     1152365 :       GEN c = gel(basis, k);
    2317     1152365 :       if (c[k])
    2318             :       {
    2319     1116403 :         long ak = a[k];
    2320     1116403 :         for (i=1; i < k; i++) if (c[i]) a[i] = (a[i] + ak*(mod_p-c[i])) % mod_p;
    2321     1116403 :         a[k] = 0;
    2322    31794070 :         do --k; while (!a[k]); /* k cannot go below 0: codeword is a sentinel */
    2323             :       }
    2324             :       else
    2325             :       {
    2326       35962 :         ulong invak = Fl_inv(uel(a,k), mod_p);
    2327             :         /* Cleanup a */
    2328     1989835 :         for (i = k; i-- > 1; )
    2329             :         {
    2330     1917911 :           long j, ai = a[i];
    2331     1917911 :           c = gel(basis, i);
    2332     1917911 :           if (!ai || !c[i]) continue;
    2333       26347 :           ai = mod_p-ai;
    2334       26347 :           for (j = 1; j < i; j++) if (c[j]) a[j] = (a[j] + ai*c[j]) % mod_p;
    2335       26347 :           a[i] = 0;
    2336             :         }
    2337             :         /* Insert a/a[k] as k-th column */
    2338       35962 :         c = gel(basis, k);
    2339       35962 :         for (i = 1; i<k; i++) if (a[i]) c[i] = (a[i] * invak) % mod_p;
    2340       35962 :         c[k] = 1; a = c;
    2341             :         /* Cleanup above k */
    2342     1936871 :         for (i = k+1; i<n; i++)
    2343             :         {
    2344             :           long j, ck;
    2345     1900909 :           c = gel(basis, i);
    2346     1900909 :           ck = c[k];
    2347     1900909 :           if (!ck) continue;
    2348      373037 :           ck = mod_p-ck;
    2349      373037 :           for (j = 1; j < k; j++) if (a[j]) c[j] = (c[j] + ck*a[j]) % mod_p;
    2350      373037 :           c[k] = 0;
    2351             :         }
    2352       35962 :         cache->missing--;
    2353       35962 :         break;
    2354             :       }
    2355             :     }
    2356             :   }
    2357             :   else
    2358       24422 :     k = (cache->last - cache->base) + 1;
    2359      507381 :   if (k || cache->relsup > 0 || (m && in_rnd_rel))
    2360             :   {
    2361             :     REL_t *rel;
    2362             : 
    2363             : ADD_REL:
    2364       66699 :     rel = ++cache->last;
    2365       66699 :     if (!k && cache->relsup && nz < n+1)
    2366             :     {
    2367        6077 :       cache->relsup--;
    2368        6077 :       k = (rel - cache->base) + cache->missing;
    2369             :     }
    2370       66699 :     rel->R  = gclone(R);
    2371       66699 :     rel->m  =  m ? gclone(m) : NULL;
    2372       66699 :     rel->nz = nz;
    2373       66699 :     if (aut)
    2374             :     {
    2375       28433 :       rel->relorig = (rel - cache->base) - orig;
    2376       28433 :       rel->relaut = aut;
    2377             :     }
    2378             :     else
    2379       38266 :       rel->relaut = 0;
    2380       66699 :     if (relp) *relp = rel;
    2381       66699 :     if (DEBUGLEVEL) dbg_newrel(cache);
    2382             :   }
    2383      507521 :   return k;
    2384             : }
    2385             : 
    2386             : static int
    2387      529078 : add_rel(RELCACHE_t *cache, FB_t *F, GEN R, long nz, GEN m, long in_rnd_rel)
    2388             : {
    2389             :   REL_t *rel;
    2390             :   long k, l, reln;
    2391      529078 :   const long nauts = lg(F->idealperm), KC = F->KC;
    2392             : 
    2393      529078 :   k = add_rel_i(cache, R, nz, m, 0, 0, &rel, in_rnd_rel);
    2394      529078 :   if (k > 0 && m)
    2395             :   {
    2396       27943 :     GEN Rl = cgetg(KC+1, t_VECSMALL);
    2397       27943 :     reln = rel - cache->base;
    2398       88692 :     for (l = 1; l < nauts; l++)
    2399             :     {
    2400       60749 :       GEN perml = gel(F->idealperm, l);
    2401       60749 :       long i, nzl = perml[nz];
    2402             : 
    2403       60749 :       for (i = 1; i <= KC; i++) Rl[i] = 0;
    2404     4602872 :       for (i = nz; i <= KC; i++)
    2405     4542123 :         if (R[i])
    2406             :         {
    2407      224572 :           long v = perml[i];
    2408             : 
    2409      224572 :           if (v < nzl) nzl = v;
    2410      224572 :           Rl[v] = R[i];
    2411             :         }
    2412       60749 :       (void)add_rel_i(cache, Rl, nzl, NULL, reln, l, NULL, in_rnd_rel);
    2413             :     }
    2414             :   }
    2415      529078 :   return k;
    2416             : }
    2417             : 
    2418             : /* Compute powers of prime ideal (P^0,...,P^a) (a > 1) */
    2419             : static void
    2420         877 : powPgen(GEN nf, GEN vp, GEN *ppowP, long a)
    2421             : {
    2422             :   GEN id2, J;
    2423             :   long j;
    2424             : 
    2425         877 :   id2 = cgetg(a+1,t_VEC);
    2426         877 :   J = mkvec2(pr_get_p(vp), zk_scalar_or_multable(nf,pr_get_gen(vp)));
    2427         877 :   gel(id2,1) = J;
    2428         877 :   vp = idealhnf_two(nf,vp);
    2429       14032 :   for (j=2; j<=a; j++)
    2430             :   {
    2431       13155 :     if (DEBUGLEVEL>1) err_printf(" %ld", j);
    2432       13155 :     J = idealtwoelt(nf, idealHNF_mul(nf, vp, J));
    2433       13155 :     gel(J, 2) = zk_scalar_or_multable(nf, gel(J,2));
    2434       13155 :     gel(id2,j) = J;
    2435             :   }
    2436         877 :   setlg(id2, j);
    2437         877 :   *ppowP = id2;
    2438         877 :   if (DEBUGLEVEL>1) err_printf("\n");
    2439         877 : }
    2440             : 
    2441             : 
    2442             : /* Compute powers of prime ideals (P^0,...,P^a) in subFB (a > 1) */
    2443             : static void
    2444         455 : powFBgen(RELCACHE_t *cache, FB_t *F, GEN nf, GEN auts)
    2445             : {
    2446         455 :   const long a = 1L<<RANDOM_BITS;
    2447         455 :   pari_sp av = avma;
    2448         455 :   GEN subFB = F->subFB, idealperm = F->idealperm;
    2449         455 :   long i, k, l, id, n = lg(F->subFB), naut = lg(auts);
    2450             : 
    2451         455 :   if (DEBUGLEVEL) err_printf("Computing powers for subFB: %Ps\n",subFB);
    2452         455 :   if (cache) pre_allocate(cache, n*naut);
    2453        1885 :   for (i=1; i<n; i++)
    2454             :   {
    2455        1430 :     id = subFB[i];
    2456        1430 :     if (gel(F->id2, id) == gen_0)
    2457             :     {
    2458        1208 :       GEN id2 = NULL;
    2459             : 
    2460        4905 :       for (k = 1; k < naut; k++)
    2461             :       {
    2462        4028 :         long sigmaid = coeff(idealperm, id, k);
    2463        4028 :         GEN sigmaid2 = gel(F->id2, sigmaid);
    2464        4028 :         if (sigmaid2 != gen_0)
    2465             :         {
    2466         331 :           GEN aut = gel(auts, k), invaut = gel(auts, F->invs[k]);
    2467             :           long lid2;
    2468         331 :           id2 = cgetg_copy(sigmaid2, &lid2);
    2469         331 :           if (DEBUGLEVEL>1) err_printf("%ld: automorphism(%ld)\n", id,sigmaid);
    2470        5627 :           for (l = 1; l < lid2; l++)
    2471             :           {
    2472        5296 :             GEN id2l = gel(sigmaid2, l);
    2473       10592 :             gel(id2, l) =
    2474        5296 :               mkvec2(gel(id2l, 1), ZM_mul(ZM_mul(invaut, gel(id2l, 2)), aut));
    2475             :           }
    2476         331 :           break;
    2477             :         }
    2478             :       }
    2479        1208 :       if (!id2)
    2480             :       {
    2481         877 :         if (DEBUGLEVEL>1) err_printf("%ld: 1", id);
    2482         877 :         powPgen(nf, gel(F->LP, id), &id2, a);
    2483             :       }
    2484        1208 :       gel(F->id2, id) = gclone(id2);
    2485        1208 :       avma = av;
    2486             :     }
    2487             :   }
    2488         455 :   F->sfb_chg = 0;
    2489         455 :   F->newpow = 0;
    2490         455 : }
    2491             : 
    2492             : INLINE void
    2493     4523897 : step(GEN x, double *y, GEN inc, long k)
    2494             : {
    2495     4523897 :   if (!y[k])
    2496     1676550 :     x[k]++; /* leading coeff > 0 */
    2497             :   else
    2498             :   {
    2499     2847347 :     long i = inc[k];
    2500     2847347 :     x[k] += i;
    2501     2847347 :     inc[k] = (i > 0)? -1-i: 1-i;
    2502             :   }
    2503     4523897 : }
    2504             : 
    2505             : INLINE long
    2506      330982 : Fincke_Pohst_ideal(RELCACHE_t *cache, FB_t *F, GEN nf, GEN M,
    2507             :     GEN G, GEN ideal0, FACT *fact, long nbrelpid, FP_t *fp,
    2508             :     RNDREL_t *rr, long prec, long *nbsmallnorm, long *nbfact)
    2509             : {
    2510             :   pari_sp av;
    2511      330982 :   const long N = nf_get_degree(nf), R1 = nf_get_r1(nf);
    2512      330982 :   GEN r, u, gx, inc=const_vecsmall(N, 1), ideal;
    2513      330982 :   GEN Nideal = nbrelpid ? NULL : idealnorm(nf, ideal0);
    2514             :   double BOUND;
    2515      330982 :   long j, k, skipfirst, nbrelideal=0, dependent=0, try_elt=0,  try_factor=0;
    2516             : 
    2517      330982 :   u = ZM_lll(ZM_mul(F->G0, ideal0), 0.99, LLL_IM|LLL_COMPATIBLE);
    2518      330982 :   ideal = ZM_mul(ideal0,u); /* approximate T2-LLL reduction */
    2519      330982 :   r = gaussred_from_QR(RgM_mul(G, ideal), prec); /* Cholesky for T2 | ideal */
    2520      330982 :   if (!r) pari_err_BUG("small_norm (precision too low)");
    2521             : 
    2522      330982 :   skipfirst = ZV_isscalar(gel(ideal,1))? 1: 0; /* 1 probable */
    2523     1327552 :   for (k=1; k<=N; k++)
    2524             :   {
    2525      996570 :     fp->v[k] = gtodouble(gcoeff(r,k,k));
    2526      996570 :     for (j=1; j<k; j++) fp->q[j][k] = gtodouble(gcoeff(r,j,k));
    2527      996570 :     if (DEBUGLEVEL>3) err_printf("fp->v[%ld]=%.4g ",k,fp->v[k]);
    2528             :   }
    2529      330982 :   BOUND = mindd(BMULT*fp->v[1], 2*(fp->v[2]+fp->v[1]*fp->q[1][2]*fp->q[1][2]));
    2530             :   /* BOUND at most BMULT fp->x smallest known vector */
    2531      330982 :   if (DEBUGLEVEL>1)
    2532             :   {
    2533           0 :     if (DEBUGLEVEL>3) err_printf("\n");
    2534           0 :     err_printf("BOUND = %.4g\n",BOUND); err_flush();
    2535             :   }
    2536      330982 :   BOUND *= 1 + 1e-6;
    2537      330982 :   k = N; fp->y[N] = fp->z[N] = 0; fp->x[N] = 0;
    2538     1299180 :   for (av = avma;; avma = av, step(fp->x,fp->y,inc,k))
    2539             :   {
    2540             :     GEN R;
    2541             :     long nz;
    2542             :     do
    2543             :     { /* look for primitive element of small norm, cf minim00 */
    2544     2605659 :       int fl = 0;
    2545             :       double p;
    2546     2605659 :       if (k > 1)
    2547             :       {
    2548     1637461 :         long l = k-1;
    2549     1637461 :         fp->z[l] = 0;
    2550     1637461 :         for (j=k; j<=N; j++) fp->z[l] += fp->q[l][j]*fp->x[j];
    2551     1637461 :         p = (double)fp->x[k] + fp->z[k];
    2552     1637461 :         fp->y[l] = fp->y[k] + p*p*fp->v[k];
    2553     1637461 :         if (l <= skipfirst && !fp->y[1]) fl = 1;
    2554     1637461 :         fp->x[l] = (long)floor(-fp->z[l] + 0.5);
    2555     1637461 :         k = l;
    2556             :       }
    2557     1590259 :       for(;; step(fp->x,fp->y,inc,k))
    2558             :       {
    2559     4523754 :         if (++try_elt > maxtry_ELEMENT) return 0;
    2560     4195918 :         if (!fl)
    2561             :         {
    2562     3936948 :           p = (double)fp->x[k] + fp->z[k];
    2563     3936948 :           if (fp->y[k] + p*p*fp->v[k] <= BOUND) break;
    2564             : 
    2565     1965440 :           step(fp->x,fp->y,inc,k);
    2566             : 
    2567     1965440 :           p = (double)fp->x[k] + fp->z[k];
    2568     1965440 :           if (fp->y[k] + p*p*fp->v[k] <= BOUND) break;
    2569             :         }
    2570     1910559 :         fl = 0; inc[k] = 1;
    2571     1910559 :         if (++k > N) return 0;
    2572     1590259 :       }
    2573     2285359 :     } while (k > 1);
    2574             : 
    2575             :     /* element complete */
    2576     1928949 :     if (zv_content(fp->x) !=1) continue; /* not primitive */
    2577      898502 :     gx = ZM_zc_mul(ideal,fp->x);
    2578      898502 :     if (ZV_isscalar(gx)) continue;
    2579      892515 :     if (++try_factor > maxtry_FACT) return 0;
    2580             : 
    2581      892508 :     if (!nbrelpid)
    2582             :     {
    2583          63 :       if (!factorgen(F,nf,ideal0,Nideal,gx,fact))
    2584          49 :          continue;
    2585          14 :       return 1;
    2586             :     }
    2587      892445 :     else if (rr)
    2588             :     {
    2589       50249 :       if (!factorgen(F,nf,ideal0,rr->Nideal,gx,fact))
    2590       45506 :          continue;
    2591        4743 :       add_to_fact(rr->jid, 1, fact);
    2592        4743 :       gx = nfmul(nf, rr->m1, gx);
    2593             :     }
    2594             :     else
    2595             :     {
    2596      842196 :       GEN Nx, xembed = RgM_RgC_mul(M, gx);
    2597             :       long e;
    2598      842196 :       if (nbsmallnorm) (*nbsmallnorm)++;
    2599      842196 :       Nx = grndtoi(embed_norm(xembed, R1), &e);
    2600      842196 :       if (e >= 0) {
    2601           0 :         if (DEBUGLEVEL > 1) { err_printf("+"); err_flush(); }
    2602      329744 :         continue;
    2603             :       }
    2604      842196 :       if (!can_factor(F, nf, NULL, gx, Nx, fact)) continue;
    2605             :     }
    2606             : 
    2607             :     /* smooth element */
    2608      517195 :     R = set_fact(F, fact, rr ? rr->ex : NULL, &nz);
    2609             :     /* make sure we get maximal rank first, then allow all relations */
    2610      517195 :     if (add_rel(cache, F, R, nz, gx, rr ? 1 : 0) <= 0)
    2611             :     { /* probably Q-dependent from previous ones: forget it */
    2612      489294 :       if (DEBUGLEVEL>1) err_printf("*");
    2613      492440 :       if (++dependent > maxtry_DEP) break;
    2614      488405 :       continue;
    2615             :     }
    2616       27901 :     dependent = 0;
    2617       27901 :     if (DEBUGLEVEL && nbfact) (*nbfact)++;
    2618       27901 :     if (cache->last >= cache->end) return 1; /* we have enough */
    2619       20386 :     if (++nbrelideal == nbrelpid) break;
    2620      968198 :   }
    2621        3146 :   return 0;
    2622             : }
    2623             : 
    2624             : static void
    2625       15518 : small_norm(RELCACHE_t *cache, FB_t *F, GEN nf, long nbrelpid, GEN M,
    2626             :            FACT *fact, GEN p0)
    2627             : {
    2628             :   pari_timer T;
    2629       15518 :   const long prec = nf_get_prec(nf);
    2630             :   FP_t fp;
    2631             :   pari_sp av;
    2632       15518 :   GEN G = nf_get_G(nf), L_jid = F->L_jid;
    2633       15518 :   long nbsmallnorm, nbfact, noideal = lg(L_jid);
    2634       15518 :   REL_t *last = cache->last;
    2635             : 
    2636       15518 :   if (DEBUGLEVEL)
    2637             :   {
    2638           0 :     timer_start(&T);
    2639           0 :     err_printf("\n#### Look for %ld relations in %ld ideals (small_norm)\n",
    2640           0 :                cache->end - last, lg(L_jid)-1);
    2641             :   }
    2642       15518 :   nbsmallnorm = nbfact = 0;
    2643             : 
    2644       15518 :   minim_alloc(lg(M), &fp.q, &fp.x, &fp.y, &fp.z, &fp.v);
    2645      328271 :   for (av = avma; --noideal; avma = av)
    2646             :   {
    2647      317779 :     GEN ideal=gel(F->LP,L_jid[noideal]);
    2648             : 
    2649      317779 :     if (DEBUGLEVEL>1)
    2650           0 :       err_printf("\n*** Ideal no %ld: %Ps\n", L_jid[noideal], vecslice(ideal,1,4));
    2651      317779 :     else if (DEBUGLEVEL)
    2652           0 :       err_printf("(%ld) ", L_jid[noideal]);
    2653      317779 :     if (p0)
    2654      300407 :       ideal = idealmul(nf, p0, ideal);
    2655             :     else
    2656       17372 :       ideal = idealhnf_two(nf, ideal);
    2657      317779 :     if (Fincke_Pohst_ideal(cache, F, nf, M, G, ideal, fact,
    2658             :           nbrelpid, &fp, NULL, prec, &nbsmallnorm, &nbfact))
    2659        5026 :       break;
    2660      312753 :     if (DEBUGLEVEL>1) timer_printf(&T, "for this ideal");
    2661             :   }
    2662       15518 :   if (DEBUGLEVEL)
    2663             :   {
    2664           0 :     err_printf("\n");
    2665           0 :     timer_printf(&T, "small norm relations");
    2666           0 :     if (nbsmallnorm && DEBUGLEVEL > 1)
    2667           0 :       err_printf("  nb. fact./nb. small norm = %ld/%ld = %.3f\n",
    2668           0 :                   nbfact,nbsmallnorm,((double)nbfact)/nbsmallnorm);
    2669             :   }
    2670       15518 : }
    2671             : 
    2672             : /* I integral ideal in HNF form */
    2673             : static GEN
    2674        3071 : remove_content(GEN I)
    2675             : {
    2676        3071 :   long N = lg(I)-1;
    2677        3071 :   if (!is_pm1(gcoeff(I,N,N))) I = Q_primpart(I);
    2678        3071 :   return I;
    2679             : }
    2680             : 
    2681             : static GEN
    2682        3071 : get_random_ideal(FB_t *F, GEN nf, GEN ex)
    2683             : {
    2684        3071 :   long l = lg(ex);
    2685             :   for (;;) {
    2686        3071 :     GEN ideal = NULL;
    2687             :     long i;
    2688       13875 :     for (i=1; i<l; i++)
    2689             :     {
    2690       10804 :       long id = F->subFB[i];
    2691       10804 :       ex[i] = random_bits(RANDOM_BITS);
    2692       10804 :       if (ex[i])
    2693             :       {
    2694       10023 :         GEN a = gmael(F->id2,id,ex[i]);
    2695       10023 :         ideal = ideal? idealHNF_mul(nf,ideal, a): idealhnf_two(nf,a);
    2696             :       }
    2697             :     }
    2698        3071 :     if (ideal) { /* ex  != 0 */
    2699        3071 :       ideal = remove_content(ideal);
    2700        6142 :       if (!is_pm1(gcoeff(ideal,1,1))) return ideal; /* ideal != Z_K */
    2701             :     }
    2702           0 :   }
    2703             : }
    2704             : 
    2705             : static void
    2706        3071 : rnd_rel(RELCACHE_t *cache, FB_t *F, GEN nf, FACT *fact)
    2707             : {
    2708             :   pari_timer T;
    2709        3071 :   const GEN L_jid = F->L_jid, M = nf_get_M(nf), G = F->G0;
    2710             :   GEN baseideal;
    2711             :   RNDREL_t rr;
    2712             :   FP_t fp;
    2713        3071 :   const long nbG = lg(F->vecG)-1, lgsub = lg(F->subFB), l_jid = lg(L_jid);
    2714        3071 :   const long prec = nf_get_prec(nf);
    2715             :   long jlist;
    2716             :   pari_sp av;
    2717             : 
    2718             :   /* will compute P[ L_jid[i] ] * (random product from subFB) */
    2719        3071 :   if (DEBUGLEVEL) {
    2720           0 :     timer_start(&T);
    2721           0 :     err_printf("\n#### Look for %ld relations in %ld ideals (rnd_rel)\n",
    2722           0 :                cache->end - cache->last, lg(L_jid)-1);
    2723             :   }
    2724        3071 :   rr.ex = cgetg(lgsub, t_VECSMALL);
    2725        3071 :   baseideal = get_random_ideal(F, nf, rr.ex);
    2726        3071 :   baseideal = red(nf, baseideal, F->G0, &rr.m1);
    2727        3071 :   baseideal = idealhnf_two(nf, baseideal);
    2728        3071 :   minim_alloc(lg(M), &fp.q, &fp.x, &fp.y, &fp.z, &fp.v);
    2729       13771 :   for (av = avma, jlist = 1; jlist < l_jid; jlist++, avma = av)
    2730             :   {
    2731             :     long j;
    2732             :     GEN ideal;
    2733             :     pari_sp av1;
    2734       13189 :     REL_t *last = cache->last;
    2735             : 
    2736       13189 :     rr.jid = L_jid[jlist];
    2737       13189 :     ideal = gel(F->LP,rr.jid);
    2738       13189 :     if (DEBUGLEVEL>1)
    2739           0 :       err_printf("\n*** Ideal no %ld: %Ps\n", rr.jid, vecslice(ideal,1,4));
    2740       13189 :     else if (DEBUGLEVEL)
    2741           0 :       err_printf("(%ld) ", rr.jid);
    2742       13189 :     ideal = idealHNF_mul(nf, baseideal, ideal);
    2743       13189 :     rr.Nideal = ZM_det_triangular(ideal);
    2744       13189 :     if (Fincke_Pohst_ideal(cache, F, nf, M, G, ideal, fact,
    2745             :                            RND_REL_RELPID, &fp, &rr, prec, NULL, NULL))
    2746        2489 :       break;
    2747       10700 :     if (PREVENT_LLL_IN_RND_REL || cache->last != last) continue;
    2748           0 :     for (av1 = avma, j = 1; j <= nbG; j++, avma = av1)
    2749             :     { /* reduce along various directions */
    2750           0 :       GEN m = idealpseudomin_nonscalar(ideal, gel(F->vecG,j));
    2751             :       GEN R;
    2752             :       long nz;
    2753           0 :       if (!factorgen(F,nf,ideal,rr.Nideal,m,fact)) continue;
    2754             :       /* can factor ideal, record relation */
    2755           0 :       add_to_fact(rr.jid, 1, fact);
    2756           0 :       R = set_fact(F, fact, rr.ex, &nz);
    2757           0 :       switch (add_rel(cache, F, R, nz, nfmul(nf, m, rr.m1), 1))
    2758             :       {
    2759             :         case -1: /* forget it */
    2760           0 :           if (DEBUGLEVEL>1) dbg_cancelrel(rr.jid,j,R);
    2761           0 :           continue;
    2762             :       }
    2763           0 :       if (DEBUGLEVEL) timer_printf(&T, "for this relation");
    2764             :       /* Need more, try next prime ideal */
    2765           0 :       if (cache->last < cache->end) break;
    2766             :       /* We have found enough. Return */
    2767        3071 :       avma = av; return;
    2768             :     }
    2769             :   }
    2770        3071 :   if (DEBUGLEVEL)
    2771             :   {
    2772           0 :     err_printf("\n");
    2773           0 :     timer_printf(&T, "for remaining ideals");
    2774             :   }
    2775             : }
    2776             : 
    2777             : static GEN
    2778        1897 : automorphism_perms(GEN M, GEN auts, GEN cyclic, long N)
    2779             : {
    2780             :   pari_sp av;
    2781        1897 :   const long r1plusr2 = lgcols(M), r1 = 2*r1plusr2-N-2, r2 = r1plusr2-r1-1;
    2782        1897 :   long nauts = lg(auts), ncyc = lg(cyclic), i, j, l, m;
    2783        1897 :   GEN Mt, perms = cgetg(nauts, t_VEC);
    2784             : 
    2785        4749 :   for (l = 1; l < nauts; l++)
    2786        2852 :     gel(perms, l) = cgetg(r1plusr2, t_VECSMALL);
    2787        1897 :   av = avma;
    2788        1897 :   Mt = shallowtrans(gprec_w(M, 3)); /* need little accuracy */
    2789        1897 :   Mt = shallowconcat(Mt, gconj(vecslice(Mt, r1+1, r1+r2)));
    2790        4182 :   for (l = 1; l < ncyc; l++)
    2791             :   {
    2792        2285 :     GEN thiscyc = gel(cyclic, l);
    2793        2285 :     long k = thiscyc[1];
    2794        2285 :     GEN Nt = RgM_mul(shallowtrans(gel(auts, k)), Mt);
    2795        2285 :     GEN perm = gel(perms, k), permprec;
    2796        2285 :     pari_sp av2 = avma;
    2797        8750 :     for (i = 1; i < r1plusr2; i++, avma = av2)
    2798             :     {
    2799        6465 :       GEN vec = gel(Nt, i), minnorm;
    2800        6465 :       minnorm = gnorml2(gsub(vec, gel(Mt, 1)));
    2801        6465 :       perm[i] = 1;
    2802       42797 :       for (j = 2; j <= N; j++)
    2803             :       {
    2804       36332 :         GEN thisnorm = gnorml2(gsub(vec, gel(Mt, j)));
    2805       36332 :         if (gcmp(thisnorm, minnorm) < 0)
    2806             :         {
    2807        8666 :           minnorm = thisnorm;
    2808        8666 :           perm[i] = j >= r1plusr2 ? r2-j : j;
    2809             :         }
    2810             :       }
    2811             :     }
    2812        2957 :     for (permprec = perm, m = 2; m < lg(thiscyc); m++)
    2813             :     {
    2814         672 :       GEN thisperm = gel(perms, thiscyc[m]);
    2815        3934 :       for (i = 1; i < r1plusr2; i++)
    2816             :       {
    2817        3262 :         long pp = labs(permprec[i]);
    2818        3262 :         thisperm[i] = permprec[i] < 0 ? -perm[pp] : perm[pp];
    2819             :       }
    2820         672 :       permprec = thisperm;
    2821             :     }
    2822             :   }
    2823        1897 :   avma = av;
    2824        1897 :   return perms;
    2825             : }
    2826             : 
    2827             : /* Determine the field automorphisms and its matrix in the integral basis. */
    2828             : static GEN
    2829        1946 : automorphism_matrices(GEN nf, GEN *invp, GEN *cycp)
    2830             : {
    2831        1946 :   pari_sp av = avma;
    2832        1946 :   GEN auts = galoisconj(nf, NULL), mats, cyclic, cyclicidx;
    2833             :   GEN invs;
    2834        1946 :   long nauts = lg(auts)-1, i, j, k, l;
    2835             : 
    2836        1946 :   cyclic = cgetg(nauts+1, t_VEC);
    2837        1946 :   cyclicidx = zero_Flv(nauts);
    2838        1946 :   invs = zero_Flv(nauts-1);
    2839        2254 :   for (l = 1; l <= nauts; l++)
    2840             :   {
    2841        2254 :     GEN aut = gel(auts, l);
    2842        2254 :     if (gequalX(aut)) { swap(gel(auts, l), gel(auts, nauts)); break; }
    2843             :   }
    2844             :   /* trivial automorphism is last */
    2845        1946 :   for (l = 1; l <= nauts; l++) gel(auts, l) = algtobasis(nf, gel(auts, l));
    2846             :   /* Compute maximal cyclic subgroups */
    2847        6765 :   for (l = nauts; --l > 0; )
    2848        2873 :     if (!cyclicidx[l])
    2849             :     {
    2850        2397 :       GEN elt = gel(auts, l), aut = elt, cyc = cgetg(nauts+1, t_VECSMALL);
    2851        2397 :       cyclicidx[l] = l;
    2852        2397 :       cyc[1] = l;
    2853        2397 :       j = 1;
    2854             :       do
    2855             :       {
    2856        3076 :         elt = galoisapply(nf, elt, aut);
    2857        3076 :         for (k = 1; k <= nauts; k++) if (gequal(elt, gel(auts, k))) break;
    2858        3076 :         cyclicidx[k] = l;
    2859        3076 :         cyc[++j] = k;
    2860             :       }
    2861        3076 :       while (k != nauts);
    2862        2397 :       setlg(cyc, j);
    2863        2397 :       gel(cyclic, l) = cyc;
    2864             :       /* Store the inverses */
    2865        5095 :       for (i = 1; i <= j/2; i++)
    2866             :       {
    2867        2698 :         invs[cyc[i]] = cyc[j-i];
    2868        2698 :         invs[cyc[j-i]] = cyc[i];
    2869             :       }
    2870             :     }
    2871        4819 :   for (i = j = 1; i < nauts; i++)
    2872        2873 :     if (cyclicidx[i] == i) cyclic[j++] = cyclic[i];
    2873        1946 :   setlg(cyclic, j);
    2874        1946 :   mats = cgetg(nauts, t_VEC);
    2875        6198 :   while (--j > 0)
    2876             :   {
    2877        2306 :     GEN cyc = gel(cyclic, j);
    2878        2306 :     long id = cyc[1];
    2879        2306 :     GEN M, Mi, aut = gel(auts, id);
    2880             : 
    2881        2306 :     gel(mats, id) = Mi = M = nfgaloismatrix(nf, aut);
    2882        2978 :     for (i = 2; i < lg(cyc); i++)
    2883             :     {
    2884         672 :       Mi = ZM_mul(Mi, M);
    2885         672 :       gel(mats, cyc[i]) = Mi;
    2886             :     }
    2887             :   }
    2888        1946 :   gerepileall(av, 3, &mats, &invs, &cyclic);
    2889        1946 :   if (invp) *invp = invs;
    2890        1946 :   if (cycp) *cycp = cyclic;
    2891        1946 :   return mats;
    2892             : }
    2893             : 
    2894             : /* vP a list of maximal ideals above the same p from idealprimedec: f(P/p) is
    2895             :  * increasing; 1 <= j <= #vP; orbit a zc of length <= #vP; auts a vector of
    2896             :  * automorphisms in ZM form.
    2897             :  * Set orbit[i] = 1 for all vP[i], i >= j, in the orbit of pr = vP[j] wrt auts.
    2898             :  * N.B.1 orbit need not be initialized to 0: useful to incrementally run
    2899             :  * through successive orbits
    2900             :  * N.B.2 i >= j, so primes with index < j will be missed; run incrementally
    2901             :  * starting from j = 1 ! */
    2902             : static void
    2903       11851 : pr_orbit_fill(GEN orbit, GEN auts, GEN vP, long j)
    2904             : {
    2905       11851 :   GEN pr = gel(vP,j), gen = pr_get_gen(pr);
    2906       11851 :   long i, l = lg(auts), J = lg(orbit), f = pr_get_f(pr);
    2907       11851 :   orbit[j] = 1;
    2908       23702 :   for (i = 1; i < l; i++)
    2909             :   {
    2910       11851 :     GEN g = ZM_ZC_mul(gel(auts,i), gen);
    2911             :     long k;
    2912       11858 :     for (k = j+1; k < J; k++)
    2913             :     {
    2914          21 :       GEN prk = gel(vP,k);
    2915          21 :       if (pr_get_f(prk) > f) break; /* f(P[k]) increases with k */
    2916             :       /* don't check that e matches: (almost) always 1 ! */
    2917          21 :       if (!orbit[k] && ZC_prdvd(g, prk)) { orbit[k] = 1; break; }
    2918             :     }
    2919             :   }
    2920       11851 : }
    2921             : /* remark: F->KCZ changes if be_honest() fails */
    2922             : static int
    2923           7 : be_honest(FB_t *F, GEN nf, GEN auts, FACT *fact)
    2924             : {
    2925             :   long ex, i, iz, nbtest;
    2926           7 :   long lgsub = lg(F->subFB), KCZ0 = F->KCZ;
    2927           7 :   long N = nf_get_degree(nf), prec = nf_get_prec(nf);
    2928           7 :   GEN M = nf_get_M(nf), G = nf_get_G(nf);
    2929             :   FP_t fp;
    2930             :   pari_sp av;
    2931             : 
    2932           7 :   if (DEBUGLEVEL) {
    2933           0 :     err_printf("Be honest for %ld primes from %ld to %ld\n", F->KCZ2 - F->KCZ,
    2934           0 :                F->FB[ F->KCZ+1 ], F->FB[ F->KCZ2 ]);
    2935             :   }
    2936           7 :   minim_alloc(N+1, &fp.q, &fp.x, &fp.y, &fp.z, &fp.v);
    2937           7 :   if (lg(auts) == 1) auts = NULL;
    2938           7 :   av = avma;
    2939          14 :   for (iz=F->KCZ+1; iz<=F->KCZ2; iz++, avma = av)
    2940             :   {
    2941           7 :     long p = F->FB[iz];
    2942           7 :     GEN pr_orbit, P = F->LV[p];
    2943           7 :     long j, J = lg(P); /* > 1 */
    2944             :     /* the P|p, NP > C2 are assumed in subgroup generated by FB + last P
    2945             :      * with NP <= C2 is unramified --> check all but last */
    2946           7 :     if (pr_get_e(gel(P,J-1)) == 1) J--;
    2947           7 :     if (J == 1) continue;
    2948           7 :     if (DEBUGLEVEL>1) err_printf("%ld ", p);
    2949           7 :     pr_orbit = auts? zero_zv(J-1): NULL;
    2950          28 :     for (j = 1; j < J; j++)
    2951             :     {
    2952             :       GEN ideal, ideal0;
    2953          21 :       if (pr_orbit)
    2954             :       {
    2955          21 :         if (pr_orbit[j]) continue;
    2956             :         /* discard all primes in automorphism orbit simultaneously */
    2957          14 :         pr_orbit_fill(pr_orbit, auts, P, j);
    2958             :       }
    2959          14 :       ideal = ideal0 = idealhnf_two(nf,gel(P,j));
    2960          14 :       for (nbtest=0;;)
    2961             :       {
    2962          14 :         if (Fincke_Pohst_ideal(NULL, F, nf, M, G, ideal, fact, 0, &fp,
    2963          14 :                                NULL, prec, NULL, NULL)) break;
    2964           0 :         if (++nbtest > maxtry_HONEST)
    2965             :         {
    2966           0 :           if (DEBUGLEVEL)
    2967           0 :             pari_warn(warner,"be_honest() failure on prime %Ps\n", gel(P,j));
    2968           0 :           return 0;
    2969             :         }
    2970           0 :         ideal = ideal0;
    2971             :         /* occurs at most once in the whole function */
    2972           0 :         if (F->newpow) powFBgen(NULL, F, nf, auts);
    2973           0 :         for (i=1; i<lgsub; i++)
    2974             :         {
    2975           0 :           long id = F->subFB[i];
    2976           0 :           ex = random_bits(RANDOM_BITS);
    2977           0 :           if (ex) ideal = idealHNF_mul(nf,ideal, gmael(F->id2,id,ex));
    2978             :         }
    2979           0 :         ideal = remove_content(ideal);
    2980           0 :       }
    2981             :     }
    2982           7 :     F->KCZ++; /* SUCCESS, "enlarge" factorbase */
    2983             :   }
    2984           7 :   F->KCZ = KCZ0; avma = av; return 1;
    2985             : }
    2986             : 
    2987             : /* all primes with N(P) <= BOUND factor on factorbase ? */
    2988             : void
    2989          49 : bnftestprimes(GEN bnf, GEN BOUND)
    2990             : {
    2991          49 :   pari_sp av0 = avma, av;
    2992          49 :   ulong count = 0;
    2993          49 :   GEN auts, p, nf = bnf_get_nf(bnf), Vbase = bnf_get_vbase(bnf);
    2994          49 :   GEN fb = gen_sort(Vbase, (void*)&cmp_prime_ideal, cmp_nodata); /*tablesearch*/
    2995          49 :   ulong pmax = itou( pr_get_p(gel(fb, lg(fb)-1)) ); /*largest p in factorbase*/
    2996             :   forprime_t S;
    2997             :   FACT *fact;
    2998             :   FB_t F;
    2999             : 
    3000          49 :   (void)recover_partFB(&F, Vbase, nf_get_degree(nf));
    3001          49 :   fact = (FACT*)stack_malloc((F.KC+1)*sizeof(FACT));
    3002          49 :   forprime_init(&S, gen_2, BOUND);
    3003          49 :   auts = automorphism_matrices(nf, NULL, NULL);
    3004          49 :   if (lg(auts) == 1) auts = NULL;
    3005          49 :   av = avma;
    3006       37240 :   while (( p = forprime_next(&S) ))
    3007             :   {
    3008             :     GEN pr_orbit, vP;
    3009             :     long j, J;
    3010             : 
    3011       37142 :     if (DEBUGLEVEL == 1 && ++count > 1000)
    3012             :     {
    3013           0 :       err_printf("passing p = %Ps / %Ps\n", p, BOUND);
    3014           0 :       count = 0;
    3015             :     }
    3016       37142 :     avma = av;
    3017       37142 :     vP = idealprimedec_limit_norm(bnf, p, BOUND);
    3018       37142 :     J = lg(vP);
    3019             :     /* if last is unramified, all P|p in subgroup generated by FB: skip last */
    3020       37142 :     if (J > 1 && pr_get_e(gel(vP,J-1)) == 1) J--;
    3021       37142 :     if (J == 1) continue;
    3022       14434 :     if (DEBUGLEVEL>1) err_printf("*** p = %Ps\n",p);
    3023       14434 :     pr_orbit = auts? zero_zv(J-1): NULL;
    3024       31325 :     for (j = 1; j < J; j++)
    3025             :     {
    3026       16891 :       GEN P = gel(vP,j);
    3027             :       long k;
    3028       16891 :       if (pr_orbit)
    3029             :       {
    3030       11844 :         if (pr_orbit[j]) continue;
    3031             :         /* discard all primes in automorphism orbit simultaneously */
    3032       11837 :         pr_orbit_fill(pr_orbit, auts, vP, j);
    3033             :       }
    3034       16884 :       if (DEBUGLEVEL>1) err_printf("  Testing P = %Ps\n",P);
    3035       16884 :       if (abscmpiu(p, pmax) <= 0 && (k = tablesearch(fb, P, &cmp_prime_ideal)))
    3036         546 :       { if (DEBUGLEVEL>1) err_printf("    #%ld in factor base\n",k); }
    3037       16338 :       else if (DEBUGLEVEL>1)
    3038           0 :         err_printf("    is %Ps\n", isprincipal(bnf,P));
    3039             :       else /* faster: don't compute result */
    3040       16338 :         (void)SPLIT(&F, nf, idealhnf_two(nf,P), Vbase, fact);
    3041             :     }
    3042             :   }
    3043          49 :   avma = av0;
    3044          49 : }
    3045             : 
    3046             : /* A t_MAT of complex floats, in fact reals. Extract a submatrix B
    3047             :  * whose columns are definitely non-0, i.e. gexpo(A[j]) >= -2
    3048             :  *
    3049             :  * If possible precision problem (t_REAL 0 with large exponent), set
    3050             :  * *precpb to 1 */
    3051             : static GEN
    3052        8315 : clean_cols(GEN A, int *precpb)
    3053             : {
    3054        8315 :   long l = lg(A), h, i, j, k;
    3055             :   GEN B;
    3056        8315 :   *precpb = 0;
    3057        8315 :   if (l == 1) return A;
    3058        8315 :   h = lgcols(A);;
    3059        8315 :   B = cgetg(l, t_MAT);
    3060      887983 :   for (i = k = 1; i < l; i++)
    3061             :   {
    3062      879668 :     GEN Ai = gel(A,i);
    3063      879668 :     int non0 = 0;
    3064     4429020 :     for (j = 1; j < h; j++)
    3065             :     {
    3066     3549352 :       GEN c = gel(Ai,j);
    3067     3549352 :       if (gexpo(c) >= -2)
    3068             :       {
    3069     3375473 :         if (gequal0(c)) *precpb = 1; else non0 = 1;
    3070             :       }
    3071             :     }
    3072      879668 :     if (non0) gel(B, k++) = Ai;
    3073             :   }
    3074        8315 :   setlg(B, k); return B;
    3075             : }
    3076             : 
    3077             : static long
    3078      847870 : compute_multiple_of_R_pivot(GEN X, GEN x0/*unused*/, long ix, GEN c)
    3079             : {
    3080      847870 :   GEN x = gel(X,ix);
    3081      847870 :   long i, k = 0, ex = - (long)HIGHEXPOBIT, lx = lg(x);
    3082             :   (void)x0;
    3083     4279652 :   for (i=1; i<lx; i++)
    3084     3431782 :     if (!c[i] && !gequal0(gel(x,i)))
    3085             :     {
    3086      891223 :       long e = gexpo(gel(x,i));
    3087      891223 :       if (e > ex) { ex = e; k = i; }
    3088             :     }
    3089      847870 :   return (k && ex > -32)? k: lx;
    3090             : }
    3091             : 
    3092             : /* A = complex logarithmic embeddings of units (u_j) found so far,
    3093             :  * RU = R1+R2 = unit rank, N = field degree
    3094             :  * need = unit rank defect
    3095             :  * L = NULL (prec problem) or B^(-1) * A with approximate rational entries
    3096             :  * (as t_REAL), B a submatrix of A, with (probably) maximal rank RU */
    3097             : static GEN
    3098        8756 : compute_multiple_of_R(GEN A, long RU, long N, long *pneed, GEN *ptL)
    3099             : {
    3100             :   GEN T, d, mdet, Im_mdet, kR, xreal, L;
    3101        8756 :   long i, j, r, R1 = 2*RU - N;
    3102             :   int precpb;
    3103        8756 :   pari_sp av = avma;
    3104             : 
    3105        8756 :   if (RU == 1) { *ptL = zeromat(0, lg(A)-1); return gen_1; }
    3106             : 
    3107        8315 :   if (DEBUGLEVEL) err_printf("\n#### Computing regulator multiple\n");
    3108        8315 :   xreal = real_i(A); /* = (log |sigma_i(u_j)|) */
    3109        8315 :   mdet = clean_cols(xreal, &precpb);
    3110             :   /* will cause precision to increase on later failure, but we may succeed! */
    3111        8315 :   *ptL = precpb? NULL: gen_1;
    3112        8315 :   T = cgetg(RU+1,t_COL);
    3113        8315 :   for (i=1; i<=R1; i++) gel(T,i) = gen_1;
    3114        8315 :   for (   ; i<=RU; i++) gel(T,i) = gen_2;
    3115        8315 :   mdet = shallowconcat(T, mdet); /* det(Span(mdet)) = N * R */
    3116             : 
    3117             :   /* could be using indexrank(), but need custom "get_pivot" function */
    3118        8315 :   d = RgM_pivots(mdet, NULL, &r, &compute_multiple_of_R_pivot);
    3119             :   /* # of independent columns == unit rank ? */
    3120        8315 :   if (lg(mdet)-1 - r != RU)
    3121             :   {
    3122        5049 :     if (DEBUGLEVEL)
    3123           0 :       err_printf("Unit group rank = %ld < %ld\n",lg(mdet)-1 - r, RU);
    3124        5049 :     *pneed = RU - (lg(mdet)-1-r);
    3125        5049 :     avma = av; return NULL;
    3126             :   }
    3127             : 
    3128        3266 :   Im_mdet = cgetg(RU+1, t_MAT); /* extract independent columns */
    3129             :   /* N.B: d[1] = 1, corresponding to T above */
    3130        3266 :   gel(Im_mdet, 1) = T;
    3131       45461 :   for (i = j = 2; i <= RU; j++)
    3132       42195 :     if (d[j]) gel(Im_mdet, i++) = gel(mdet,j);
    3133             : 
    3134             :   /* integral multiple of R: the cols we picked form a Q-basis, they have an
    3135             :    * index in the full lattice. First column is T */
    3136        3266 :   kR = divru(det2(Im_mdet), N);
    3137             :   /* R > 0.2 uniformly */
    3138        3266 :   if (!signe(kR) || expo(kR) < -3) { avma=av; *pneed = 0; return NULL; }
    3139             : 
    3140        3266 :   setabssign(kR);
    3141        3266 :   L = RgM_inv(Im_mdet);
    3142        3266 :   if (!L) { *ptL = NULL; return kR; }
    3143             : 
    3144        3266 :   L = rowslice(L, 2, RU); /* remove first line */
    3145        3266 :   L = RgM_mul(L, xreal); /* approximate rational entries */
    3146        3266 :   gerepileall(av,2, &L, &kR);
    3147        3266 :   *ptL = L; return kR;
    3148             : }
    3149             : 
    3150             : static GEN
    3151        3707 : bestappr_noer(GEN x, GEN k)
    3152             : {
    3153             :   GEN y;
    3154        3707 :   pari_CATCH(e_PREC) { y = NULL; }
    3155        3707 :   pari_TRY { y = bestappr(x,k); } pari_ENDCATCH;
    3156        3707 :   return y;
    3157             : }
    3158             : 
    3159             : /* Input:
    3160             :  * lambda = approximate rational entries: coords of units found so far on a
    3161             :  * sublattice of maximal rank (sublambda)
    3162             :  * *ptkR = regulator of sublambda = multiple of regulator of lambda
    3163             :  * Compute R = true regulator of lambda.
    3164             :  *
    3165             :  * If c := Rz ~ 1, by Dirichlet's formula, then lambda is the full group of
    3166             :  * units AND the full set of relations for the class group has been computed.
    3167             :  *
    3168             :  * In fact z is a very rough approximation and we only expect 0.75 < Rz < 1.3
    3169             :  *
    3170             :  * Output: *ptkR = R, *ptU = basis of fundamental units (in terms lambda) */
    3171             : static int
    3172        3707 : compute_R(GEN lambda, GEN z, GEN *ptL, GEN *ptkR, pari_timer *T)
    3173             : {
    3174        3707 :   pari_sp av = avma;
    3175             :   long r, ec;
    3176             :   GEN L, H, D, den, R, c;
    3177             : 
    3178        3707 :   if (DEBUGLEVEL) { err_printf("\n#### Computing check\n"); err_flush(); }
    3179        3707 :   D = gmul2n(mpmul(*ptkR,z), 1); /* bound for denom(lambda) */
    3180        3707 :   if (expo(D) < 0 && rtodbl(D) < 0.95) return fupb_PRECI;
    3181        3707 :   lambda = bestappr_noer(lambda,D);
    3182        3707 :   if (!lambda)
    3183             :   {
    3184           0 :     if (DEBUGLEVEL) err_printf("truncation error in bestappr\n");
    3185           0 :     return fupb_PRECI;
    3186             :   }
    3187        3707 :   den = Q_denom(lambda);
    3188        3707 :   if (mpcmp(den,D) > 0)
    3189             :   {
    3190          12 :     if (DEBUGLEVEL) err_printf("D = %Ps\nden = %Ps\n",D,
    3191           0 :                     lgefint(den) <= DEFAULTPREC? den: itor(den,LOWDEFAULTPREC));
    3192          12 :     return fupb_PRECI;
    3193             :   }
    3194        3695 :   L = Q_muli_to_int(lambda, den);
    3195        3695 :   H = ZM_hnf(L);
    3196        3695 :   r = lg(H)-1;
    3197        3695 :   if (r && r != nbrows(H))
    3198           1 :     R = gen_0; /* wrong rank */
    3199             :   else
    3200        3694 :     R = gmul(*ptkR, gdiv(ZM_det_triangular(H), powiu(den, r)));
    3201             :   /* R = tentative regulator; regulator > 0.2 uniformly */
    3202        3695 :   if (gexpo(R) < -3) {
    3203           1 :     if (DEBUGLEVEL)
    3204             :     {
    3205           0 :       err_printf("\n#### Tentative regulator: %.28Pg\n", R);
    3206           0 :       timer_printf(T, "computing check");
    3207             :     }
    3208           1 :     avma = av; return fupb_PRECI;
    3209             :   }
    3210        3694 :   c = gmul(R,z); /* should be n (= 1 if we are done) */
    3211        3694 :   if (DEBUGLEVEL)
    3212             :   {
    3213           0 :     err_printf("\n#### Tentative regulator: %.28Pg\n", R);
    3214           0 :     err_printf("\n ***** check = %.28Pg\n",c);
    3215           0 :     timer_printf(T, "computing check");
    3216             :   }
    3217        3694 :   ec = gexpo(c);
    3218             :   /* safe check for c < 0.75 : avoid underflow in gtodouble() */
    3219        3694 :   if (ec < -1 || (ec == -1 && gtodouble(c) < 0.75)) {
    3220           0 :     avma = av; return fupb_PRECI;
    3221             :   }
    3222             :   /* safe check for c > 1.3 : avoid overflow */
    3223        3694 :   if (ec > 0 || (ec == 0 && gtodouble(c) > 1.3)) {
    3224        1695 :     avma = av; return fupb_RELAT;
    3225             :   }
    3226        1999 :   *ptkR = R; *ptL = L; return fupb_NONE;
    3227             : }
    3228             : 
    3229             : /* norm of an extended ideal I, whose 1st component is in integral HNF */
    3230             : static GEN
    3231        5343 : idnorm(GEN I) { return ZM_det_triangular(gel(I,1)); }
    3232             : 
    3233             : /* find the smallest (wrt norm) among I, I^-1 and red(I^-1) */
    3234             : static GEN
    3235        1781 : inverse_if_smaller(GEN nf, GEN I)
    3236             : {
    3237             :   GEN d, dmin, I1;
    3238             : 
    3239        1781 :   dmin = idnorm(I);
    3240        1781 :   I1 = idealinv(nf,I); gel(I1,1) = Q_remove_denom(gel(I1,1), NULL);
    3241        1781 :   d = idnorm(I1); if (cmpii(d,dmin) < 0) {I=I1; dmin=d;}
    3242             :   /* try reducing (often _increases_ the norm) */
    3243        1781 :   I1 = idealred(nf,I1);
    3244        1781 :   d = idnorm(I1); if (cmpii(d,dmin) < 0) I=I1;
    3245        1781 :   return I;
    3246             : }
    3247             : 
    3248             : /* in place */
    3249             : static void
    3250         268 : neg_row(GEN U, long i)
    3251             : {
    3252         268 :   GEN c = U + lg(U)-1;
    3253         268 :   for (; c>U; c--) gcoeff(c,i,0) = negi(gcoeff(c,i,0));
    3254         268 : }
    3255             : 
    3256             : static void
    3257         189 : setlg_col(GEN U, long l)
    3258             : {
    3259         189 :   GEN c = U + lg(U)-1;
    3260         189 :   for (; c>U; c--) setlg(*c, l);
    3261         189 : }
    3262             : 
    3263             : /* compute class group (clg1) + data for isprincipal (clg2) */
    3264             : static void
    3265        1934 : class_group_gen(GEN nf,GEN W,GEN C,GEN Vbase,long prec, GEN nf0,
    3266             :                 GEN *ptclg1,GEN *ptclg2)
    3267             : {
    3268             :   GEN z, G, Ga, ga, GD, cyc, X, Y, D, U, V, Ur, Ui, Uir, I, J, arch;
    3269             :   long i, j, lo, lo0;
    3270             :   pari_timer T;
    3271             : 
    3272        1934 :   if (DEBUGLEVEL) timer_start(&T);
    3273        1934 :   D = ZM_snfall(W,&U,&V); /* UWV=D, D diagonal, G = g Ui (G=new gens, g=old) */
    3274        1934 :   Ui = ZM_inv(U,gen_1);
    3275        1934 :   lo0 = lo = lg(D);
    3276             :  /* we could set lo = lg(cyc) and truncate all matrices below
    3277             :   *   setlg_col(D && U && Y, lo) + setlg(D && V && X && Ui, lo)
    3278             :   * but it's not worth the complication:
    3279             :   * 1) gain is negligible (avoid computing z^0 if lo < lo0)
    3280             :   * 2) when computing ga, the products XU and VY use the original matrices */
    3281        1934 :   Ur  = ZM_hnfdivrem(U, D, &Y);
    3282        1934 :   Uir = ZM_hnfdivrem(Ui,W, &X);
    3283             :  /* [x] = logarithmic embedding of x (arch. component)
    3284             :   * NB: z = idealred(I) --> I = y z[1], with [y] = - z[2]
    3285             :   * P invertible diagonal matrix (\pm 1) which is only implicitly defined
    3286             :   * G = g Uir P + [Ga],  Uir = Ui + WX
    3287             :   * g = G P Ur  + [ga],  Ur  = U + DY */
    3288        1934 :   G = cgetg(lo,t_VEC);
    3289        1934 :   Ga= cgetg(lo,t_VEC);
    3290        1934 :   z = init_famat(NULL);
    3291        1934 :   if (!nf0) nf0 = nf;
    3292        3715 :   for (j=1; j<lo; j++)
    3293             :   {
    3294        1781 :     GEN v = gel(Uir,j);
    3295        1781 :     GEN p1 = gel(v,1);
    3296        1781 :     gel(z,1) = gel(Vbase,1); I = idealpowred(nf0,z,p1);
    3297        3731 :     for (i=2; i<lo0; i++)
    3298             :     {
    3299        1950 :       p1 = gel(v,i);
    3300        1950 :       if (signe(p1))
    3301             :       {
    3302         801 :         gel(z,1) = gel(Vbase,i);
    3303         801 :         I = idealHNF_mulred(nf0, I, idealpowred(nf0,z,p1));
    3304             :       }
    3305             :     }
    3306        1781 :     J = inverse_if_smaller(nf0, I);
    3307        1781 :     if (J != I)
    3308             :     { /* update wrt P */
    3309         134 :       neg_row(Y ,j); gel(V,j) = ZC_neg(gel(V,j));
    3310         134 :       neg_row(Ur,j); gel(X,j) = ZC_neg(gel(X,j));
    3311             :     }
    3312        1781 :     gel(G,j) = gel(J,1); /* generator, order cyc[j] */
    3313        1781 :     arch = famat_to_arch(nf, gel(J,2), prec);
    3314        1781 :     if (!arch) pari_err_PREC("class_group_gen");
    3315        1781 :     gel(Ga,j) = gneg(arch);
    3316             :   }
    3317             :   /* at this point Y = PY, Ur = PUr, V = VP, X = XP */
    3318             : 
    3319             :   /* G D =: [GD] = g (UiP + W XP) D + [Ga]D = g W (VP + XP D) + [Ga]D
    3320             :    * NB: DP = PD and Ui D = W V. gW is given by (first lo0-1 cols of) C
    3321             :    */
    3322        1934 :   GD = gadd(act_arch(ZM_add(V, ZM_mul(X,D)), C), act_arch(D, Ga));
    3323             :   /* -[ga] = [GD]PY + G PU - g = [GD]PY + [Ga] PU + gW XP PU
    3324             :                                = gW (XP PUr + VP PY) + [Ga]PUr */
    3325        1934 :   ga = gadd(act_arch(ZM_add(ZM_mul(X,Ur), ZM_mul(V,Y)), C),
    3326             :             act_arch(Ur, Ga));
    3327        1934 :   ga = gneg(ga);
    3328             :   /* TODO: could (LLL)reduce ga and GD mod units ? */
    3329             : 
    3330        1934 :   cyc = cgetg(lo,t_VEC); /* elementary divisors */
    3331        3512 :   for (j=1; j<lo; j++)
    3332             :   {
    3333        1767 :     gel(cyc,j) = gcoeff(D,j,j);
    3334        1767 :     if (gequal1(gel(cyc,j)))
    3335             :     { /* strip useless components */
    3336         189 :       lo = j; setlg(cyc,lo); setlg_col(Ur,lo);
    3337         189 :       setlg(G,lo); setlg(Ga,lo); setlg(GD,lo); break;
    3338             :     }
    3339             :   }
    3340        1934 :   *ptclg1 = mkvec3(ZM_det_triangular(W), cyc, G);
    3341        1934 :   *ptclg2 = mkvec3(Ur, ga, GD);
    3342        1934 :   if (DEBUGLEVEL) timer_printf(&T, "classgroup generators");
    3343        1934 : }
    3344             : 
    3345             : /* SMALLBUCHINIT */
    3346             : 
    3347             : static GEN
    3348          49 : decodeprime(GEN T, GEN L, long n)
    3349             : {
    3350          49 :   long t = itos(T);
    3351          49 :   return gmael(L, t/n, t%n + 1);
    3352             : }
    3353             : static GEN
    3354          49 : codeprime(GEN L, long N, GEN pr)
    3355             : {
    3356          49 :   long p = pr_get_smallp(pr);
    3357          49 :   return utoipos( N*p + pr_index(gel(L,p), pr)-1 );
    3358             : }
    3359             : 
    3360             : static GEN
    3361           7 : decode_pr_lists(GEN nf, GEN pfc)
    3362             : {
    3363           7 :   long i, n = nf_get_degree(nf), l = lg(pfc);
    3364           7 :   GEN L, P = cgetg(l, t_VECSMALL), Vbase = cgetg(l, t_COL);
    3365             : 
    3366           7 :   for (i = 1; i < l; i++) P[i] = itou(gel(pfc,i)) / n;
    3367           7 :   L = const_vec(vecsmall_max(P), NULL);
    3368          56 :   for (i = 1; i < l; i++)
    3369             :   {
    3370          49 :     long p = P[i];
    3371          49 :     if (!gel(L,p)) gel(L,p) = idealprimedec(nf, utoipos(p));
    3372             :   }
    3373           7 :   for (i = 1; i < l; i++) gel(Vbase,i) = decodeprime(gel(pfc,i), L, n);
    3374           7 :   return Vbase;
    3375             : }
    3376             : 
    3377             : static GEN
    3378           7 : codeprimes(GEN Vbase, long N)
    3379             : {
    3380           7 :   GEN v, L = get_pr_lists(Vbase, N, 1);
    3381           7 :   long i, l = lg(Vbase);
    3382           7 :   v = cgetg(l, t_VEC);
    3383           7 :   for (i=1; i<l; i++) gel(v,i) = codeprime(L, N, gel(Vbase,i));
    3384           7 :   return v;
    3385             : }
    3386             : 
    3387             : /* compute principal ideals corresponding to (gen[i]^cyc[i]) */
    3388             : static GEN
    3389         917 : makecycgen(GEN bnf)
    3390             : {
    3391             :   GEN cyc,gen,h,nf,y,GD;
    3392             :   long e,i,l;
    3393             : 
    3394         917 :   if (DEBUGLEVEL) pari_warn(warner,"completing bnf (building cycgen)");
    3395         917 :   nf = bnf_get_nf(bnf);
    3396         917 :   cyc = bnf_get_cyc(bnf);
    3397         917 :   gen = bnf_get_gen(bnf); GD = gmael(bnf,9,3);
    3398         917 :   h = cgetg_copy(gen, &l);
    3399        1890 :   for (i=1; i<l; i++)
    3400             :   {
    3401         973 :     GEN gi = gel(gen,i), ci = gel(cyc,i);
    3402         973 :     if (abscmpiu(ci, 5) < 0)
    3403             :     {
    3404         672 :       GEN N = ZM_det_triangular(gi);
    3405         672 :       y = isprincipalarch(bnf,gel(GD,i), N, ci, gen_1, &e);
    3406         672 :       if (y && fact_ok(nf,y,NULL,mkvec(gi),mkvec(ci)))
    3407             :       {
    3408         672 :         gel(h,i) = to_famat_shallow(y,gen_1);
    3409         672 :         continue;
    3410             :       }
    3411             :     }
    3412         301 :     y = isprincipalfact(bnf, NULL, mkvec(gi), mkvec(ci), nf_GENMAT|nf_FORCE);
    3413         301 :     h[i] = y[2];
    3414             :   }
    3415         917 :   return h;
    3416             : }
    3417             : 
    3418             : static GEN
    3419         790 : get_y(GEN bnf, GEN W, GEN B, GEN C, GEN pFB, long j)
    3420             : {
    3421         790 :   GEN y, nf  = bnf_get_nf(bnf);
    3422         790 :   long e, lW = lg(W)-1;
    3423         790 :   GEN ex = (j<=lW)? gel(W,j): gel(B,j-lW);
    3424         790 :   GEN P = (j<=lW)? NULL: gel(pFB,j);
    3425         790 :   if (C)
    3426             :   { /* archimedean embeddings known: cheap trial */
    3427         775 :     GEN Nx = get_norm_fact_primes(pFB, ex, P);
    3428         775 :     y = isprincipalarch(bnf,gel(C,j), Nx,gen_1, gen_1, &e);
    3429         775 :     if (y && fact_ok(nf,y,P,pFB,ex)) return y;
    3430             :   }
    3431          30 :   y = isprincipalfact_or_fail(bnf, P, pFB, ex);
    3432          30 :   return typ(y) == t_INT? y: gel(y,2);
    3433             : }
    3434             : /* compute principal ideals corresponding to bnf relations */
    3435             : static GEN
    3436          28 : makematal(GEN bnf)
    3437             : {
    3438          28 :   GEN W = bnf_get_W(bnf), B = bnf_get_B(bnf), C = bnf_get_C(bnf);
    3439             :   GEN pFB, ma, retry;
    3440          28 :   long lma, j, prec = 0;
    3441             : 
    3442          28 :   if (DEBUGLEVEL) pari_warn(warner,"completing bnf (building matal)");
    3443          28 :   lma=lg(W)+lg(B)-1;
    3444          28 :   pFB = bnf_get_vbase(bnf);
    3445          28 :   ma = cgetg(lma,t_VEC);
    3446          28 :   retry = vecsmalltrunc_init(lma);
    3447         803 :   for (j=lma-1; j>0; j--)
    3448             :   {
    3449         775 :     pari_sp av = avma;
    3450         775 :     GEN y = get_y(bnf, W, B, C, pFB, j);
    3451         775 :     if (typ(y) == t_INT)
    3452             :     {
    3453          15 :       long E = itos(y);
    3454          15 :       if (DEBUGLEVEL>1) err_printf("\n%ld done later at prec %ld\n",j,E);
    3455          15 :       avma = av;
    3456          15 :       vecsmalltrunc_append(retry, j);
    3457          15 :       if (E > prec) prec = E;
    3458             :     }
    3459             :     else
    3460             :     {
    3461         760 :       if (DEBUGLEVEL>1) err_printf("%ld ",j);
    3462         760 :       gel(ma,j) = gerepileupto(av,y);
    3463             :     }
    3464             :   }
    3465          28 :   if (prec)
    3466             :   {
    3467           7 :     long k, l = lg(retry);
    3468           7 :     GEN y, nf = bnf_get_nf(bnf);
    3469           7 :     if (DEBUGLEVEL) pari_warn(warnprec,"makematal",prec);
    3470           7 :     nf = nfnewprec_shallow(nf,prec);
    3471           7 :     bnf = Buchall(nf, nf_FORCE, prec);
    3472           7 :     if (DEBUGLEVEL) err_printf("makematal, adding missing entries:");
    3473          22 :     for (k=1; k<l; k++)
    3474             :     {
    3475          15 :       pari_sp av = avma;
    3476          15 :       long j = retry[k];
    3477          15 :       y = get_y(bnf,W,B,NULL, pFB, j);
    3478          15 :       if (typ(y) == t_INT) pari_err_PREC("makematal");
    3479          15 :       if (DEBUGLEVEL>1) err_printf("%ld ",j);
    3480          15 :       gel(ma,j) = gerepileupto(av,y);
    3481             :     }
    3482             :   }
    3483          28 :   if (DEBUGLEVEL>1) err_printf("\n");
    3484          28 :   return ma;
    3485             : }
    3486             : 
    3487             : enum { MATAL = 1, CYCGEN, UNITS };
    3488             : 
    3489             : GEN
    3490        3129 : bnf_build_cycgen(GEN bnf)
    3491        3129 : { return obj_checkbuild(bnf, CYCGEN, &makecycgen); }
    3492             : GEN
    3493          37 : bnf_build_matalpha(GEN bnf)
    3494          37 : { return obj_checkbuild(bnf, MATAL, &makematal); }
    3495             : GEN
    3496       16074 : bnf_build_units(GEN bnf)
    3497       16074 : { return obj_checkbuild(bnf, UNITS, &makeunits); }
    3498             : 
    3499             : static GEN
    3500          37 : get_regulator(GEN mun)
    3501             : {
    3502          37 :   pari_sp av = avma;
    3503             :   GEN R;
    3504             : 
    3505          37 :   if (lg(mun) == 1) return gen_1;
    3506          37 :   R = det( rowslice(real_i(mun), 1, lgcols(mun)-2) );
    3507          37 :   setabssign(R); return gerepileuptoleaf(av, R);
    3508             : }
    3509             : 
    3510             : /* return corrected archimedian components for elts of x (vector)
    3511             :  * (= log(sigma_i(x)) - log(|Nx|) / [K:Q]) */
    3512             : static GEN
    3513         106 : get_archclean(GEN nf, GEN x, long prec, int units)
    3514             : {
    3515         106 :   long k,N, la = lg(x);
    3516         106 :   GEN M = cgetg(la,t_MAT);
    3517             : 
    3518         106 :   if (la == 1) return M;
    3519         106 :   N = nf_get_degree(nf);
    3520        1745 :   for (k=1; k<la; k++)
    3521             :   {
    3522        1667 :     pari_sp av = avma;
    3523        1667 :     GEN c = get_arch(nf, gel(x,k), prec);
    3524        1667 :     if (!c) return NULL;
    3525        1639 :     if (!units) {
    3526        1552 :       c = cleanarch(c, N, prec);
    3527        1552 :       if (!c) return NULL;
    3528             :     }
    3529        1639 :     settyp(c,t_COL);
    3530        1639 :     gel(M,k) = gerepilecopy(av, c);
    3531             :   }
    3532          78 :   return M;
    3533             : }
    3534             : 
    3535             : static void
    3536          30 : my_class_group_gen(GEN bnf, long prec, GEN nf0, GEN *ptcl, GEN *ptcl2)
    3537             : {
    3538          30 :   GEN W = bnf_get_W(bnf), C = bnf_get_C(bnf), nf = bnf_get_nf(bnf);
    3539          30 :   class_group_gen(nf,W,C,bnf_get_vbase(bnf),prec,nf0, ptcl,ptcl2);
    3540          30 : }
    3541             : 
    3542             : GEN
    3543          30 : bnfnewprec_shallow(GEN bnf, long prec)
    3544             : {
    3545          30 :   GEN nf0 = bnf_get_nf(bnf), nf, res, fu, mun, gac, matal, clgp, clgp2, y;
    3546             :   long r1, r2, prec1;
    3547             : 
    3548          30 :   nf_get_sign(nf0, &r1, &r2);
    3549          30 :   fu = bnf_build_units(bnf);
    3550          30 :   fu = vecslice(fu, 2, lg(fu)-1);
    3551             : 
    3552          30 :   prec1 = prec;
    3553          30 :   if (r1 + r2 > 1) {
    3554          30 :     long e = gexpo(bnf_get_logfu(bnf)) + 1 - TWOPOTBITS_IN_LONG;
    3555          30 :     if (e >= 0) prec += nbits2extraprec(e);
    3556             :   }
    3557          30 :   if (DEBUGLEVEL && prec1!=prec) pari_warn(warnprec,"bnfnewprec",prec);
    3558          30 :   matal = bnf_build_matalpha(bnf);
    3559             :   for(;;)
    3560             :   {
    3561          58 :     pari_sp av = avma;
    3562          58 :     nf = nfnewprec_shallow(nf0,prec);
    3563          58 :     mun = get_archclean(nf, fu, prec, 1);
    3564          58 :     if (mun)
    3565             :     {
    3566          34 :       gac = get_archclean(nf, matal, prec, 0);
    3567          34 :       if (gac) break;
    3568             :     }
    3569          28 :     avma = av; prec = precdbl(prec);
    3570          28 :     if (DEBUGLEVEL) pari_warn(warnprec,"bnfnewprec(extra)",prec);
    3571          28 :   }
    3572          30 :   y = leafcopy(bnf);
    3573          30 :   gel(y,3) = mun;
    3574          30 :   gel(y,4) = gac;
    3575          30 :   gel(y,7) = nf;
    3576          30 :   my_class_group_gen(y,prec,nf0, &clgp,&clgp2);
    3577          30 :   res = leafcopy(gel(bnf,8));
    3578          30 :   gel(res,1) = clgp;
    3579          30 :   gel(res,2) = get_regulator(mun);
    3580          30 :   gel(y,8) = res;
    3581          30 :   gel(y,9) = clgp2; return y;
    3582             : }
    3583             : GEN
    3584          14 : bnfnewprec(GEN bnf, long prec)
    3585             : {
    3586          14 :   pari_sp av = avma;
    3587          14 :   return gerepilecopy(av, bnfnewprec_shallow(checkbnf(bnf), prec));
    3588             : }
    3589             : 
    3590             : GEN
    3591           0 : bnrnewprec_shallow(GEN bnr, long prec)
    3592             : {
    3593           0 :   GEN y = cgetg(7,t_VEC);
    3594             :   long i;
    3595           0 :   gel(y,1) = bnfnewprec_shallow(bnr_get_bnf(bnr), prec);
    3596           0 :   for (i=2; i<7; i++) gel(y,i) = gel(bnr,i);
    3597           0 :   return y;
    3598             : }
    3599             : GEN
    3600           7 : bnrnewprec(GEN bnr, long prec)
    3601             : {
    3602           7 :   GEN y = cgetg(7,t_VEC);
    3603             :   long i;
    3604           7 :   checkbnr(bnr);
    3605           7 :   gel(y,1) = bnfnewprec(bnr_get_bnf(bnr), prec);
    3606           7 :   for (i=2; i<7; i++) gel(y,i) = gcopy(gel(bnr,i));
    3607           7 :   return y;
    3608             : }
    3609             : 
    3610             : static GEN
    3611        2366 : get_clfu(GEN clgp, GEN reg, GEN zu, GEN fu)
    3612             : {
    3613        2366 :   if (!fu) fu = cgetg(1,t_MAT);
    3614        2366 :   return mkvec5(clgp, reg, gen_1/*DUMMY*/, zu, fu);
    3615             : }
    3616             : 
    3617             : static GEN
    3618        2366 : buchall_end(GEN nf,GEN res, GEN clg2, GEN W, GEN B, GEN A, GEN C,GEN Vbase)
    3619             : {
    3620        2366 :   GEN z = obj_init(9, 3);
    3621        2366 :   gel(z,1) = W;
    3622        2366 :   gel(z,2) = B;
    3623        2366 :   gel(z,3) = A;
    3624        2366 :   gel(z,4) = C;
    3625        2366 :   gel(z,5) = Vbase;
    3626        2366 :   gel(z,6) = gen_0;
    3627        2366 :   gel(z,7) = nf;
    3628        2366 :   gel(z,8) = res;
    3629        2366 :   gel(z,9) = clg2;
    3630        2366 :   return z;
    3631             : }
    3632             : 
    3633             : /* FIXME: obsolete function */
    3634             : GEN
    3635           7 : bnfcompress(GEN bnf)
    3636             : {
    3637           7 :   pari_sp av = avma;
    3638           7 :   GEN nf, fu, y = cgetg(13,t_VEC);
    3639             : 
    3640           7 :   bnf = checkbnf(bnf);
    3641           7 :   nf = bnf_get_nf(bnf);
    3642           7 :   gel(y,1) = nf_get_pol(nf);
    3643           7 :   gel(y,2) = gmael(nf,2,1);
    3644           7 :   gel(y,3) = nf_get_disc(nf);
    3645           7 :   gel(y,4) = nf_get_zk(nf);
    3646           7 :   gel(y,5) = nf_get_roots(nf);
    3647           7 :   gel(y,6) = gen_0; /* FIXME: unused */
    3648           7 :   gel(y,7) = bnf_get_W(bnf);
    3649           7 :   gel(y,8) = bnf_get_B(bnf);
    3650           7 :   gel(y,9) = codeprimes(bnf_get_vbase(bnf), nf_get_degree(nf));
    3651           7 :   gel(y,10) = mkvec2(utoipos(bnf_get_tuN(bnf)),
    3652             :                      nf_to_scalar_or_basis(nf, bnf_get_tuU(bnf)));
    3653           7 :   fu = bnf_build_units(bnf); fu = vecslice(fu,2,lg(fu)-1);
    3654           7 :   gel(y,11) = fu;
    3655           7 :   gel(y,12) = bnf_build_matalpha(bnf);
    3656           7 :   return gerepilecopy(av, y);
    3657             : }
    3658             : 
    3659             : /* FIXME: obsolete feature */
    3660             : static GEN
    3661           7 : sbnf2bnf(GEN sbnf, long prec)
    3662             : {
    3663           7 :   pari_sp av = avma;
    3664             :   GEN ro, nf, A, fu, FU, C, clgp, clgp2, res, y, W, zu, matal, Vbase;
    3665             :   long k, l;
    3666             :   nfmaxord_t S;
    3667             : 
    3668           7 :   if (typ(sbnf) != t_VEC || lg(sbnf) != 13) pari_err_TYPE("bnfmake",sbnf);
    3669           7 :   if (prec < DEFAULTPREC) prec = DEFAULTPREC;
    3670             : 
    3671           7 :   S.T0 = S.T = gel(sbnf,1);
    3672           7 :   S.r1    = itos(gel(sbnf,2));
    3673           7 :   S.dK    = gel(sbnf,3);
    3674           7 :   S.basis = gel(sbnf,4);
    3675           7 :   S.index = NULL;
    3676           7 :   S.dT    = NULL;
    3677           7 :   S.dKP   = NULL;
    3678           7 :   S.basden= NULL;
    3679           7 :   ro = gel(sbnf,5); if (prec > gprecision(ro)) ro = NULL;
    3680           7 :   nf = nfmaxord_to_nf(&S, ro, prec);
    3681             : 
    3682           7 :   fu = gel(sbnf,11);
    3683           7 :   A = get_archclean(nf, fu, prec, 1);
    3684           7 :   if (!A) pari_err_PREC("bnfmake");
    3685             : 
    3686           7 :   prec = nf_get_prec(nf);
    3687           7 :   matal = gel(sbnf,12);
    3688           7 :   C = get_archclean(nf,matal,prec,0);
    3689           7 :   if (!C) pari_err_PREC("bnfmake");
    3690             : 
    3691           7 :   Vbase = decode_pr_lists(nf, gel(sbnf,9));
    3692           7 :   W = gel(sbnf,7);
    3693           7 :   class_group_gen(nf,W,C,Vbase,prec,NULL, &clgp,&clgp2);
    3694             : 
    3695           7 :   zu = gel(sbnf,10);
    3696           7 :   zu = mkvec2(gel(zu,1), nf_to_scalar_or_alg(nf, gel(zu,2)));
    3697           7 :   FU = cgetg_copy(fu, &l);
    3698           7 :   for (k=1; k < l; k++) gel(FU,k) = coltoliftalg(nf, gel(fu,k));
    3699             : 
    3700           7 :   res = get_clfu(clgp, get_regulator(A), zu, FU);
    3701           7 :   y = buchall_end(nf,res,clgp2,W,gel(sbnf,8),A,C,Vbase);
    3702           7 :   return gerepilecopy(av,y);
    3703             : }
    3704             : 
    3705             : GEN
    3706        1127 : bnfinit0(GEN P, long flag, GEN data, long prec)
    3707             : {
    3708        1127 :   double c1 = BNF_C1, c2 = BNF_C2;
    3709        1127 :   long fl, relpid = BNF_RELPID;
    3710             : 
    3711        1127 :   if (typ(P) == t_VEC && lg(P) == 13) return sbnf2bnf(P, prec); /* sbnf */
    3712        1120 :   if (data)
    3713             :   {
    3714          21 :     long lx = lg(data);
    3715          21 :     if (typ(data) != t_VEC || lx > 5) pari_err_TYPE("bnfinit",data);
    3716          21 :     switch(lx)
    3717             :     {
    3718           0 :       case 4: relpid = itos(gel(data,3));
    3719          14 :       case 3: c2 = gtodouble(gel(data,2));
    3720          14 :       case 2: c1 = gtodouble(gel(data,1));
    3721             :     }
    3722             :   }
    3723        1120 :   switch(flag)
    3724             :   {
    3725             :     case 2:
    3726         896 :     case 0: fl = 0; break;
    3727         224 :     case 1: fl = nf_FORCE; break;
    3728           0 :     default: pari_err_FLAG("bnfinit");
    3729             :       return NULL; /* LCOV_EXCL_LINE */
    3730             :   }
    3731        1120 :   return Buchall_param(P, c1, c2, relpid, fl, prec);
    3732             : }
    3733             : GEN
    3734        1239 : Buchall(GEN P, long flag, long prec)
    3735        1239 : { return Buchall_param(P, BNF_C1, BNF_C2, BNF_RELPID, flag, prec); }
    3736             : 
    3737             : static GEN
    3738         462 : Buchall_deg1(GEN nf)
    3739             : {
    3740         462 :   GEN v = cgetg(1,t_VEC), m = cgetg(1,t_MAT);
    3741             :   GEN W, A, B, C, Vbase, res;
    3742         462 :   GEN fu = v, R = gen_1, zu = mkvec2(gen_2, gen_m1);
    3743         462 :   GEN clg1 = mkvec3(gen_1,v,v), clg2 = mkvec3(m,v,v);
    3744             : 
    3745         462 :   W = A = B = C = m;
    3746         462 :   Vbase = cgetg(1,t_COL);
    3747         462 :   res = get_clfu(clg1, R, zu, fu);
    3748         462 :   return buchall_end(nf,res,clg2,W,B,A,C,Vbase);
    3749             : }
    3750             : 
    3751             : /* return (small set of) indices of columns generating the same lattice as x.
    3752             :  * Assume HNF(x) is inexpensive (few rows, many columns).
    3753             :  * Dichotomy approach since interesting columns may be at the very end */
    3754             : GEN
    3755        1999 : extract_full_lattice(GEN x)
    3756             : {
    3757        1999 :   long dj, j, k, l = lg(x);
    3758             :   GEN h, h2, H, v;
    3759             : 
    3760        1999 :   if (l < 200) return NULL; /* not worth it */
    3761             : 
    3762           7 :   v = vecsmalltrunc_init(l);
    3763           7 :   H = ZM_hnf(x);
    3764           7 :   h = cgetg(1, t_MAT);
    3765           7 :   dj = 1;
    3766         378 :   for (j = 1; j < l; )
    3767             :   {
    3768         371 :     pari_sp av = avma;
    3769         371 :     long lv = lg(v);
    3770             : 
    3771         371 :     for (k = 0; k < dj; k++) v[lv+k] = j+k;
    3772         371 :     setlg(v, lv + dj);
    3773         371 :     h2 = ZM_hnf(vecpermute(x, v));
    3774         371 :     if (ZM_equal(h, h2))
    3775             :     { /* these dj columns can be eliminated */
    3776         140 :       avma = av; setlg(v, lv);
    3777         140 :       j += dj;
    3778         140 :       if (j >= l) break;
    3779         140 :       dj <<= 1;
    3780         140 :       if (j + dj >= l) { dj = (l - j) >> 1; if (!dj) dj = 1; }
    3781             :     }
    3782         231 :     else if (dj > 1)
    3783             :     { /* at least one interesting column, try with first half of this set */
    3784         140 :       avma = av; setlg(v, lv);
    3785         140 :       dj >>= 1; /* > 0 */
    3786             :     }
    3787             :     else
    3788             :     { /* this column should be kept */
    3789          91 :       if (ZM_equal(h2, H)) break;
    3790          84 :       h = h2; j++;
    3791             :     }
    3792             :   }
    3793           7 :   return v;
    3794             : }
    3795             : 
    3796             : static void
    3797        2044 : init_rel(RELCACHE_t *cache, FB_t *F, long add_need)
    3798             : {
    3799        2044 :   const long n = F->KC + add_need; /* expected # of needed relations */
    3800             :   long i, j, k, p;
    3801             :   GEN c, P;
    3802             :   GEN R;
    3803             : 
    3804        2044 :   if (DEBUGLEVEL) err_printf("KCZ = %ld, KC = %ld, n = %ld\n", F->KCZ,F->KC,n);
    3805        2044 :   reallocate(cache, 10*n + 50); /* make room for lots of relations */
    3806        2044 :   cache->chk = cache->base;
    3807        2044 :   cache->end = cache->base + n;
    3808        2044 :   cache->relsup = add_need;
    3809        2044 :   cache->last = cache->base;
    3810        2044 :   cache->missing = lg(cache->basis) - 1;
    3811       16631 :   for (i = 1; i <= F->KCZ; i++)
    3812             :   { /* trivial relations (p) = prod P^e */
    3813       14587 :     p = F->FB[i]; P = F->LV[p];
    3814       14587 :     if (!isclone(P)) continue;
    3815             : 
    3816             :     /* all prime divisors in FB */
    3817       10085 :     c = zero_Flv(F->KC); k = F->iLP[p];
    3818       10085 :     R = c; c += k;
    3819       10085 :     for (j = lg(P)-1; j; j--) c[j] = pr_get_e(gel(P,j));
    3820       10085 :     add_rel(cache, F, R, k+1, /*m*/NULL, 0);
    3821             :   }
    3822        2044 : }
    3823             : 
    3824             : /* Let z = \zeta_n in nf. List of not-obviously-dependent generators for
    3825             :  * cyclotomic units modulo torsion in Q(z) [independent when n a prime power]:
    3826             :  * - z^a - 1,  n/(a,n) not a prime power, a \nmid n unless a=1,  1 <= a < n/2
    3827             :  * - (Z^a - 1)/(Z - 1),  p^k || n, Z = z^{n/p^k}, (p,a) = 1, 1 < a <= (p^k-1)/2
    3828             :  */
    3829             : GEN
    3830        2044 : nfcyclotomicunits(GEN nf, GEN zu)
    3831             : {
    3832        2044 :   long n = itos(gel(zu, 1)), n2, lP, i, a;
    3833             :   GEN z, fa, P, E, L, mz, powz;
    3834        2044 :   if (n <= 6) return cgetg(1, t_VEC);
    3835             : 
    3836         126 :   z = algtobasis(nf,gel(zu, 2));
    3837         126 :   if ((n & 3) == 2) { n = n >> 1; z = ZC_neg(z); } /* ensure n != 2 (mod 4) */
    3838         126 :   n2 = n/2;
    3839         126 :   mz = zk_multable(nf, z); /* multiplication by z */
    3840         126 :   powz = cgetg(n2, t_VEC); gel(powz,1) = z;
    3841         126 :   for (i = 2; i < n2; i++) gel(powz,i) = ZM_ZC_mul(mz, gel(powz,i-1));
    3842             :   /* powz[i] = z^i */
    3843             : 
    3844         126 :   L = vectrunc_init(n);
    3845         126 :   fa = factoru(n);
    3846         126 :   P = gel(fa,1); lP = lg(P);
    3847         126 :   E = gel(fa,2);
    3848         266 :   for (i = 1; i < lP; i++)
    3849             :   { /* second kind */
    3850         140 :     long p = P[i], k = E[i], pk = upowuu(p,k), pk2 = (pk-1) / 2;
    3851         140 :     GEN u = gen_1;
    3852         273 :     for (a = 2; a <= pk2; a++)
    3853             :     {
    3854         133 :       u = nfadd(nf, u, gel(powz, (n/pk) * (a-1))); /* = (Z^a-1)/(Z-1) */
    3855         133 :       if (a % p) vectrunc_append(L, u);
    3856             :     }
    3857             :   }
    3858         196 :   if (lP > 2) for (a = 1; a < n2; a++)
    3859             :   { /* first kind, when n not a prime power */
    3860             :     ulong p;
    3861          70 :     if (a > 1 && (n % a == 0 || uisprimepower(n/ugcd(a,n), &p))) continue;
    3862          28 :     vectrunc_append(L, nfadd(nf, gel(powz, a), gen_m1));
    3863             :   }
    3864         126 :   return L;
    3865             : }
    3866             : static void
    3867        2044 : add_cyclotomic_units(GEN nf, GEN zu, RELCACHE_t *cache, FB_t *F)
    3868             : {
    3869        2044 :   pari_sp av = avma;
    3870        2044 :   GEN L = nfcyclotomicunits(nf, zu);
    3871        2044 :   long i, l = lg(L);
    3872        2044 :   if (l > 1)
    3873             :   {
    3874         126 :     GEN R = zero_Flv(F->KC);
    3875         126 :     for(i = 1; i < l; i++) add_rel(cache, F, R, F->KC+1, gel(L,i), 0);
    3876             :   }
    3877        2044 :   avma = av;
    3878        2044 : }
    3879             : 
    3880             : static void
    3881       13661 : shift_embed(GEN G, GEN Gtw, long a, long r1)
    3882             : {
    3883       13661 :   long j, k, l = lg(G);
    3884       13661 :   if (a <= r1)
    3885        8286 :     for (j=1; j<l; j++) gcoeff(G,a,j) = gcoeff(Gtw,a,j);
    3886             :   else
    3887             :   {
    3888        5375 :     k = (a<<1) - r1;
    3889       50391 :     for (j=1; j<l; j++)
    3890             :     {
    3891       45016 :       gcoeff(G,k-1,j) = gcoeff(Gtw,k-1,j);
    3892       45016 :       gcoeff(G,k  ,j) = gcoeff(Gtw,k,  j);
    3893             :     }
    3894             :   }
    3895       13661 : }
    3896             : 
    3897             : /* G where embeddings a and b are multiplied by 2^10 */
    3898             : static GEN
    3899        8901 : shift_G(GEN G, GEN Gtw, long a, long b, long r1)
    3900             : {
    3901        8901 :   GEN g = RgM_shallowcopy(G);
    3902        8901 :   if (a != b) shift_embed(g,Gtw,a,r1);
    3903        8901 :   shift_embed(g,Gtw,b,r1); return g;
    3904             : }
    3905             : 
    3906             : static void
    3907        1897 : compute_vecG(GEN nf, FB_t *F, long n)
    3908             : {
    3909        1897 :   GEN G0, Gtw0, vecG, G = nf_get_G(nf);
    3910        1897 :   long e, i, j, ind, r1 = nf_get_r1(nf), r = lg(G)-1;
    3911        3794 :   if (n == 1) { F->G0 = G0 = ground(G); F->vecG = mkvec( G0 ); return; }
    3912        1519 :   for (e = 32;;)
    3913             :   {
    3914        1519 :     G = gmul2n(G, e);
    3915        1519 :     G0 = ground(G); if (ZM_rank(G0) == r) break; /* maximal rank ? */
    3916           0 :   }
    3917        1519 :   Gtw0 = ground(gmul2n(G, 10));
    3918        1519 :   vecG = cgetg(1 + n*(n+1)/2,t_VEC);
    3919        5660 :   for (ind=j=1; j<=n; j++)
    3920        4141 :     for (i=1; i<=j; i++) gel(vecG,ind++) = shift_G(G0,Gtw0,i,j,r1);
    3921        1519 :   F->G0 = G0; F->vecG = vecG;
    3922             : }
    3923             : 
    3924             : static GEN
    3925       18960 : trim_list(FB_t *F)
    3926             : {
    3927       18960 :   pari_sp av = avma;
    3928       18960 :   GEN L_jid = F->L_jid, present = zero_Flv(F->KC);
    3929       18960 :   long i, j, imax = minss(lg(L_jid), F->KC + 1);
    3930       18960 :   GEN minidx = F->minidx, idx = cgetg(imax, t_VECSMALL);
    3931             : 
    3932      755893 :   for (i = j = 1; i < imax; i++)
    3933             :   {
    3934      736933 :     long id = minidx[L_jid[i]];
    3935             : 
    3936      736933 :     if (!present[id])
    3937             :     {
    3938      454536 :       idx[j++] = L_jid[i];
    3939      454536 :       present[id] = 1;
    3940             :     }
    3941             :   }
    3942       18960 :   setlg(idx, j);
    3943       18960 :   return gerepileuptoleaf(av, idx);
    3944             : }
    3945             : 
    3946             : static void
    3947        1659 : try_elt(RELCACHE_t *cache, FB_t *F, GEN nf, GEN x, FACT *fact)
    3948             : {
    3949        1659 :   pari_sp av = avma;
    3950             :   GEN R, Nx;
    3951        1659 :   long nz, tx = typ(x);
    3952             : 
    3953        1660 :   if (tx == t_INT || tx == t_FRAC) return;
    3954        1659 :   if (tx != t_COL) x = algtobasis(nf, x);
    3955        1659 :   if (RgV_isscalar(x)) return;
    3956        1658 :   x = Q_primpart(x);
    3957        1658 :   Nx = nfnorm(nf, x);
    3958        1658 :   if (!can_factor(F, nf, NULL, x, Nx, fact)) return;
    3959             : 
    3960             :   /* smooth element */
    3961        1658 :   R = set_fact(F, fact, NULL, &nz);
    3962             :   /* make sure we get maximal rank first, then allow all relations */
    3963        1658 :   (void) add_rel(cache, F, R, nz, x, 0);
    3964        1658 :   avma = av;
    3965             : }
    3966             : 
    3967             : GEN
    3968        2359 : Buchall_param(GEN P, double cbach, double cbach2, long nbrelpid, long flun, long prec)
    3969             : {
    3970             :   pari_timer T;
    3971        2359 :   pari_sp av0 = avma, av, av2;
    3972             :   long PRECREG, N, R1, R2, RU, low, high, LIMC0, LIMC, LIMC2, LIMCMAX, zc, i;
    3973             :   long LIMres;
    3974             :   long MAXDEPSIZESFB, MAXDEPSFB;
    3975        2359 :   long nreldep, sfb_trials, need, old_need, precdouble = 0, precadd = 0;
    3976             :   long done_small, small_fail, fail_limit, squash_index, small_norm_prec;
    3977        2359 :   long flag_nfinit = 0;
    3978             :   double LOGD, LOGD2, lim;
    3979        2359 :   GEN computed = NULL, zu, nf, M_sn, D, A, W, R, h, PERM, fu = NULL /*-Wall*/;
    3980             :   GEN small_multiplier;
    3981             :   GEN res, L, invhr, B, C, C0, lambda, dep, clg1, clg2, Vbase;
    3982             :   GEN auts, cyclic;
    3983        2359 :   const char *precpb = NULL;
    3984        2359 :   int FIRST = 1, class1 = 0;
    3985             :   nfmaxord_t nfT;
    3986             :   RELCACHE_t cache;
    3987             :   FB_t F;
    3988             :   GRHcheck_t GRHcheck;
    3989             :   FACT *fact;
    3990             : 
    3991        2359 :   if (DEBUGLEVEL) timer_start(&T);
    3992        2359 :   P = get_nfpol(P, &nf);
    3993        2359 :   if (nf)
    3994             :   {
    3995         105 :     PRECREG = nf_get_prec(nf);
    3996         105 :     D = nf_get_disc(nf);
    3997             :   }
    3998             :   else
    3999             :   {
    4000        2254 :     PRECREG = maxss(prec, MEDDEFAULTPREC);
    4001        2254 :     nfinit_basic(&nfT, P);
    4002        2254 :     D = nfT.dK;
    4003        2254 :     if (!equali1(leading_coeff(nfT.T0)))
    4004             :     {
    4005          14 :       pari_warn(warner,"non-monic polynomial in bnfinit, using polredbest");
    4006          14 :       flag_nfinit = nf_RED;
    4007             :     }
    4008             :   }
    4009        2359 :   N = degpol(P);
    4010        2359 :   if (N <= 1)
    4011             :   {
    4012         462 :     if (!nf) nf = nfinit_complete(&nfT, flag_nfinit, PRECREG);
    4013         462 :     return gerepilecopy(av0, Buchall_deg1(nf));
    4014             :   }
    4015        1897 :   D = absi(D);
    4016        1897 :   LOGD = dbllog2(D) * LOG2;
    4017        1897 :   LOGD2 = LOGD*LOGD;
    4018        1897 :   LIMCMAX = (long)(12.*LOGD2);
    4019             :   /* In small_norm, LLL reduction produces v0 in I such that
    4020             :    *     T2(v0) <= (4/3)^((n-1)/2) NI^(2/n) disc(K)^(1/n)
    4021             :    * We consider v with T2(v) <= BMULT * T2(v0)
    4022             :    * Hence Nv <= ((4/3)^((n-1)/2) * BMULT / n)^(n/2) NI sqrt(disc(K)).
    4023             :    * NI <= LIMCMAX^2 */
    4024        1897 :   small_norm_prec = nbits2prec( BITS_IN_LONG +
    4025        1897 :     (N/2. * ((N-1)/2.*log(4./3) + log(BMULT/(double)N))
    4026        1897 :      + 2*log((double) LIMCMAX) + LOGD/2) / LOG2 ); /* enough to compute norms */
    4027        1897 :   if (small_norm_prec > PRECREG) PRECREG = small_norm_prec;
    4028        1897 :   if (!nf)
    4029        1820 :     nf = nfinit_complete(&nfT, flag_nfinit, PRECREG);
    4030          77 :   else if (nf_get_prec(nf) < PRECREG)
    4031           0 :     nf = nfnewprec_shallow(nf, PRECREG);
    4032        1897 :   M_sn = nf_get_M(nf);
    4033        1897 :   if (PRECREG > small_norm_prec) M_sn = gprec_w(M_sn, small_norm_prec);
    4034             : 
    4035        1897 :   zu = rootsof1(nf);
    4036        1897 :   gel(zu,2) = nf_to_scalar_or_alg(nf, gel(zu,2));
    4037             : 
    4038        1897 :   auts = automorphism_matrices(nf, &F.invs, &cyclic);
    4039        1897 :   F.embperm = automorphism_perms(nf_get_M(nf), auts, cyclic, N);
    4040             : 
    4041        1897 :   nf_get_sign(nf, &R1, &R2); RU = R1+R2;
    4042        1897 :   compute_vecG(nf, &F, minss(RU, 9));
    4043        1897 :   if (DEBUGLEVEL)
    4044             :   {
    4045           0 :     timer_printf(&T, "nfinit & rootsof1");
    4046           0 :     err_printf("R1 = %ld, R2 = %ld\nD = %Ps\n",R1,R2, D);
    4047             :   }
    4048        1897 :   if (LOGD < 20.) /* tiny disc, Minkowski *may* be smaller than Bach */
    4049             :   {
    4050        1624 :     lim = exp(-N + R2 * log(4/M_PI) + LOGD/2) * sqrt(2*M_PI*N);
    4051        1624 :     if (lim < 3) lim = 3;
    4052             :   }
    4053             :   else /* to be ignored */
    4054         273 :     lim = -1;
    4055        1897 :   if (cbach > 12.) {
    4056           0 :     if (cbach2 < cbach) cbach2 = cbach;
    4057           0 :     cbach = 12.;
    4058             :   }
    4059        1897 :   if (cbach < 0.)
    4060           0 :     pari_err_DOMAIN("Buchall","Bach constant","<",gen_0,dbltor(cbach));
    4061             : 
    4062        1897 :   cache.base = NULL; F.subFB = NULL; F.LP = NULL;
    4063        1897 :   init_GRHcheck(&GRHcheck, N, R1, LOGD);
    4064        1897 :   high = low = LIMC0 = maxss((long)(cbach2*LOGD2), 1);
    4065       12567 :   while (!GRHchk(nf, &GRHcheck, high))
    4066             :   {
    4067        8773 :     low = high;
    4068        8773 :     high *= 2;
    4069             :   }
    4070       10712 :   while (high - low > 1)
    4071             :   {
    4072        6918 :     long test = (low+high)/2;
    4073        6918 :     if (GRHchk(nf, &GRHcheck, test))
    4074        3949 :       high = test;
    4075             :     else
    4076        2969 :       low = test;
    4077             :   }
    4078        1897 :   if (high == LIMC0+1 && GRHchk(nf, &GRHcheck, LIMC0))
    4079           0 :     LIMC2 = LIMC0;
    4080             :   else
    4081        1897 :     LIMC2 = high;
    4082        1897 :   if (LIMC2 > LIMCMAX) LIMC2 = LIMCMAX;
    4083        1897 :   if (DEBUGLEVEL) err_printf("LIMC2 = %ld\n", LIMC2);
    4084        1897 :   if (LIMC2 < nthideal(&GRHcheck, nf, 1)) class1 = 1;
    4085        1897 :   if (DEBUGLEVEL && class1) err_printf("Class 1\n", LIMC2);
    4086        1897 :   LIMC0 = (long)(cbach*LOGD2);
    4087        1897 :   LIMC = cbach ? LIMC0 : LIMC2;
    4088        1897 :   LIMC = maxss(LIMC, nthideal(&GRHcheck, nf, N));
    4089        1897 :   if (DEBUGLEVEL) timer_printf(&T, "computing Bach constant");
    4090        1897 :   LIMres = primeneeded(N, R1, R2, LOGD);
    4091        1897 :   cache_prime_dec(&GRHcheck, LIMres, nf);
    4092             :   /* invhr ~ 2^r1 (2pi)^r2 / sqrt(D) w * Res(zeta_K, s=1) = 1 / hR */
    4093        3794 :   invhr = gmul(gdiv(gmul2n(powru(mppi(DEFAULTPREC), R2), RU),
    4094        1897 :               mulri(gsqrt(D,DEFAULTPREC),gel(zu,1))),
    4095             :               compute_invres(&GRHcheck, LIMres));
    4096        1897 :   if (DEBUGLEVEL) timer_printf(&T, "computing inverse of hR");
    4097        1897 :   av = avma;
    4098             : 
    4099             : START:
    4100        2044 :   if (DEBUGLEVEL) timer_start(&T);
    4101        2044 :   if (!FIRST) LIMC = bnf_increase_LIMC(LIMC,LIMCMAX);
    4102        2044 :   if (DEBUGLEVEL && LIMC > LIMC0)
    4103           0 :     err_printf("%s*** Bach constant: %f\n", FIRST?"":"\n", LIMC/LOGD2);
    4104        2044 :   if (cache.base)
    4105             :   {
    4106             :     REL_t *rel;
    4107        6561 :     for (i = 1, rel = cache.base + 1; rel < cache.last; rel++)
    4108        6414 :       if (rel->m) i++;
    4109         147 :     computed = cgetg(i, t_VEC);
    4110        6561 :     for (i = 1, rel = cache.base + 1; rel < cache.last; rel++)
    4111        6414 :       if (rel->m) gel(computed, i++) = rel->m;
    4112         147 :     computed = gclone(computed);
    4113         147 :     delete_cache(&cache);
    4114             :   }
    4115        2044 :   FIRST = 0; avma = av;
    4116        2044 :   if (F.LP) delete_FB(&F);
    4117        2044 :   if (LIMC2 < LIMC) LIMC2 = LIMC;
    4118        2044 :   if (DEBUGLEVEL) { err_printf("LIMC = %ld, LIMC2 = %ld\n",LIMC,LIMC2); }
    4119             : 
    4120        2044 :   FBgen(&F, nf, N, LIMC, LIMC2, &GRHcheck);
    4121        2044 :   if (!F.KC) goto START;
    4122        2044 :   av = avma;
    4123        2044 :   subFBgen(&F,auts,cyclic,lim < 0? LIMC2: mindd(lim,LIMC2),MINSFB);
    4124        2044 :   if (DEBUGLEVEL)
    4125             :   {
    4126           0 :     if (lg(F.subFB) > 1)
    4127           0 :       timer_printf(&T, "factorbase (#subFB = %ld) and ideal permutations",
    4128           0 :                        lg(F.subFB)-1);
    4129             :     else
    4130           0 :       timer_printf(&T, "factorbase (no subFB) and ideal permutations");
    4131             :   }
    4132        2044 :   fact = (FACT*)stack_malloc((F.KC+1)*sizeof(FACT));
    4133        2044 :   PERM = leafcopy(F.perm); /* to be restored in case of precision increase */
    4134        2044 :   cache.basis = zero_Flm_copy(F.KC,F.KC);
    4135        2044 :   small_multiplier = zero_Flv(F.KC);
    4136        2044 :   F.id2 = zerovec(F.KC);
    4137        2044 :   MAXDEPSIZESFB = (lg(F.subFB) - 1) * DEPSIZESFBMULT;
    4138        2044 :   MAXDEPSFB = MAXDEPSIZESFB / DEPSFBDIV;
    4139        2044 :   done_small = 0; small_fail = 0; squash_index = 0;
    4140        2044 :   fail_limit = F.KC + 1;
    4141        2044 :   R = NULL; A = NULL;
    4142        2044 :   av2 = avma;
    4143        2044 :   init_rel(&cache, &F, RELSUP + RU-1); /* trivial relations */
    4144        2044 :   old_need = need = cache.end - cache.last;
    4145        2044 :   add_cyclotomic_units(nf, zu, &cache, &F);
    4146        2044 :   cache.end = cache.last + need;
    4147             : 
    4148        2044 :   W = NULL; zc = 0;
    4149        2044 :   sfb_trials = nreldep = 0;
    4150             : 
    4151        2044 :   if (computed)
    4152             :   {
    4153        1806 :     for (i = 1; i < lg(computed); i++)
    4154        1659 :       try_elt(&cache, &F, nf, gel(computed, i), fact);
    4155         147 :     if (isclone(computed)) gunclone(computed);
    4156         147 :     if (DEBUGLEVEL && i > 1)
    4157             :     {
    4158           0 :       err_printf("\n");
    4159           0 :       timer_printf(&T, "including already computed relations");
    4160             :     }
    4161         147 :     need = 0;
    4162             :   }
    4163             : 
    4164             :   do
    4165             :   {
    4166             :     do
    4167             :     {
    4168       19222 :       pari_sp av4 = avma;
    4169       19222 :       if (need > 0)
    4170             :       {
    4171       18960 :         long oneed = cache.end - cache.last;
    4172             :         /* Test below can be true if small_norm did not find enough linearly
    4173             :          * dependent relations */
    4174       18960 :         if (need < oneed) need = oneed;
    4175       18960 :         pre_allocate(&cache, need+lg(auts)-1+(R ? lg(W)-1 : 0));
    4176       18960 :         cache.end = cache.last + need;
    4177       18960 :         F.L_jid = trim_list(&F);
    4178             :       }
    4179       19222 :       if (need > 0 && nbrelpid > 0 && (done_small <= F.KC+1 || A) &&
    4180       17735 :           small_fail <= fail_limit &&
    4181       17735 :           cache.last < cache.base + 2*F.KC+2*RU+RELSUP /* heuristic */)
    4182             :       {
    4183       15742 :         pari_sp av3 = avma;
    4184       15742 :         GEN p0 = NULL;
    4185             :         long j, k;
    4186       15742 :         REL_t *last = cache.last;
    4187       15742 :         if (R && lg(W) > 1 && (done_small % 2))
    4188             :         {
    4189             :           /* We have full rank for class group and unit, however those
    4190             :            * lattices are too small. The following tries to improve the
    4191             :            * prime group lattice: it specifically looks for relations
    4192             :            * involving the primes generating the class group. */
    4193         608 :           long l = lg(W) - 1;
    4194             :           /* We need lg(W)-1 relations to squash the class group. */
    4195         608 :           F.L_jid = vecslice(F.perm, 1, l); cache.end = cache.last + l;
    4196             :           /* Lie to the add_rel subsystem: pretend we miss relations involving
    4197             :            * the primes generating the class group (and only those). */
    4198         608 :           cache.missing = l;
    4199         608 :           for ( ; l > 0; l--) mael(cache.basis, F.perm[l], F.perm[l]) = 0;
    4200             :         }
    4201       15742 :         j = done_small % (F.KC+1);
    4202       15742 :         if (j)
    4203             :         {
    4204       13432 :           long mj = small_multiplier[j];
    4205       13432 :           p0 = gel(F.LP, j);
    4206       13432 :           if (!A)
    4207             :           {
    4208             :             /* Prevent considering both P_iP_j and P_jP_i in small_norm */
    4209             :             /* Since not all elements end up in F.L_jid (because they can
    4210             :              * be eliminated by hnfspec/add or by trim_list, keep track
    4211             :              * of which ideals are being considered at each run. */
    4212      336907 :             for (i = k = 1; i < lg(F.L_jid); i++)
    4213      327743 :               if (F.L_jid[i] > mj)
    4214             :               {
    4215      274551 :                 small_multiplier[F.L_jid[i]] = j;
    4216      274551 :                 F.L_jid[k++] = F.L_jid[i];
    4217             :               }
    4218        9164 :             setlg(F.L_jid, k);
    4219             :           }
    4220             :         }
    4221       15742 :         if (lg(F.L_jid) > 1)
    4222       15518 :           small_norm(&cache, &F, nf, nbrelpid, M_sn, fact, p0);
    4223       15742 :         avma = av3;
    4224       15742 :         if (!A && cache.last != last)
    4225        3708 :           small_fail = 0;
    4226             :         else
    4227       12034 :           small_fail++;
    4228       15742 :         if (R && lg(W) > 1 && (done_small % 2))
    4229             :         {
    4230         608 :           long l = lg(W) - 1;
    4231         608 :           for ( ; l > 0; l--) mael(cache.basis, F.perm[l], F.perm[l]) = 1;
    4232         608 :           cache.missing = 0;
    4233             :         }
    4234       15742 :         F.L_jid = F.perm;
    4235       15742 :         need = 0; cache.end = cache.last;
    4236       15742 :         done_small++;
    4237       15742 :         F.sfb_chg = 0;
    4238             :       }
    4239       19222 :       if (need > 0)
    4240             :       {
    4241             :         /* Random relations */
    4242        3218 :         if (lg(F.subFB) == 1) goto START;
    4243        3078 :         nreldep++;
    4244        3078 :         if (nreldep > MAXDEPSIZESFB) {
    4245          28 :           if (++sfb_trials > SFB_MAX && LIMC < LIMCMAX/6) goto START;
    4246          21 :           F.sfb_chg = sfb_INCREASE;
    4247          21 :           nreldep = 0;
    4248             :         }
    4249        3050 :         else if (!(nreldep % MAXDEPSFB))
    4250         440 :           F.sfb_chg = sfb_CHANGE;
    4251        3071 :         if (F.newpow)
    4252             :         {
    4253         309 :           F.sfb_chg = 0;
    4254         309 :           if (DEBUGLEVEL) err_printf("\n");
    4255             :         }
    4256        3071 :         if (F.sfb_chg && !subFB_change(&F)) goto START;
    4257        3071 :         if (F.newpow) {
    4258         455 :           powFBgen(&cache, &F, nf, auts);
    4259         455 :           MAXDEPSIZESFB = (lg(F.subFB) - 1) * DEPSIZESFBMULT;
    4260         455 :           MAXDEPSFB = MAXDEPSIZESFB / DEPSFBDIV;
    4261         455 :           if (DEBUGLEVEL) timer_printf(&T, "powFBgen");
    4262             :         }
    4263        3071 :         if (!F.sfb_chg) rnd_rel(&cache, &F, nf, fact);
    4264        3071 :         F.L_jid = F.perm;
    4265             :       }
    4266       19075 :       if (DEBUGLEVEL) timer_start(&T);
    4267       19075 :       if (precpb)
    4268             :       {
    4269         123 :         GEN nf0 = nf;
    4270         123 :         if (precadd) { PRECREG += precadd; precadd = 0; }
    4271          47 :         else           PRECREG = precdbl(PRECREG);
    4272         123 :         if (DEBUGLEVEL)
    4273             :         {
    4274           0 :           char str[64]; sprintf(str,"Buchall_param (%s)",precpb);
    4275           0 :           pari_warn(warnprec,str,PRECREG);
    4276             :         }
    4277         123 :         nf = gclone( nfnewprec_shallow(nf, PRECREG) );
    4278         123 :         if (precdouble) gunclone(nf0);
    4279         123 :         precdouble++; precpb = NULL;
    4280             : 
    4281         123 :         for (i = 1; i < lg(PERM); i++) F.perm[i] = PERM[i];
    4282         123 :         cache.chk = cache.base; W = NULL; /* recompute arch components+reduce */
    4283             :       }
    4284       19075 :       avma = av4;
    4285       19075 :       if (cache.chk != cache.last)
    4286             :       { /* Reduce relation matrices */
    4287       10506 :         long l = cache.last - cache.chk + 1, j;
    4288       10506 :         GEN M = nf_get_M(nf), mat = cgetg(l, t_MAT), emb = cgetg(l, t_MAT);
    4289       10506 :         int first = (W == NULL); /* never reduced before */
    4290             :         REL_t *rel;
    4291             : 
    4292       91540 :         for (j=1,rel = cache.chk + 1; j < l; rel++,j++)
    4293             :         {
    4294       81034 :           gel(mat,j) = rel->R;
    4295       81034 :           if (!rel->relaut)
    4296       49017 :             gel(emb,j) = get_log_embed(rel, M, RU, R1, PRECREG);
    4297             :           else
    4298       64034 :             gel(emb,j) = perm_log_embed(gel(emb, j-rel->relorig),
    4299       32017 :                                         gel(F.embperm, rel->relaut));
    4300             :         }
    4301       10506 :         if (DEBUGLEVEL) timer_printf(&T, "floating point embeddings");
    4302       10506 :         if (first) {
    4303        2167 :           C = emb;
    4304        2167 :           W = hnfspec_i(mat, F.perm, &dep, &B, &C, F.subFB ? lg(F.subFB)-1:0);
    4305             :         }
    4306             :         else
    4307        8339 :           W = hnfadd_i(W, F.perm, &dep, &B, &C, mat, emb);
    4308       10506 :         gerepileall(av2, 4, &W,&C,&B,&dep);
    4309       10506 :         cache.chk = cache.last;
    4310       10506 :         if (DEBUGLEVEL)
    4311             :         {
    4312           0 :           if (first)
    4313           0 :             timer_printf(&T, "hnfspec [%ld x %ld]", lg(F.perm)-1, l-1);
    4314             :           else
    4315           0 :             timer_printf(&T, "hnfadd (%ld + %ld)", l-1, lg(dep)-1);
    4316             :         }
    4317             :       }
    4318        8569 :       else if (!W)
    4319             :       {
    4320           0 :         need = old_need;
    4321           0 :         F.L_jid = vecslice(F.perm, 1, need);
    4322           0 :         continue;
    4323             :       }
    4324       19075 :       need = F.KC - (lg(W)-1) - (lg(B)-1);
    4325             :       /* FIXME: replace by err(e_BUG,"") */
    4326       19075 :       if (!need && cache.missing)
    4327             :       { /* The test above will never be true except if 27449|class number,
    4328             :          * but the code implicitely assumes that if we have maximal rank
    4329             :          * for the ideal lattice, then cache.missing == 0. */
    4330          14 :         for (i = 1; cache.missing; i++)
    4331           7 :           if (!mael(cache.basis, i, i))
    4332             :           {
    4333             :             long j;
    4334           7 :             mael(cache.basis, i, i) = 1;
    4335           7 :             cache.missing--;
    4336           7 :             for (j = i+1; j <= F.KC; j++) mael(cache.basis, j, i) = 0;
    4337             :           }
    4338             :       }
    4339       19075 :       zc = (lg(C)-1) - (lg(B)-1) - (lg(W)-1);
    4340       19075 :       if (zc < RU-1)
    4341             :       {
    4342             :         /* need more columns for units */
    4343        3856 :         need += RU-1 - zc;
    4344        3856 :         if (need > F.KC) need = F.KC;
    4345             :       }
    4346       19075 :       if (need)
    4347             :       { /* dependent rows */
    4348       10319 :         F.L_jid = vecslice(F.perm, 1, need);
    4349       10319 :         vecsmall_sort(F.L_jid);
    4350       10319 :         if (need != old_need) nreldep = 0;
    4351       10319 :         old_need = need;
    4352             :       }
    4353             :       else
    4354             :       {
    4355             :         /* If the relation lattice is too small, check will be > 1 and we
    4356             :          * will do a new run of small_norm/rnd_rel asking for 1 relation.
    4357             :          * However they tend to give a relation involving the first element
    4358             :          * of L_jid. We thus permute which element is the first of L_jid in
    4359             :          * order to increase the probability of finding a good relation, i.e.
    4360             :          * one that increases the relation lattice. */
    4361        8756 :         if (lg(W) > 2 && squash_index % (lg(W) - 1))
    4362        2712 :         {
    4363        2712 :           long j, l = lg(W) - 1;
    4364        2712 :           F.L_jid = leafcopy(F.perm);
    4365       15716 :           for (j = 1; j <= l; j++)
    4366       13004 :             F.L_jid[j] = F.perm[1 + (j + squash_index - 1) % l];
    4367             :         }
    4368             :         else
    4369        6044 :           F.L_jid = F.perm;
    4370        8756 :         squash_index++;
    4371             :       }
    4372             :     }
    4373       19075 :     while (need);
    4374        8756 :     if (!A)
    4375             :     {
    4376        1904 :       small_fail = 0; fail_limit = maxss(F.KC / FAIL_DIVISOR, MINFAIL);
    4377        1904 :       old_need = 0;
    4378             :     }
    4379        8756 :     A = vecslice(C, 1, zc); /* cols corresponding to units */
    4380        8756 :     R = compute_multiple_of_R(A, RU, N, &need, &lambda);
    4381        8756 :     if (need < old_need) small_fail = 0;
    4382        8756 :     old_need = need;
    4383        8756 :     if (!lambda) { precpb = "bestappr"; continue; }
    4384        8748 :     if (!R)
    4385             :     { /* not full rank for units */
    4386        5041 :       if (DEBUGLEVEL) err_printf("regulator is zero.\n");
    4387        5041 :       if (!need) precpb = "regulator";
    4388        5041 :       continue;
    4389             :     }
    4390             : 
    4391        3707 :     h = ZM_det_triangular(W);
    4392        3707 :     if (DEBUGLEVEL) err_printf("\n#### Tentative class number: %Ps\n", h);
    4393             : 
    4394        3707 :     switch (compute_R(lambda, mulir(h,invhr), &L, &R, &T))
    4395             :     {
    4396             :       case fupb_RELAT:
    4397        1695 :         need = 1; /* not enough relations */
    4398        1695 :         continue;
    4399             :       case fupb_PRECI: /* prec problem unless we cheat on Bach constant */
    4400          13 :         if ((precdouble&7) == 7 && LIMC<=LIMCMAX/6) goto START;
    4401          13 :         precpb = "compute_R";
    4402          13 :         continue;
    4403             :     }
    4404             :     /* DONE */
    4405             : 
    4406        1999 :     if (F.KCZ2 > F.KCZ)
    4407             :     {
    4408           7 :       if (F.sfb_chg && !subFB_change(&F)) goto START;
    4409           7 :       if (!be_honest(&F, nf, auts, fact)) goto START;
    4410           7 :       if (DEBUGLEVEL) timer_printf(&T, "to be honest");
    4411             :     }
    4412        1999 :     F.KCZ2 = 0; /* be honest only once */
    4413             : 
    4414             :     /* fundamental units */
    4415             :     {
    4416        1999 :       pari_sp av3 = avma;
    4417        1999 :       GEN AU, U, H, v = extract_full_lattice(L); /* L may be very large */
    4418             :       long e;
    4419        1999 :       if (v)
    4420             :       {
    4421           7 :         A = vecpermute(A, v);
    4422           7 :         L = vecpermute(L, v);
    4423             :       }
    4424             :       /* arch. components of fund. units */
    4425        1999 :       H = ZM_hnflll(L, &U, 1); U = vecslice(U, lg(U)-(RU-1), lg(U)-1);
    4426        1999 :       U = ZM_mul(U, ZM_lll(H, 0.99, LLL_IM|LLL_COMPATIBLE));
    4427        1999 :       AU = RgM_mul(A, U);
    4428        1999 :       A = cleanarch(AU, N, PRECREG);
    4429        1999 :       if (DEBUGLEVEL) timer_printf(&T, "cleanarch");
    4430        1999 :       if (!A) {
    4431           0 :         precadd = nbits2extraprec( gexpo(AU) + 64 ) - gprecision(AU);
    4432           0 :         if (precadd <= 0) precadd = 1;
    4433         102 :         precpb = "cleanarch"; continue;
    4434             :       }
    4435        1999 :       fu = getfu(nf, &A, &e, PRECREG);
    4436        1999 :       if (DEBUGLEVEL) timer_printf(&T, "getfu");
    4437        1999 :       if (!fu && (flun & nf_FORCE))
    4438             :       { /* units not found but we want them */
    4439         102 :         if (e > 0) pari_err_OVERFLOW("bnfinit [fundamental units too large]");
    4440         102 :         if (e < 0) precadd = nbits2extraprec( (-e - (BITS_IN_LONG - 1)) + 64);
    4441         102 :         avma = av3; precpb = "getfu"; continue;
    4442             :       }
    4443             :     }
    4444             :     /* class group generators */
    4445        1897 :     i = lg(C)-zc; C += zc; C[0] = evaltyp(t_MAT)|evallg(i);
    4446        1897 :     C0 = C; C = cleanarch(C, N, PRECREG);
    4447        1897 :     if (!C) {
    4448           0 :       precadd = nbits2extraprec( gexpo(C0) + 64 ) - gprecision(C0);
    4449           0 :       if (precadd <= 0) precadd = 1;
    4450           0 :       precpb = "cleanarch";
    4451             :     }
    4452        8756 :   } while (need || precpb);
    4453             : 
    4454        1897 :   delete_cache(&cache); delete_FB(&F); free_GRHcheck(&GRHcheck);
    4455        1897 :   Vbase = vecpermute(F.LP, F.perm);
    4456        1897 :   class_group_gen(nf,W,C,Vbase,PRECREG,NULL, &clg1, &clg2);
    4457        1897 :   res = get_clfu(clg1, R, zu, fu);
    4458        1897 :   res = buchall_end(nf,res,clg2,W,B,A,C,Vbase);
    4459        1897 :   res = gerepilecopy(av0, res); if (precdouble) gunclone(nf);
    4460        1897 :   return res;
    4461             : }

Generated by: LCOV version 1.11