Code coverage tests

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

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

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

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

Generated by: LCOV version 1.13