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

Generated by: LCOV version 1.13