Code coverage tests

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

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

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

LCOV - code coverage report
Current view: top level - basemath - buch2.c (source / functions) Hit Total Coverage
Test: PARI/GP v2.10.0 lcov report (development 21342-bb34613) Lines: 2303 2486 92.6 %
Date: 2017-11-18 06:21:14 Functions: 143 151 94.7 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.11