Code coverage tests

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

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

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

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

Generated by: LCOV version 1.11