Code coverage tests

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

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

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

LCOV - code coverage report
Current view: top level - basemath - ifactor1.c (source / functions) Hit Total Coverage
Test: PARI/GP v2.14.0 lcov report (development 27775-aca467eab2) Lines: 1528 1860 82.2 %
Date: 2022-07-03 07:33:15 Functions: 92 106 86.8 %
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; either version 2 of the License, or (at your option) any later
       8             : version. It is distributed in the hope that it will be useful, but WITHOUT
       9             : ANY WARRANTY WHATSOEVER.
      10             : 
      11             : Check the License for details. You should have received a copy of it, along
      12             : with the package; see the file 'COPYING'. If not, write to the Free Software
      13             : Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */
      14             : #include "pari.h"
      15             : #include "paripriv.h"
      16             : 
      17             : #define DEBUGLEVEL DEBUGLEVEL_factorint
      18             : 
      19             : /***********************************************************************/
      20             : /**                       PRIMES IN SUCCESSION                        **/
      21             : /***********************************************************************/
      22             : 
      23             : /* map from prime residue classes mod 210 to their numbers in {0...47}.
      24             :  * Subscripts into this array take the form ((k-1)%210)/2, ranging from
      25             :  * 0 to 104.  Unused entries are */
      26             : #define NPRC 128 /* nonprime residue class */
      27             : 
      28             : static unsigned char prc210_no[] = {
      29             :   0, NPRC, NPRC, NPRC, NPRC, 1, 2, NPRC, 3, 4, NPRC, /* 21 */
      30             :   5, NPRC, NPRC, 6, 7, NPRC, NPRC, 8, NPRC, 9, /* 41 */
      31             :   10, NPRC, 11, NPRC, NPRC, 12, NPRC, NPRC, 13, 14, NPRC, /* 63 */
      32             :   NPRC, 15, NPRC, 16, 17, NPRC, NPRC, 18, NPRC, 19, /* 83 */
      33             :   NPRC, NPRC, 20, NPRC, NPRC, NPRC, 21, NPRC, 22, 23, NPRC, /* 105 */
      34             :   24, 25, NPRC, 26, NPRC, NPRC, NPRC, 27, NPRC, NPRC, /* 125 */
      35             :   28, NPRC, 29, NPRC, NPRC, 30, 31, NPRC, 32, NPRC, NPRC, /* 147 */
      36             :   33, 34, NPRC, NPRC, 35, NPRC, NPRC, 36, NPRC, 37, /* 167 */
      37             :   38, NPRC, 39, NPRC, NPRC, 40, 41, NPRC, NPRC, 42, NPRC, /* 189 */
      38             :   43, 44, NPRC, 45, 46, NPRC, NPRC, NPRC, NPRC, 47, /* 209 */
      39             : };
      40             : 
      41             : /* first differences of the preceding */
      42             : static unsigned char prc210_d1[] = {
      43             :   10, 2, 4, 2, 4, 6, 2, 6, 4, 2, 4, 6, 6, 2, 6, 4, 2, 6,
      44             :   4, 6, 8, 4, 2, 4, 2, 4, 8, 6, 4, 6, 2, 4, 6,
      45             :   2, 6, 6, 4, 2, 4, 6, 2, 6, 4, 2, 4, 2, 10, 2,
      46             : };
      47             : 
      48             : static int
      49      946151 : unextprime_overflow(ulong n)
      50             : {
      51             : #ifdef LONG_IS_64BIT
      52      916555 :   return (n > (ulong)-59);
      53             : #else
      54       29596 :   return (n > (ulong)-5);
      55             : #endif
      56             : }
      57             : 
      58             : /* return 0 for overflow */
      59             : ulong
      60      956950 : unextprime(ulong n)
      61             : {
      62             :   long rc, rc0, rcn;
      63             : 
      64      956950 :   switch(n) {
      65        5962 :     case 0: case 1: case 2: return 2;
      66        2210 :     case 3: return 3;
      67        1535 :     case 4: case 5: return 5;
      68        1085 :     case 6: case 7: return 7;
      69             :   }
      70      946158 :   if (unextprime_overflow(n)) return 0;
      71             :   /* here n > 7 */
      72      946127 :   n |= 1; /* make it odd */
      73      946127 :   rc = rc0 = n % 210;
      74             :   /* find next prime residue class mod 210 */
      75             :   for(;;)
      76             :   {
      77     3097533 :     rcn = (long)(prc210_no[rc>>1]);
      78     2021830 :     if (rcn != NPRC) break;
      79     1075703 :     rc += 2; /* cannot wrap since 209 is coprime and rc odd */
      80             :   }
      81      946127 :   if (rc > rc0) n += rc - rc0;
      82             :   /* now find an actual (pseudo)prime */
      83             :   for(;;)
      84             :   {
      85     9233047 :     if (uisprime(n)) break;
      86     8286920 :     n += prc210_d1[rcn];
      87     8286920 :     if (++rcn > 47) rcn = 0;
      88             :   }
      89      946148 :   return n;
      90             : }
      91             : 
      92             : GEN
      93      126624 : nextprime(GEN n)
      94             : {
      95             :   long rc, rc0, rcn;
      96      126624 :   pari_sp av = avma;
      97             : 
      98      126624 :   if (typ(n) != t_INT)
      99             :   {
     100          14 :     n = gceil(n);
     101          14 :     if (typ(n) != t_INT) pari_err_TYPE("nextprime",n);
     102             :   }
     103      126617 :   if (signe(n) <= 0) { set_avma(av); return gen_2; }
     104      126617 :   if (lgefint(n) == 3)
     105             :   {
     106      118605 :     ulong k = unextprime(uel(n,2));
     107      118605 :     set_avma(av);
     108      118605 :     if (k) return utoipos(k);
     109             : #ifdef LONG_IS_64BIT
     110           6 :     return uutoi(1,13);
     111             : #else
     112           1 :     return uutoi(1,15);
     113             : #endif
     114             :   }
     115             :   /* here n > 7 */
     116        8012 :   if (!mod2(n)) n = addui(1,n);
     117        8012 :   rc = rc0 = umodiu(n, 210);
     118             :   /* find next prime residue class mod 210 */
     119             :   for(;;)
     120             :   {
     121       26848 :     rcn = (long)(prc210_no[rc>>1]);
     122       17430 :     if (rcn != NPRC) break;
     123        9418 :     rc += 2; /* cannot wrap since 209 is coprime and rc odd */
     124             :   }
     125        8012 :   if (rc > rc0) n = addui(rc - rc0, n);
     126             :   /* now find an actual (pseudo)prime */
     127             :   for(;;)
     128             :   {
     129       83096 :     if (BPSW_psp(n)) break;
     130       75084 :     n = addui(prc210_d1[rcn], n);
     131       75084 :     if (++rcn > 47) rcn = 0;
     132             :   }
     133        8012 :   if (avma == av) return icopy(n);
     134        8012 :   return gerepileuptoint(av, n);
     135             : }
     136             : 
     137             : ulong
     138          32 : uprecprime(ulong n)
     139             : {
     140             :   long rc, rc0, rcn;
     141             :   { /* check if n <= 10 */
     142          32 :     if (n <= 1)  return 0;
     143          25 :     if (n == 2)  return 2;
     144          18 :     if (n <= 4)  return 3;
     145          18 :     if (n <= 6)  return 5;
     146          18 :     if (n <= 10) return 7;
     147             :   }
     148             :   /* here n >= 11 */
     149          18 :   if (!(n % 2)) n--;
     150          18 :   rc = rc0 = n % 210;
     151             :   /* find previous prime residue class mod 210 */
     152             :   for(;;)
     153             :   {
     154          54 :     rcn = (long)(prc210_no[rc>>1]);
     155          36 :     if (rcn != NPRC) break;
     156          18 :     rc -= 2; /* cannot wrap since 1 is coprime and rc odd */
     157             :   }
     158          18 :   if (rc < rc0) n += rc - rc0;
     159             :   /* now find an actual (pseudo)prime */
     160             :   for(;;)
     161             :   {
     162          36 :     if (uisprime(n)) break;
     163          18 :     if (--rcn < 0) rcn = 47;
     164          18 :     n -= prc210_d1[rcn];
     165             :   }
     166          18 :   return n;
     167             : }
     168             : 
     169             : GEN
     170          49 : precprime(GEN n)
     171             : {
     172             :   long rc, rc0, rcn;
     173          49 :   pari_sp av = avma;
     174             : 
     175          49 :   if (typ(n) != t_INT)
     176             :   {
     177          14 :     n = gfloor(n);
     178          14 :     if (typ(n) != t_INT) pari_err_TYPE("nextprime",n);
     179             :   }
     180          42 :   if (signe(n) <= 0) { set_avma(av); return gen_0; }
     181          42 :   if (lgefint(n) <= 3)
     182             :   {
     183          32 :     ulong k = uel(n,2);
     184          32 :     set_avma(av);
     185          32 :     return utoi(uprecprime(k));
     186             :   }
     187          10 :   if (!mod2(n)) n = subiu(n,1);
     188          10 :   rc = rc0 = umodiu(n, 210);
     189             :   /* find previous prime residue class mod 210 */
     190             :   for(;;)
     191             :   {
     192          30 :     rcn = (long)(prc210_no[rc>>1]);
     193          20 :     if (rcn != NPRC) break;
     194          10 :     rc -= 2; /* cannot wrap since 1 is coprime and rc odd */
     195             :   }
     196          10 :   if (rc0 > rc) n = subiu(n, rc0 - rc);
     197             :   /* now find an actual (pseudo)prime */
     198             :   for(;;)
     199             :   {
     200          48 :     if (BPSW_psp(n)) break;
     201          38 :     if (--rcn < 0) rcn = 47;
     202          38 :     n = subiu(n, prc210_d1[rcn]);
     203             :   }
     204          10 :   if (avma == av) return icopy(n);
     205          10 :   return gerepileuptoint(av, n);
     206             : }
     207             : 
     208             : /* Find next single-word prime strictly larger than p.
     209             :  * If **d is non-NULL (somewhere in a diffptr), this is p + *(*d)++;
     210             :  * otherwise imitate nextprime().
     211             :  * *rcn = NPRC or the correct residue class for the current p; we'll use this
     212             :  * to track the current prime residue class mod 210 once we're out of range of
     213             :  * the diffptr table, and we'll update it before that if it isn't NPRC.
     214             :  *
     215             :  * *q is incremented whenever q!=NULL and we wrap from 209 mod 210 to
     216             :  * 1 mod 210 */
     217             : ulong
     218     4659536 : snextpr(ulong p, byteptr *d, long *rcn, long *q, int (*ispsp)(ulong))
     219             : {
     220     4659536 :   if (**d)
     221             :   {
     222     4659536 :     byteptr dd = *d;
     223     4659536 :     long d1 = 0;
     224             : 
     225     4659536 :     NEXT_PRIME_VIADIFF(d1,dd);
     226             :     /* d1 = nextprime(p+1) - p */
     227     4659536 :     if (*rcn != NPRC)
     228             :     {
     229    16289252 :       while (d1 > 0)
     230             :       {
     231    11647380 :         d1 -= prc210_d1[*rcn];
     232    11647380 :         if (++*rcn > 47) { *rcn = 0; if (q) (*q)++; }
     233             :       }
     234             :       /* assert(d1 == 0) */
     235             :     }
     236     4659536 :     NEXT_PRIME_VIADIFF(p,*d);
     237     4659536 :     return p;
     238             :   }
     239           0 :   if (unextprime_overflow(p)) pari_err_OVERFLOW("snextpr");
     240             :   /* we are beyond the diffptr table, initialize if needed */
     241           0 :   if (*rcn == NPRC) *rcn = prc210_no[(p % 210) >> 1]; /* != NPRC */
     242             :   /* look for the next one */
     243             :   do {
     244           0 :     p += prc210_d1[*rcn];
     245           0 :     if (++*rcn > 47) { *rcn = 0; if (q) (*q)++; }
     246           0 :   } while (!ispsp(p));
     247           0 :   return p;
     248             : }
     249             : 
     250             : /********************************************************************/
     251             : /**                                                                **/
     252             : /**                     INTEGER FACTORIZATION                      **/
     253             : /**                                                                **/
     254             : /********************************************************************/
     255             : int factor_add_primes = 0, factor_proven = 0;
     256             : 
     257             : /***********************************************************************/
     258             : /**                                                                   **/
     259             : /**                 FACTORIZATION (ECM) -- GN Jul-Aug 1998            **/
     260             : /**   Integer factorization using the elliptic curves method (ECM).   **/
     261             : /**   ellfacteur() returns a non trivial factor of N, assuming N>0,   **/
     262             : /**   is composite, and has no prime divisor below 2^14 or so.        **/
     263             : /**   Thanks to Paul Zimmermann for much helpful advice and to        **/
     264             : /**   Guillaume Hanrot and Igor Schein for intensive testing          **/
     265             : /**                                                                   **/
     266             : /***********************************************************************/
     267             : #define nbcmax 64 /* max number of simultaneous curves */
     268             : 
     269             : static const ulong TB1[] = {
     270             :   142,172,208,252,305,370,450,545,661,801,972,1180,1430,
     271             :   1735,2100,2550,3090,3745,4540,5505,6675,8090,9810,11900,
     272             :   14420,17490,21200,25700,31160,37780UL,45810UL,55550UL,67350UL,
     273             :   81660UL,99010UL,120050UL,145550UL,176475UL,213970UL,259430UL,
     274             :   314550UL,381380UL,462415UL,560660UL,679780UL,824220UL,999340UL,
     275             :   1211670UL,1469110UL,1781250UL,2159700UL,2618600UL,3175000UL,
     276             :   3849600UL,4667500UL,5659200UL,6861600UL,8319500UL,10087100UL,
     277             :   12230300UL,14828900UL,17979600UL,21799700UL,26431500UL,
     278             :   32047300UL,38856400UL, /* 110 times that still fits into 32bits */
     279             : #ifdef LONG_IS_64BIT
     280             :   47112200UL,57122100UL,69258800UL,83974200UL,101816200UL,
     281             :   123449000UL,149678200UL,181480300UL,220039400UL,266791100UL,
     282             :   323476100UL,392204900UL,475536500UL,576573500UL,699077800UL,
     283             :   847610500UL,1027701900UL,1246057200UL,1510806400UL,1831806700UL,
     284             :   2221009800UL,2692906700UL,3265067200UL,3958794400UL,4799917500UL
     285             : #endif
     286             : };
     287             : static const ulong TB1_for_stage[] = {
     288             :  /* Start below the optimal B1 for finding factors which would just have been
     289             :   * missed by pollardbrent(), and escalate, changing curves to give good
     290             :   * coverage of the small factor ranges. Entries grow faster than what would
     291             :   * be optimal but a table instead of a 2D array keeps the code simple */
     292             :   500,520,560,620,700,800,900,1000,1150,1300,1450,1600,1800,2000,
     293             :   2200,2450,2700,2950,3250,3600,4000,4400,4850,5300,5800,6400,
     294             :   7100,7850,8700,9600,10600,11700,12900,14200,15700,17300,
     295             :   19000,21000,23200,25500,28000,31000,34500UL,38500UL,43000UL,
     296             :   48000UL,53800UL,60400UL,67750UL,76000UL,85300UL,95700UL,
     297             :   107400UL,120500UL,135400UL,152000UL,170800UL,191800UL,215400UL,
     298             :   241800UL,271400UL,304500UL,341500UL,383100UL,429700UL,481900UL,
     299             :   540400UL,606000UL,679500UL,761800UL,854100UL,957500UL,1073500UL
     300             : };
     301             : 
     302             : /* addition/doubling/multiplication of a point on an 'elliptic curve mod N'
     303             :  * may result in one of three things:
     304             :  * - a new bona fide point
     305             :  * - a point at infinity (denominator divisible by N)
     306             :  * - a point at infinity mod some p | N but finite mod q | N betraying itself
     307             :  *   by a denominator which has nontrivial gcd with N.
     308             :  *
     309             :  * In the second case, addition/doubling aborts, copying one of the summands
     310             :  * to the destination array of points unless they coincide.
     311             :  * Multiplication will stop at some unpredictable intermediate stage:  The
     312             :  * destination will contain _some_ multiple of the input point, but not
     313             :  * necessarily the desired one, which doesn't matter.  As long as we're
     314             :  * multiplying (B1 phase) we simply carry on with the next multiplier.
     315             :  * During the B2 phase, the only additions are the giant steps, and the
     316             :  * worst that can happen here is that we lose one residue class mod 210
     317             :  * of prime multipliers on 4 of the curves, so again, we ignore the problem
     318             :  * and just carry on.)
     319             :  *
     320             :  * Idea: select nbc curves mod N and one point P on each of them. For each
     321             :  * such P, compute [M]P = Q where M is the product of all powers <= B2 of
     322             :  * primes <= nextprime(B1). Then check whether [p]Q for p < nextprime(B2)
     323             :  * betrays a factor. This second stage looks separately at the primes in
     324             :  * each residue class mod 210, four curves at a time, and steps additively
     325             :  * to ever larger multipliers, by comparing X coordinates of points which we
     326             :  * would need to add in order to reach another prime multiplier in the same
     327             :  * residue class. 'Comparing' means that we accumulate a product of
     328             :  * differences of X coordinates, and from time to time take a gcd of this
     329             :  * product with N. Montgomery's multi-inverse trick is used heavily. */
     330             : 
     331             : /* *** auxiliary functions for ellfacteur: *** */
     332             : /* (Rx,Ry) <- (Px,Py)+(Qx,Qy) over Z/NZ, z=1/(Px-Qx). If Ry = NULL, don't set */
     333             : static void
     334     8437096 : FpE_add_i(GEN N, GEN z, GEN Px, GEN Py, GEN Qx, GEN Qy, GEN *Rx, GEN *Ry)
     335             : {
     336     8437096 :   GEN slope = modii(mulii(subii(Py, Qy), z), N);
     337     8437096 :   GEN t = subii(sqri(slope), addii(Qx, Px));
     338     8437096 :   affii(modii(t, N), *Rx);
     339     8437096 :   if (Ry) {
     340     8362212 :     t = subii(mulii(slope, subii(Px, *Rx)), Py);
     341     8362212 :     affii(modii(t, N), *Ry);
     342             :   }
     343     8437096 : }
     344             : /* X -> Z; cannot add on one of the curves: make sure Z contains
     345             :  * something useful before letting caller proceed */
     346             : static void
     347       29178 : ZV_aff(long n, GEN *X, GEN *Z)
     348             : {
     349       29178 :   if (X != Z) {
     350             :     long k;
     351     1618204 :     for (k = n; k--; ) affii(X[k],Z[k]);
     352             :   }
     353       29178 : }
     354             : 
     355             : /* Parallel addition on nbc curves, assigning the result to locations at and
     356             :  * following *X3, *Y3. (If Y-coords of result not desired, set Y=NULL.)
     357             :  * Safe even if (X3,Y3) = (X2,Y2), _not_ if (X1,Y1). It is also safe to
     358             :  * overwrite Y2 with X3. If nbc1 < nbc, the first summand is
     359             :  * assumed to hold only nbc1 distinct points, repeated as often as we need
     360             :  * them  (to add one point on each of a few curves to several other points on
     361             :  * the same curves): only used with nbc1 = nbc or nbc1 = 4 | nbc.
     362             :  *
     363             :  * Return 0 [SUCCESS], 1 [N | den], 2 [gcd(den, N) is a factor of N, preserved
     364             :  * in gl.
     365             :  * Stack space is bounded by a constant multiple of lgefint(N)*nbc:
     366             :  * - Phase 2 creates 12 items on the stack per iteration, of which 4 are twice
     367             :  *   as long and 1 is thrice as long as N, i.e. 18 units per iteration.
     368             :  * - Phase  1 creates 4 units.
     369             :  * Total can be as large as 4*nbcmax + 18*8 units; ecm_elladd2() is
     370             :  * just as bad, and elldouble() comes to 3*nbcmax + 29*8 units. */
     371             : static int
     372      257042 : ecm_elladd0(GEN N, GEN *gl, long nbc, long nbc1,
     373             :             GEN *X1, GEN *Y1, GEN *X2, GEN *Y2, GEN *X3, GEN *Y3)
     374             : {
     375      257042 :   const ulong mask = (nbc1 == 4)? 3: ~0UL; /*nbc1 = 4 or nbc*/
     376      257042 :   GEN W[2*nbcmax], *A = W+nbc; /* W[0],A[0] unused */
     377             :   long i;
     378      257042 :   pari_sp av = avma;
     379             : 
     380      257042 :   W[1] = subii(X1[0], X2[0]);
     381     7972896 :   for (i=1; i<nbc; i++)
     382             :   { /*prepare for multi-inverse*/
     383     7715854 :     A[i] = subii(X1[i&mask], X2[i]); /* don't waste time reducing mod N */
     384     7715854 :     W[i+1] = modii(mulii(A[i], W[i]), N);
     385             :   }
     386      257042 :   if (!invmod(W[nbc], N, gl))
     387             :   {
     388         494 :     if (!equalii(N,*gl)) return 2;
     389         462 :     ZV_aff(nbc, X2,X3);
     390         462 :     if (Y3) ZV_aff(nbc, Y2,Y3);
     391         462 :     return gc_int(av,1);
     392             :   }
     393             : 
     394     7964584 :   while (i--) /* nbc times */
     395             :   {
     396     7964584 :     pari_sp av2 = avma;
     397     7964584 :     GEN Px = X1[i&mask], Py = Y1[i&mask], Qx = X2[i], Qy = Y2[i];
     398     7964584 :     GEN z = i? mulii(*gl,W[i]): *gl; /*1/(Px-Qx)*/
     399     7964584 :     FpE_add_i(N,z,  Px,Py,Qx,Qy, X3+i, Y3? Y3+i: NULL);
     400     7964584 :     if (!i) break;
     401     7708036 :     set_avma(av2); *gl = modii(mulii(*gl, A[i]), N);
     402             :   }
     403      256548 :   return gc_int(av,0);
     404             : }
     405             : 
     406             : /* Shortcut, for use in cases where Y coordinates follow their corresponding
     407             :  * X coordinates, and first summand doesn't need to be repeated */
     408             : static int
     409      250776 : ecm_elladd(GEN N, GEN *gl, long nbc, GEN *X1, GEN *X2, GEN *X3) {
     410      250776 :   return ecm_elladd0(N, gl, nbc, nbc, X1, X1+nbc, X2, X2+nbc, X3, X3+nbc);
     411             : }
     412             : 
     413             : /* As ecm_elladd except it does twice as many additions (and hides even more
     414             :  * of the cost of the modular inverse); the net effect is the same as
     415             :  * ecm_elladd(nbc,X1,X2,X3) && ecm_elladd(nbc,X4,X5,X6). Safe to
     416             :  * have X2=X3, X5=X6, or X1,X2 coincide with X4,X5 in any order. */
     417             : static int
     418        7586 : ecm_elladd2(GEN N, GEN *gl, long nbc,
     419             :             GEN *X1, GEN *X2, GEN *X3, GEN *X4, GEN *X5, GEN *X6)
     420             : {
     421        7586 :   GEN *Y1 = X1+nbc, *Y2 = X2+nbc, *Y3 = X3+nbc;
     422        7586 :   GEN *Y4 = X4+nbc, *Y5 = X5+nbc, *Y6 = X6+nbc;
     423        7586 :   GEN W[4*nbcmax], *A = W+2*nbc; /* W[0],A[0] unused */
     424             :   long i, j;
     425        7586 :   pari_sp av = avma;
     426             : 
     427        7586 :   W[1] = subii(X1[0], X2[0]);
     428      236368 :   for (i=1; i<nbc; i++)
     429             :   {
     430      228782 :     A[i] = subii(X1[i], X2[i]); /* don't waste time reducing mod N here */
     431      228782 :     W[i+1] = modii(mulii(A[i], W[i]), N);
     432             :   }
     433      243954 :   for (j=0; j<nbc; i++,j++)
     434             :   {
     435      236368 :     A[i] = subii(X4[j], X5[j]);
     436      236368 :     W[i+1] = modii(mulii(A[i], W[i]), N);
     437             :   }
     438        7586 :   if (!invmod(W[2*nbc], N, gl))
     439             :   {
     440          14 :     if (!equalii(N,*gl)) return 2;
     441          14 :     ZV_aff(2*nbc, X2,X3); /* hack: 2*nbc => copy Y2->Y3 */
     442          14 :     ZV_aff(2*nbc, X5,X6); /* also copy Y5->Y6 */
     443          14 :     return gc_int(av,1);
     444             :   }
     445             : 
     446      243828 :   while (j--) /* nbc times */
     447             :   {
     448      236256 :     pari_sp av2 = avma;
     449      236256 :     GEN Px = X4[j], Py = Y4[j], Qx = X5[j], Qy = Y5[j];
     450      236256 :     GEN z = mulii(*gl,W[--i]); /*1/(Px-Qx)*/
     451      236256 :     FpE_add_i(N,z, Px,Py, Qx,Qy, X6+j,Y6+j);
     452      236256 :     set_avma(av2); *gl = modii(mulii(*gl, A[i]), N);
     453             :   }
     454      236256 :   while (i--) /* nbc times */
     455             :   {
     456      236256 :     pari_sp av2 = avma;
     457      236256 :     GEN Px = X1[i], Py = Y1[i], Qx = X2[i], Qy = Y2[i];
     458      236256 :     GEN z = i? mulii(*gl, W[i]): *gl; /*1/(Px-Qx)*/
     459      236256 :     FpE_add_i(N,z, Px,Py, Qx,Qy, X3+i,Y3+i);
     460      236256 :     if (!i) break;
     461      228684 :     set_avma(av2); *gl = modii(mulii(*gl, A[i]), N);
     462             :   }
     463        7572 :   return gc_int(av,0);
     464             : }
     465             : 
     466             : /* Parallel doubling on nbc curves, assigning the result to locations at
     467             :  * and following *X2.  Safe to be called with X2 equal to X1.  Return
     468             :  * value as for ecm_elladd.  If we find a point at infinity mod N,
     469             :  * and if X1 != X2, we copy the points at X1 to X2. */
     470             : static int
     471       43951 : elldouble(GEN N, GEN *gl, long nbc, GEN *X1, GEN *X2)
     472             : {
     473       43951 :   GEN *Y1 = X1+nbc, *Y2 = X2+nbc;
     474             :   GEN W[nbcmax+1]; /* W[0] unused */
     475             :   long i;
     476       43951 :   pari_sp av = avma;
     477       43951 :   /*W[0] = gen_1;*/ W[1] = Y1[0];
     478     1264568 :   for (i=1; i<nbc; i++) W[i+1] = modii(mulii(Y1[i], W[i]), N);
     479       43951 :   if (!invmod(W[nbc], N, gl))
     480             :   {
     481           0 :     if (!equalii(N,*gl)) return 2;
     482           0 :     ZV_aff(2*nbc,X1,X2); /* also copies Y1->Y2 */
     483           0 :     return gc_int(av,1);
     484             :   }
     485     1308519 :   while (i--) /* nbc times */
     486             :   {
     487             :     pari_sp av2;
     488     1264568 :     GEN v, w, L, z = i? mulii(*gl,W[i]): *gl;
     489     1264568 :     if (i) *gl = modii(mulii(*gl, Y1[i]), N);
     490     1264568 :     av2 = avma;
     491     1264568 :     L = modii(mulii(addui(1, mului(3, Fp_sqr(X1[i],N))), z), N);
     492     1264568 :     if (signe(L)) /* half of zero is still zero */
     493     1264568 :       L = shifti(mod2(L)? addii(L, N): L, -1);
     494     1264568 :     v = modii(subii(sqri(L), shifti(X1[i],1)), N);
     495     1264568 :     w = modii(subii(mulii(L, subii(X1[i], v)), Y1[i]), N);
     496     1264568 :     affii(v, X2[i]);
     497     1264568 :     affii(w, Y2[i]);
     498     1264568 :     set_avma(av2);
     499             :   }
     500       43951 :   return gc_int(av,0);
     501             : }
     502             : 
     503             : /* Parallel multiplication by an odd prime k on nbc curves, storing the
     504             :  * result to locations at and following *X2. Safe to be called with X2 = X1.
     505             :  * Return values as ecm_elladd. Uses (a simplified variant of) Montgomery's
     506             :  * PRAC algorithm; see ftp://ftp.cwi.nl/pub/pmontgom/Lucas.ps.gz .
     507             :  * With thanks to Paul Zimmermann for the reference.  --GN1998Aug13 */
     508             : static int
     509      221719 : get_rule(ulong d, ulong e)
     510             : {
     511      221719 :   if (d <= e + (e>>2)) /* floor(1.25*e) */
     512             :   {
     513       17631 :     if ((d+e)%3 == 0) return 0; /* rule 1 */
     514       10551 :     if ((d-e)%6 == 0) return 1;  /* rule 2 */
     515             :   }
     516             :   /* d <= 4*e but no ofl */
     517      214585 :   if ((d+3)>>2 <= e) return 2; /* rule 3, common case */
     518       12813 :   if ((d&1)==(e&1))  return 1; /* rule 4 = rule 2 */
     519        6631 :   if (!(d&1))        return 3; /* rule 5 */
     520        1846 :   if (d%3 == 0)      return 4; /* rule 6 */
     521         424 :   if ((d+e)%3 == 0)  return 5; /* rule 7 */
     522           0 :   if ((d-e)%3 == 0)  return 6; /* rule 8 */
     523             :   /* when we get here, e is even, otherwise one of rules 4,5 would apply */
     524           0 :   return 7; /* rule 9 */
     525             : }
     526             : 
     527             : /* PRAC implementation notes - main changes against the paper version:
     528             :  * (1) The general function [m+n]P = f([m]P,[n]P,[m-n]P) collapses (for m!=n)
     529             :  * to an ecm_elladd() which does not depend on the third argument; thus
     530             :  * references to the third variable (C in the paper) can be eliminated.
     531             :  * (2) Since our multipliers are prime, the outer loop of the paper
     532             :  * version executes only once, and thus is invisible above.
     533             :  * (3) The first step in the inner loop of the paper version will always be
     534             :  * rule 3, but the addition requested by this rule amounts to a doubling, and
     535             :  * will always be followed by a swap, so we have unrolled this first iteration.
     536             :  * (4) Simplifications in rules 6 and 7 are possible given the above, and we
     537             :  * save one addition in each of the two cases.  NB none of the other
     538             :  * ecm_elladd()s in the loop can ever degenerate into an elldouble.
     539             :  * (5) I tried to optimize for rule 3, which is used more frequently than all
     540             :  * others together, but it didn't improve things, so I removed the nested
     541             :  * tight loop again.  --GN */
     542             : /* The main loop body of ellfacteur() runs _slower_ under PRAC than under a
     543             :  * straightforward left-shift binary multiplication when N has <30 digits and
     544             :  * B1 is small;  PRAC wins when N and B1 get larger.  Weird. --GN */
     545             : /* k>2 assumed prime, XAUX = scratchpad */
     546             : static int
     547       28240 : ellmult(GEN N, GEN *gl, long nbc, ulong k, GEN *X1, GEN *X2, GEN *XAUX)
     548             : {
     549             :   ulong r, d, e, e1;
     550             :   int res;
     551       28240 :   GEN *A = X2, *B = XAUX, *T = XAUX + 2*nbc;
     552             : 
     553       28240 :   ZV_aff(2*nbc,X1,XAUX);
     554             :   /* first doubling picks up X1;  after this we'll be working in XAUX and
     555             :    * X2 only, mostly via A and B and T */
     556       28240 :   if ((res = elldouble(N, gl, nbc, X1, X2)) != 0) return res;
     557             : 
     558             :   /* split the work at the golden ratio */
     559       28240 :   r = (ulong)(k*0.61803398875 + .5);
     560       28240 :   d = k - r;
     561       28240 :   e = r - d; /* d+e == r, so no danger of ofl below */
     562      249763 :   while (d != e)
     563             :   { /* apply one of the nine transformations from PM's Table 4. */
     564      221719 :     switch(get_rule(d,e))
     565             :     {
     566        7080 :     case 0: /* rule 1 */
     567        7080 :       if ( (res = ecm_elladd(N, gl, nbc, A, B, T)) ) return res;
     568        7066 :       if ( (res = ecm_elladd2(N, gl, nbc, T, A, A, T, B, B)) != 0) return res;
     569        7052 :       e1 = d - e; d = (d + e1)/3; e = (e - e1)/3; break;
     570        6236 :     case 1: /* rules 2 and 4 */
     571        6236 :       if ( (res = ecm_elladd(N, gl, nbc, A, B, B)) ) return res;
     572        6215 :       if ( (res = elldouble(N, gl, nbc, A, A)) ) return res;
     573        6215 :       d = (d-e)>>1; break;
     574        4785 :     case 3: /* rule 5 */
     575        4785 :       if ( (res = elldouble(N, gl, nbc, A, A)) ) return res;
     576        4785 :       d >>= 1; break;
     577        1422 :     case 4: /* rule 6 */
     578        1422 :       if ( (res = elldouble(N, gl, nbc, A, T)) ) return res;
     579        1422 :       if ( (res = ecm_elladd(N, gl, nbc, T, A, A)) ) return res;
     580        1422 :       if ( (res = ecm_elladd(N, gl, nbc, A, B, B)) ) return res;
     581        1422 :       d = d/3 - e; break;
     582      201772 :     case 2: /* rule 3 */
     583      201772 :       if ( (res = ecm_elladd(N, gl, nbc, A, B, B)) ) return res;
     584      201625 :       d -= e; break;
     585         424 :     case 5: /* rule 7 */
     586         424 :       if ( (res = elldouble(N, gl, nbc, A, T)) ) return res;
     587         424 :       if ( (res = ecm_elladd2(N, gl, nbc, T, A, A, T, B, B)) != 0) return res;
     588         424 :       d = (d - 2*e)/3; break;
     589           0 :     case 6: /* rule 8 */
     590           0 :       if ( (res = ecm_elladd(N, gl, nbc, A, B, B)) ) return res;
     591           0 :       if ( (res = elldouble(N, gl, nbc, A, T)) ) return res;
     592           0 :       if ( (res = ecm_elladd(N, gl, nbc, T, A, A)) ) return res;
     593           0 :       d = (d - e)/3; break;
     594           0 :     case 7: /* rule 9 */
     595           0 :       if ( (res = elldouble(N, gl, nbc, B, B)) ) return res;
     596           0 :       e >>= 1; break;
     597             :     }
     598             :     /* swap d <-> e and A <-> B if necessary */
     599      221523 :     if (d < e) { lswap(d,e); pswap(A,B); }
     600             :   }
     601       28044 :   return ecm_elladd(N, gl, nbc, XAUX, X2, X2);
     602             : }
     603             : 
     604             : struct ECM {
     605             :   pari_timer T;
     606             :   long nbc, nbc2, seed;
     607             :   GEN *X, *XAUX, *XT, *XD, *XB, *XB2, *XH, *Xh, *Yh;
     608             : };
     609             : 
     610             : /* memory layout in ellfacteur():  a large array of GEN pointers, and one
     611             :  * huge chunk of memory containing all the actual GEN (t_INT) objects.
     612             :  * nbc is constant throughout the invocation:
     613             :  * - The B1 stage of each iteration through the main loop needs little
     614             :  * space:  enough for the X and Y coordinates of the current points,
     615             :  * and twice as much again as scratchpad for ellmult().
     616             :  * - The B2 stage, starting from some current set of points Q, needs, in
     617             :  * succession:
     618             :  *   + space for [2]Q, [4]Q, ..., [10]Q, and [p]Q for building the helix;
     619             :  *   + space for 48*nbc X and Y coordinates to hold the helix.  This could
     620             :  *   re-use [2]Q,...,[8]Q, but only with difficulty, since we don't
     621             :  *   know in advance which residue class mod 210 our p is going to be in.
     622             :  *   It can and should re-use [p]Q, though;
     623             :  *   + space for (temporarily [30]Q and then) [210]Q, [420]Q, and several
     624             :  *   further doublings until the giant step multiplier is reached.  This
     625             :  *   can re-use the remaining cells from above.  The computation of [210]Q
     626             :  *   will have been the last call to ellmult() within this iteration of the
     627             :  *   main loop, so the scratchpad is now also free to be re-used. We also
     628             :  *   compute [630]Q by a parallel addition;  we'll need it later to get the
     629             :  *   baby-step table bootstrapped a little faster.
     630             :  *   + Finally, for no more than 4 curves at a time, room for up to 1024 X
     631             :  *   coordinates only: the Y coordinates needed whilst setting up this baby
     632             :  *   step table are temporarily stored in the upper half, and overwritten
     633             :  *   during the last series of additions.
     634             :  *
     635             :  * Graphically:  after end of B1 stage (X,Y are the coords of Q):
     636             :  * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--
     637             :  * | X Y |  scratch  | [2]Q| [4]Q| [6]Q| [8]Q|[10]Q|    ...    | ...
     638             :  * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--
     639             :  * *X    *XAUX *XT   *XD                                       *XB
     640             :  *
     641             :  * [30]Q is computed from [10]Q.  [210]Q can go into XY, etc:
     642             :  * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--
     643             :  * |[210]|[420]|[630]|[840]|[1680,3360,6720,...,2048*210]      |bstp table...
     644             :  * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--
     645             :  * *X    *XAUX *XT   *XD      [*XG, somewhere here]            *XB .... *XH
     646             :  *
     647             :  * So we need (13 + 48) * 2 * nbc slots here + 4096 slots for the baby step
     648             :  * table (not all of which will be used when we start with a small B1, but
     649             :  * better to allocate and initialize ahead of time all the slots that might
     650             :  * be needed later).
     651             :  *
     652             :  * Note on memory locality:  During the B2 phase, accesses to the helix
     653             :  * (once it is set up) will be clustered by curves (4 out of nbc at a time).
     654             :  * Accesses to the baby steps table will wander from one end of the array to
     655             :  * the other and back, one such cycle per giant step, and during a full cycle
     656             :  * we would expect on the order of 2E4 accesses when using the largest giant
     657             :  * step size.  Thus we shouldn't be doing too bad with respect to thrashing
     658             :  * a 512KBy L2 cache.  However, we don't want the baby step table to grow
     659             :  * larger than this, even if it would reduce the number of EC operations by a
     660             :  * few more per cent for very large B2, lest cache thrashing slow down
     661             :  * everything disproportionally. --GN */
     662             : /* Auxiliary routines need < (3*nbc+240)*lN words on the PARI stack, in
     663             :  * addition to the spc*(lN+1) words occupied by our main table. */
     664             : static void
     665          78 : ECM_alloc(struct ECM *E, long lN)
     666             : {
     667          78 :   const long bstpmax = 1024; /* max number of baby step table entries */
     668          78 :   long spc = (13 + 48) * E->nbc2 + bstpmax * 4;
     669          78 :   long len = spc + 385 + spc*lN;
     670          78 :   long i, tw = evallg(lN) | evaltyp(t_INT);
     671          78 :   GEN w, *X = (GEN*)new_chunk(len);
     672             :   /* hack for X[i] = cgeti(lN). X = current point in B1 phase */
     673          78 :   w = (GEN)(X + spc + 385);
     674      483534 :   for (i = spc-1; i >= 0; i--) { X[i] = w; *w = tw; w += lN; }
     675          78 :   E->X = X;
     676          78 :   E->XAUX = E->X    + E->nbc2; /* scratchpad for ellmult() */
     677          78 :   E->XT   = E->XAUX + E->nbc2; /* ditto, will later hold [3*210]Q */
     678          78 :   E->XD   = E->XT   + E->nbc2; /* room for various multiples */
     679          78 :   E->XB   = E->XD   + 10*E->nbc2; /* start of baby steps table */
     680          78 :   E->XB2  = E->XB   + 2 * bstpmax; /* middle of baby steps table */
     681          78 :   E->XH   = E->XB2  + 2 * bstpmax; /* end of bstps table, start of helix */
     682          78 :   E->Xh   = E->XH   + 48*E->nbc2; /* little helix, X coords */
     683          78 :   E->Yh   = E->XH   + 192;     /* ditto, Y coords */
     684             :   /* XG,YG set inside the main loop, since they depend on B2 */
     685             :   /* E.Xh range of 384 pointers not set; these will later duplicate the pointers
     686             :    * in the E.XH range, 4 curves at a time. Some of the cells reserved here for
     687             :    * the E.XB range will never be used, instead, we'll warp the pointers to
     688             :    * connect to (read-only) GENs in the X/E.XD range */
     689          78 : }
     690             : /* N.B. E->seed is not initialized here */
     691             : static void
     692          78 : ECM_init(struct ECM *E, GEN N, long nbc)
     693             : {
     694          78 :   if (nbc < 0)
     695             :   { /* choose a sensible default */
     696          64 :     const long size = expi(N) + 1;
     697          64 :     nbc = ((size >> 3) << 2) - 80;
     698          64 :     if (nbc < 8) nbc = 8;
     699             :   }
     700          78 :   if (nbc > nbcmax) nbc = nbcmax;
     701          78 :   E->nbc = nbc;
     702          78 :   E->nbc2 = nbc << 1;
     703          78 :   ECM_alloc(E, lgefint(N));
     704          78 : }
     705             : 
     706             : static GEN
     707         128 : ECM_loop(struct ECM *E, GEN N, ulong B1)
     708             : {
     709         128 :   const ulong B2 = 110 * B1, B2_rt = usqrt(B2);
     710         128 :   const ulong nbc = E->nbc, nbc2 = E->nbc2;
     711             :   pari_sp av1, avtmp;
     712         128 :   byteptr d0, d = diffptr;
     713             :   long i, gse, gss, bstp, bstp0, rcn0, rcn;
     714             :   ulong B2_p, m, p, p0;
     715             :   GEN g, *XG, *YG;
     716         128 :   GEN *X = E->X, *XAUX = E->XAUX, *XT = E->XT, *XD = E->XD;
     717         128 :   GEN *XB = E->XB, *XB2 = E->XB2, *XH = E->XH, *Xh = E->Xh, *Yh = E->Yh;
     718             :   /* pick curves */
     719        5056 :   for (i = nbc2; i--; ) affui(E->seed++, X[i]);
     720             :   /* pick giant step exponent and size */
     721         128 :   gse = B1 < 656
     722             :           ? (B1 < 200? 5: 6)
     723         128 :           : (B1 < 10500
     724             :             ? (B1 < 2625? 7: 8)
     725             :             : (B1 < 42000? 9: 10));
     726         128 :   gss = 1UL << gse;
     727             :   /* With 32 baby steps, a giant step corresponds to 32*420 = 13440,
     728             :    * appropriate for the smallest B2s. With 1024, a giant step will be 430080;
     729             :    * appropriate for B1 >~ 42000, where 512 baby steps would imply roughly
     730             :    * the same number of curve additions. */
     731         128 :   XG = XT + gse*nbc2; /* will later hold [2^(gse+1)*210]Q */
     732         128 :   YG = XG + nbc;
     733             : 
     734         128 :   if (DEBUGLEVEL >= 4) {
     735           0 :     err_printf("ECM: time = %6ld ms\nECM: B1 = %4lu,", timer_delay(&E->T), B1);
     736           0 :     err_printf("\tB2 = %6lu,\tgss = %4ld*420\n", B2, gss);
     737             :   }
     738         128 :   p = 0;
     739         128 :   NEXT_PRIME_VIADIFF(p,d);
     740             : 
     741             :   /* ---B1 PHASE--- */
     742             :   /* treat p=2 separately */
     743         128 :   B2_p = B2 >> 1;
     744        2107 :   for (m=1; m<=B2_p; m<<=1)
     745             :   {
     746        1979 :     int fl = elldouble(N, &g, nbc, X, X);
     747        1979 :     if (fl > 1) return g; else if (fl) break;
     748             :   }
     749         128 :   rcn = NPRC; /* multipliers begin at the beginning */
     750             :   /* p=3,...,nextprime(B1) */
     751        7469 :   while (p < B1 && p <= B2_rt)
     752             :   {
     753        7355 :     pari_sp av2 = avma;
     754        7355 :     p = snextpr(p, &d, &rcn, NULL, uisprime);
     755        7355 :     B2_p = B2/p; /* beware integer overflow on 32-bit CPUs */
     756       24912 :     for (m=1; m<=B2_p; m*=p)
     757             :     {
     758       17739 :       int fl = ellmult(N, &g, nbc, p, X, X, XAUX);
     759       17739 :       if (fl > 1) return g; else if (fl) break;
     760       17557 :       set_avma(av2);
     761             :     }
     762        7341 :     set_avma(av2);
     763             :   }
     764             :   /* primes p larger than sqrt(B2) appear only to the 1st power */
     765       10309 :   while (p < B1)
     766             :   {
     767       10213 :     pari_sp av2 = avma;
     768       10213 :     p = snextpr(p, &d, &rcn, NULL, uisprime);
     769       10213 :     if (ellmult(N, &g, nbc, p, X, X, XAUX) > 1) return g;
     770       10195 :     set_avma(av2);
     771             :   }
     772          96 :   if (DEBUGLEVEL >= 4) {
     773           0 :     err_printf("ECM: time = %6ld ms, B1 phase done, ", timer_delay(&E->T));
     774           0 :     err_printf("p = %lu, setting up for B2\n", p);
     775             :   }
     776             : 
     777             :   /* ---B2 PHASE--- */
     778             :   /* compute [2]Q,...,[10]Q, needed to build the helix */
     779          96 :   if (elldouble(N, &g, nbc, X, XD) > 1) return g; /*[2]Q*/
     780          96 :   if (elldouble(N, &g, nbc, XD, XD + nbc2) > 1) return g; /*[4]Q*/
     781          96 :   if (ecm_elladd(N, &g, nbc,
     782          96 :         XD, XD + nbc2, XD + (nbc<<2)) > 1) return g; /* [6]Q */
     783          96 :   if (ecm_elladd2(N, &g, nbc,
     784             :         XD, XD + (nbc<<2), XT + (nbc<<3),
     785          96 :         XD + nbc2, XD + (nbc<<2), XD + (nbc<<3)) > 1)
     786           0 :     return g; /* [8]Q and [10]Q */
     787          96 :   if (DEBUGLEVEL >= 7) err_printf("\t(got [2]Q...[10]Q)\n");
     788             : 
     789             :   /* get next prime (still using the foolproof test) */
     790          96 :   p = snextpr(p, &d, &rcn, NULL, uisprime);
     791             :   /* make sure we have the residue class number (mod 210) */
     792          96 :   if (rcn == NPRC)
     793             :   {
     794          96 :     rcn = prc210_no[(p % 210) >> 1];
     795          96 :     if (rcn == NPRC)
     796             :     {
     797           0 :       err_printf("ECM: %lu should have been prime but isn\'t\n", p);
     798           0 :       pari_err_BUG("ellfacteur");
     799             :     }
     800             :   }
     801             : 
     802             :   /* compute [p]Q and put it into its place in the helix */
     803          96 :   if (ellmult(N, &g, nbc, p, X, XH + rcn*nbc2, XAUX) > 1)
     804           0 :     return g;
     805          96 :   if (DEBUGLEVEL >= 7)
     806           0 :     err_printf("\t(got [p]Q, p = %lu = prc210_rp[%ld] mod 210)\n", p, rcn);
     807             : 
     808             :   /* save current p, d, and rcn;  we'll need them more than once below */
     809          96 :   p0 = p;
     810          96 :   d0 = d;
     811          96 :   rcn0 = rcn; /* remember where the helix wraps */
     812          96 :   bstp0 = 0; /* p is at baby-step offset 0 from itself */
     813             : 
     814             :   /* fill up the helix, stepping forward through the prime residue classes
     815             :    * mod 210 until we're back at the r'class of p0.  Keep updating p so
     816             :    * that we can print meaningful diagnostics if a factor shows up; don't
     817             :    * bother checking which of these p's are in fact prime */
     818        4608 :   for (i = 47; i; i--) /* 47 iterations */
     819             :   {
     820        4512 :     ulong dp = (ulong)prc210_d1[rcn];
     821        4512 :     p += dp;
     822        4512 :     if (rcn == 47)
     823             :     { /* wrap mod 210 */
     824          96 :       if (ecm_elladd(N, &g, nbc, XT+dp*nbc, XH+rcn*nbc2, XH) > 1) return g;
     825          96 :       rcn = 0; continue;
     826             :     }
     827        4416 :     if (ecm_elladd(N, &g, nbc, XT+dp*nbc, XH+rcn*nbc2, XH+rcn*nbc2+nbc2) > 1)
     828           0 :       return g;
     829        4416 :     rcn++;
     830             :   }
     831          96 :   if (DEBUGLEVEL >= 7) err_printf("\t(got initial helix)\n");
     832             :   /* compute [210]Q etc, needed for the baby step table */
     833          96 :   if (ellmult(N, &g, nbc, 3, XD + (nbc<<3), X, XAUX) > 1) return g;
     834          96 :   if (ellmult(N, &g, nbc, 7, X, X, XAUX) > 1) return g; /* [210]Q */
     835             :   /* this was the last call to ellmult() in the main loop body; may now
     836             :    * overwrite XAUX and slots XD and following */
     837          96 :   if (elldouble(N, &g, nbc, X, XAUX) > 1) return g; /* [420]Q */
     838          96 :   if (ecm_elladd(N, &g, nbc, X, XAUX, XT) > 1) return g;/*[630]Q*/
     839          96 :   if (ecm_elladd(N, &g, nbc, X, XT, XD) > 1) return g;  /*[840]Q*/
     840         694 :   for (i=1; i <= gse; i++)
     841         598 :     if (elldouble(N, &g, nbc, XT + i*nbc2, XD + i*nbc2) > 1) return g;
     842             :   /* (the last iteration has initialized XG to [210*2^(gse+1)]Q) */
     843             : 
     844          96 :   if (DEBUGLEVEL >= 4)
     845           0 :     err_printf("ECM: time = %6ld ms, entering B2 phase, p = %lu\n",
     846             :                timer_delay(&E->T), p);
     847             : 
     848         454 :   for (i = nbc - 4; i >= 0; i -= 4)
     849             :   { /* loop over small sets of 4 curves at a time */
     850             :     GEN *Xb;
     851             :     long j, k;
     852         365 :     if (DEBUGLEVEL >= 6)
     853           0 :       err_printf("ECM: finishing curves %ld...%ld\n", i, i+3);
     854             :     /* Copy relevant pointers from XH to Xh. Memory layout in XH:
     855             :      * nbc X coordinates, nbc Y coordinates for residue class
     856             :      * 1 mod 210, then the same for r.c. 11 mod 210, etc. Memory layout for
     857             :      * Xh is: four X coords for 1 mod 210, four for 11 mod 210, ..., four
     858             :      * for 209 mod 210, then the corresponding Y coordinates in the same
     859             :      * order. This allows a giant step on Xh using just three calls to
     860             :      * ecm_elladd0() each acting on 64 points in parallel */
     861       17885 :     for (j = 48; j--; )
     862             :     {
     863       17520 :       k = nbc2*j + i;
     864       17520 :       m = j << 2; /* X coordinates */
     865       17520 :       Xh[m]   = XH[k];   Xh[m+1] = XH[k+1];
     866       17520 :       Xh[m+2] = XH[k+2]; Xh[m+3] = XH[k+3];
     867       17520 :       k += nbc; /* Y coordinates */
     868       17520 :       Yh[m]   = XH[k];   Yh[m+1] = XH[k+1];
     869       17520 :       Yh[m+2] = XH[k+2]; Yh[m+3] = XH[k+3];
     870             :     }
     871             :     /* Build baby step table of X coords of multiples of [210]Q.  XB[4*j]
     872             :      * will point at X coords on four curves from [(j+1)*210]Q.  Until
     873             :      * we're done, we need some Y coords as well, which we keep in the
     874             :      * second half of the table, overwriting them at the end when gse=10.
     875             :      * Multiples which we already have  (by 1,2,3,4,8,16,...,2^gse) are
     876             :      * entered simply by copying the pointers, ignoring the few slots in w
     877             :      * that were initially reserved for them. Here are the initial entries */
     878        1095 :     for (Xb=XB,k=2,j=i; k--; Xb=XB2,j+=nbc) /* first X, then Y coords */
     879             :     {
     880         730 :       Xb[0]  = X[j];      Xb[1]  = X[j+1]; /* [210]Q */
     881         730 :       Xb[2]  = X[j+2];    Xb[3]  = X[j+3];
     882         730 :       Xb[4]  = XAUX[j];   Xb[5]  = XAUX[j+1]; /* [420]Q */
     883         730 :       Xb[6]  = XAUX[j+2]; Xb[7]  = XAUX[j+3];
     884         730 :       Xb[8]  = XT[j];     Xb[9]  = XT[j+1]; /* [630]Q */
     885         730 :       Xb[10] = XT[j+2];   Xb[11] = XT[j+3];
     886         730 :       Xb += 4; /* points at [420]Q */
     887             :       /* ... entries at powers of 2 times 210 .... */
     888        4463 :       for (m = 2; m < (ulong)gse+k; m++) /* omit Y coords of [2^gse*210]Q */
     889             :       {
     890        3733 :         long m2 = m*nbc2 + j;
     891        3733 :         Xb += (2UL<<m); /* points at [2^m*210]Q */
     892        3733 :         Xb[0] = XAUX[m2];   Xb[1] = XAUX[m2+1];
     893        3733 :         Xb[2] = XAUX[m2+2]; Xb[3] = XAUX[m2+3];
     894             :       }
     895             :     }
     896         365 :     if (DEBUGLEVEL >= 7)
     897           0 :       err_printf("\t(extracted precomputed helix / baby step entries)\n");
     898             :     /* ... glue in between, up to 16*210 ... */
     899         365 :     if (ecm_elladd0(N, &g, 12, 4, /* 12 pts + (4 pts replicated thrice) */
     900             :           XB + 12, XB2 + 12,
     901             :           XB,      XB2,
     902           0 :           XB + 16, XB2 + 16) > 1) return g; /*4+{1,2,3} = {5,6,7}*/
     903         365 :     if (ecm_elladd0(N, &g, 28, 4, /* 28 pts + (4 pts replicated 7fold) */
     904             :           XB + 28, XB2 + 28,
     905             :           XB,      XB2,
     906           0 :           XB + 32, XB2 + 32) > 1) return g;/*8+{1...7} = {9...15}*/
     907             :     /* ... and the remainder of the lot */
     908        1319 :     for (m = 5; m <= (ulong)gse; m++)
     909             :     { /* fill in from 2^(m-1)+1 to 2^m-1 in chunks of 64 and 60 points */
     910         954 :       ulong m2 = 2UL << m; /* will point at 2^(m-1)+1 */
     911        2047 :       for (j = 0; (ulong)j < m2-64; j+=64) /* executed 0 times when m = 5 */
     912             :       {
     913        1934 :         if (ecm_elladd0(N, &g, 64, 4,
     914        2172 :               XB + m2-4, XB2 + m2-4,
     915        2186 :               XB + j,    XB2 + j,
     916        1934 :               XB + m2+j, (m<(ulong)gse? XB2+m2+j: NULL)) > 1)
     917           0 :           return g;
     918             :       } /* j = m2-64 here, 60 points left */
     919        1319 :       if (ecm_elladd0(N, &g, 60, 4,
     920        1872 :             XB + m2-4, XB2 + m2-4,
     921        1908 :             XB + j,    XB2 + j,
     922        1319 :             XB + m2+j, (m<(ulong)gse? XB2+m2+j: NULL)) > 1)
     923           0 :         return g;
     924             :       /* when m=gse, drop Y coords of result, and when both equal 1024,
     925             :        * overwrite Y coords of second argument with X coords of result */
     926             :     }
     927         365 :     if (DEBUGLEVEL >= 7) err_printf("\t(baby step table complete)\n");
     928             :     /* initialize a few other things */
     929         365 :     bstp = bstp0;
     930         365 :     p = p0; d = d0; rcn = rcn0;
     931         365 :     g = gen_1; av1 = avma;
     932             :     /* scratchspace for prod (x_i-x_j) */
     933         365 :     avtmp = (pari_sp)new_chunk(8 * lgefint(N));
     934             :     /* The correct entry in XB to use depends on bstp and on where we are
     935             :      * on the helix. As we skip from prime to prime, bstp is incremented
     936             :      * by snextpr each time we wrap around through residue class number 0
     937             :      * (1 mod 210), but the baby step should not be taken until rcn>=rcn0,
     938             :      * i.e. until we pass again the residue class of p0.
     939             :      *
     940             :      * The correct signed multiplier is thus k = bstp - (rcn < rcn0),
     941             :      * and the offset from XB is four times (|k| - 1).  When k=0, we ignore
     942             :      * the current prime: if it had led to a factorization, this
     943             :      * would have been noted during the last giant step, or -- when we
     944             :      * first get here -- whilst initializing the helix.  When k > gss,
     945             :      * we must do a giant step and bump bstp back by -2*gss.
     946             :      *
     947             :      * The gcd of the product of X coord differences against N is taken just
     948             :      * before we do a giant step. */
     949     4642230 :     while (p < B2)
     950             :     {/* loop over probable primes p0 < p <= nextprime(B2), inserting giant
     951             :       * steps as necessary */
     952     4641872 :       p = snextpr(p, &d, &rcn, &bstp, uis2psp); /* next probable prime */
     953             :       /* work out the corresponding baby-step multiplier */
     954     4641872 :       k = bstp - (rcn < rcn0 ? 1 : 0);
     955     4641872 :       if (k > gss)
     956             :       { /* giant-step time, take gcd */
     957        1170 :         g = gcdii(g, N);
     958        1170 :         if (!is_pm1(g) && !equalii(g, N)) return g;
     959        1163 :         g = gen_1; set_avma(av1);
     960        2326 :         while (k > gss)
     961             :         { /* giant step */
     962        1163 :           if (DEBUGLEVEL >= 7) err_printf("\t(giant step at p = %lu)\n", p);
     963        1163 :           if (ecm_elladd0(N, &g, 64, 4, XG + i, YG + i,
     964           0 :                 Xh, Yh, Xh, Yh) > 1) return g;
     965        1163 :           if (ecm_elladd0(N, &g, 64, 4, XG + i, YG + i,
     966             :                 Xh + 64, Yh + 64, Xh + 64, Yh + 64) > 1)
     967           0 :             return g;
     968        1163 :           if (ecm_elladd0(N, &g, 64, 4, XG + i, YG + i,
     969             :                 Xh + 128, Yh + 128, Xh + 128, Yh + 128) > 1)
     970           0 :             return g;
     971        1163 :           bstp -= (gss << 1);
     972        1163 :           k = bstp - (rcn < rcn0? 1: 0); /* recompute multiplier */
     973             :         }
     974             :       }
     975     4641865 :       if (!k) continue; /* point of interest is already in Xh */
     976     4614456 :       if (k < 0) k = -k;
     977     4614456 :       m = ((ulong)k - 1) << 2;
     978             :       /* accumulate product of differences of X coordinates */
     979     4614456 :       j = rcn<<2;
     980     4614456 :       avma = avtmp; /* go to garbage zone; don't use set_avma */
     981     4614456 :       g = modii(mulii(g, subii(XB[m],   Xh[j])), N);
     982     4614456 :       g = modii(mulii(g, subii(XB[m+1], Xh[j+1])), N);
     983     4614456 :       g = modii(mulii(g, subii(XB[m+2], Xh[j+2])), N);
     984     4614456 :       g = mulii(g, subii(XB[m+3], Xh[j+3]));
     985     4614456 :       set_avma(av1);
     986     4614456 :       g = modii(g, N);
     987             :     }
     988         358 :     set_avma(av1);
     989             :   }
     990          89 :   return NULL;
     991             : }
     992             : 
     993             : /* ellfacteur() tuned to be useful as a first stage before MPQS, especially for
     994             :  * large arguments, when 'insist' is false, and now also for the case when
     995             :  * 'insist' is true, vaguely following suggestions by Paul Zimmermann
     996             :  * (http://www.loria.fr/~zimmerma/records/ecmnet.html). --GN 1998Jul,Aug */
     997             : static GEN
     998        1098 : ellfacteur(GEN N, int insist)
     999             : {
    1000        1098 :   const long size = expi(N) + 1;
    1001        1098 :   pari_sp av = avma;
    1002             :   struct ECM E;
    1003        1098 :   long nbc, dsn, dsnmax, rep = 0;
    1004        1098 :   if (insist)
    1005             :   {
    1006          14 :     const long DSNMAX = numberof(TB1)-1;
    1007          14 :     dsnmax = (size >> 2) - 10;
    1008          14 :     if (dsnmax < 0) dsnmax = 0;
    1009           0 :     else if (dsnmax > DSNMAX) dsnmax = DSNMAX;
    1010          14 :     E.seed = 1 + (nbcmax<<7)*(size&0xffff); /* seed for choice of curves */
    1011             : 
    1012          14 :     dsn = (size >> 3) - 5;
    1013          14 :     if (dsn < 0) dsn = 0; else if (dsn > 47) dsn = 47;
    1014             :     /* pick up the torch where noninsistent stage would have given up */
    1015          14 :     nbc = dsn + (dsn >> 2) + 9; /* 8 or more curves in parallel */
    1016          14 :     nbc &= ~3; /* 4 | nbc */
    1017             :   }
    1018             :   else
    1019             :   {
    1020        1084 :     dsn = (size - 140) >> 3;
    1021        1084 :     if (dsn < 0)
    1022             :     {
    1023             : #ifndef __EMX__ /* unless DOS/EMX: MPQS's disk access is abysmally slow */
    1024        1020 :       if (DEBUGLEVEL >= 4)
    1025           0 :         err_printf("ECM: number too small to justify this stage\n");
    1026        1020 :       return NULL; /* too small, decline the task */
    1027             : #endif
    1028             :       dsn = 0;
    1029          64 :     } else if (dsn > 12) dsn = 12;
    1030          64 :     rep = (size <= 248 ?
    1031          64 :            (size <= 176 ? (size - 124) >> 4 : (size - 148) >> 3) :
    1032          18 :            (size - 224) >> 1);
    1033             : #ifdef __EMX__ /* DOS/EMX: extra rounds (shun MPQS) */
    1034             :     rep += 20;
    1035             : #endif
    1036          64 :     dsnmax = 72;
    1037             :     /* Use disjoint sets of curves for non-insist and insist phases; moreover,
    1038             :      * repeated calls acting on factors of the same original number should try
    1039             :      * to use fresh curves. The following achieves this */
    1040          64 :     E.seed = 1 + (nbcmax<<3)*(size & 0xf);
    1041          64 :     nbc = -1;
    1042             :   }
    1043          78 :   ECM_init(&E, N, nbc);
    1044          78 :   if (DEBUGLEVEL >= 4)
    1045             :   {
    1046           0 :     timer_start(&E.T);
    1047           0 :     err_printf("ECM: working on %ld curves at a time; initializing", E.nbc);
    1048           0 :     if (!insist)
    1049             :     {
    1050           0 :       if (rep == 1) err_printf(" for one round");
    1051           0 :       else          err_printf(" for up to %ld rounds", rep);
    1052             :     }
    1053           0 :     err_printf("...\n");
    1054             :   }
    1055          78 :   if (dsn > dsnmax) dsn = dsnmax;
    1056             :   for(;;)
    1057          50 :   {
    1058         128 :     ulong B1 = insist? TB1[dsn]: TB1_for_stage[dsn];
    1059         128 :     GEN g = ECM_loop(&E, N, B1);
    1060         128 :     if (g)
    1061             :     {
    1062          39 :       if (DEBUGLEVEL >= 4)
    1063           0 :         err_printf("ECM: time = %6ld ms\n\tfound factor = %Ps\n",
    1064             :                    timer_delay(&E.T), g);
    1065          39 :       return gerepilecopy(av, g);
    1066             :     }
    1067          89 :     if (dsn < dsnmax)
    1068             :     {
    1069          75 :       if (insist) dsn++;
    1070          75 :       else { dsn += 2; if (dsn > dsnmax) dsn = dsnmax; }
    1071             :     }
    1072          89 :     if (!insist && !--rep)
    1073             :     {
    1074          39 :       if (DEBUGLEVEL >= 4)
    1075           0 :         err_printf("ECM: time = %6ld ms,\tellfacteur giving up.\n",
    1076             :                    timer_delay(&E.T));
    1077          39 :       return gc_NULL(av);
    1078             :     }
    1079             :   }
    1080             : }
    1081             : /* assume rounds >= 1, seed >= 1, B1 <= ULONG_MAX / 110 */
    1082             : GEN
    1083           0 : Z_ECM(GEN N, long rounds, long seed, ulong B1)
    1084             : {
    1085           0 :   pari_sp av = avma;
    1086             :   struct ECM E;
    1087             :   long i;
    1088           0 :   E.seed = seed;
    1089           0 :   ECM_init(&E, N, -1);
    1090           0 :   if (DEBUGLEVEL >= 4) timer_start(&E.T);
    1091           0 :   for (i = rounds; i--; )
    1092             :   {
    1093           0 :     GEN g = ECM_loop(&E, N, B1);
    1094           0 :     if (g) return gerepilecopy(av, g);
    1095             :   }
    1096           0 :   return gc_NULL(av);
    1097             : }
    1098             : 
    1099             : /***********************************************************************/
    1100             : /**                                                                   **/
    1101             : /**                FACTORIZATION (Pollard-Brent rho) --GN1998Jun18-26 **/
    1102             : /**  pollardbrent() returns a nontrivial factor of n, assuming n is   **/
    1103             : /**  composite and has no small prime divisor, or NULL if going on    **/
    1104             : /**  would take more time than we want to spend.  Sometimes it finds  **/
    1105             : /**  more than one factor, and returns a structure suitable for       **/
    1106             : /**  interpretation by ifac_crack. (Cf Algo 8.5.2 in ACiCNT)          **/
    1107             : /**                                                                   **/
    1108             : /***********************************************************************/
    1109             : #define VALUE(x) gel(x,0)
    1110             : #define EXPON(x) gel(x,1)
    1111             : #define CLASS(x) gel(x,2)
    1112             : 
    1113             : INLINE void
    1114       56229 : INIT(GEN x, GEN v, GEN e, GEN c) {
    1115       56229 :   VALUE(x) = v;
    1116       56229 :   EXPON(x) = e;
    1117       56229 :   CLASS(x) = c;
    1118       56229 : }
    1119             : static void
    1120       49722 : ifac_delete(GEN x) { INIT(x,NULL,NULL,NULL); }
    1121             : 
    1122             : static void
    1123           0 : rho_dbg(pari_timer *T, long c, long msg_mask)
    1124             : {
    1125           0 :   if (c & msg_mask) return;
    1126           0 :   err_printf("Rho: time = %6ld ms,\t%3ld round%s\n",
    1127             :              timer_delay(T), c, (c==1?"":"s"));
    1128             : }
    1129             : 
    1130             : static void
    1131    33259276 : one_iter(GEN *x, GEN *P, GEN x1, GEN n, long delta)
    1132             : {
    1133    33259276 :   *x = addis(remii(sqri(*x), n), delta);
    1134    33207512 :   *P = modii(mulii(*P, subii(x1, *x)), n);
    1135    33258454 : }
    1136             : /* Return NULL when we run out of time, or a single t_INT containing a
    1137             :  * nontrivial factor of n, or a vector of t_INTs, each triple of successive
    1138             :  * entries containing a factor, an exponent (equal to one),  and a factor
    1139             :  * class (NULL for unknown or zero for known composite),  matching the
    1140             :  * internal representation used by the ifac_*() routines below. Repeated
    1141             :  * factors may arise; the caller will sort the factors anyway. Result
    1142             :  * is not gerepile-able (contains NULL) */
    1143             : static GEN
    1144        5433 : pollardbrent_i(GEN n, long size, long c0, long retries)
    1145             : {
    1146        5433 :   long tf = lgefint(n), delta, msg_mask, c, k, k1, l;
    1147             :   pari_sp av;
    1148             :   GEN x, x1, y, P, g, g1, res;
    1149             :   pari_timer T;
    1150             : 
    1151        5433 :   if (DEBUGLEVEL >= 4) timer_start(&T);
    1152        5433 :   c = c0 << 5; /* 2^5 iterations per round */
    1153       10866 :   msg_mask = (size >= 448? 0x1fff:
    1154        5433 :                            (size >= 192? (256L<<((size-128)>>6))-1: 0xff));
    1155        5433 :   y = cgeti(tf);
    1156        5433 :   x1= cgeti(tf);
    1157        5433 :   av = avma;
    1158             : 
    1159        5433 : PB_RETRY:
    1160             :  /* trick to make a 'random' choice determined by n.  Don't use x^2+0 or
    1161             :   * x^2-2, ever.  Don't use x^2-3 or x^2-7 with a starting value of 2.
    1162             :   * x^2+4, x^2+9 are affine conjugate to x^2+1, so don't use them either.
    1163             :   *
    1164             :   * (the point being that when we get called again on a composite cofactor
    1165             :   * of something we've already seen, we had better avoid the same delta) */
    1166        5433 :   switch ((size + retries) & 7)
    1167             :   {
    1168        1092 :     case 0:  delta=  1; break;
    1169         713 :     case 1:  delta= -1; break;
    1170         662 :     case 2:  delta=  3; break;
    1171         595 :     case 3:  delta=  5; break;
    1172         552 :     case 4:  delta= -5; break;
    1173         686 :     case 5:  delta=  7; break;
    1174         616 :     case 6:  delta= 11; break;
    1175             :     /* case 7: */
    1176         517 :     default: delta=-11; break;
    1177             :   }
    1178        5433 :   if (DEBUGLEVEL >= 4)
    1179             :   {
    1180           0 :     if (!retries)
    1181           0 :       err_printf("Rho: searching small factor of %ld-bit integer\n", size);
    1182             :     else
    1183           0 :       err_printf("Rho: restarting for remaining rounds...\n");
    1184           0 :     err_printf("Rho: using X^2%+1ld for up to %ld rounds of 32 iterations\n",
    1185             :                delta, c >> 5);
    1186             :   }
    1187        5433 :   x = gen_2; P = gen_1; g1 = NULL; k = 1; l = 1;
    1188        5433 :   affui(2, y);
    1189        5433 :   affui(2, x1);
    1190             :   for (;;) /* terminated under the control of c */
    1191             :   { /* use the polynomial  x^2 + delta */
    1192    15400481 :     one_iter(&x, &P, x1, n, delta);
    1193             : 
    1194    15402299 :     if ((--c & 0x1f)==0)
    1195             :     { /* one round complete */
    1196      476586 :       g = gcdii(n, P); if (!is_pm1(g)) goto fin;
    1197      474564 :       if (c <= 0)
    1198             :       { /* getting bored */
    1199        2243 :         if (DEBUGLEVEL >= 4)
    1200           0 :           err_printf("Rho: time = %6ld ms,\tPollard-Brent giving up.\n",
    1201             :                      timer_delay(&T));
    1202        2243 :         return NULL;
    1203             :       }
    1204      472321 :       P = gen_1;
    1205      472321 :       if (DEBUGLEVEL >= 4) rho_dbg(&T, c0-(c>>5), msg_mask);
    1206      472321 :       affii(x,y); x = y; set_avma(av);
    1207             :     }
    1208             : 
    1209    15396394 :     if (--k) continue; /* normal end of loop body */
    1210             : 
    1211       49694 :     if (c & 0x1f) /* otherwise, we already checked */
    1212             :     {
    1213       32598 :       g = gcdii(n, P); if (!is_pm1(g)) goto fin;
    1214       32577 :       P = gen_1;
    1215             :     }
    1216             : 
    1217             :    /* Fast forward phase, doing l inner iterations without computing gcds.
    1218             :     * Check first whether it would take us beyond the alloted time.
    1219             :     * Fast forward rounds count only half (although they're taking
    1220             :     * more like 2/3 the time of normal rounds).  This to counteract the
    1221             :     * nuisance that all c0 between 4096 and 6144 would act exactly as
    1222             :     * 4096;  with the halving trick only the range 4096..5120 collapses
    1223             :     * (similarly for all other powers of two) */
    1224       49673 :     if ((c -= (l>>1)) <= 0)
    1225             :     { /* got bored */
    1226        1170 :       if (DEBUGLEVEL >= 4)
    1227           0 :         err_printf("Rho: time = %6ld ms,\tPollard-Brent giving up.\n",
    1228             :                    timer_delay(&T));
    1229        1170 :       return NULL;
    1230             :     }
    1231       48503 :     c &= ~0x1f; /* keep it on multiples of 32 */
    1232             : 
    1233             :     /* Fast forward loop */
    1234       48503 :     affii(x, x1); set_avma(av); x = x1;
    1235       48503 :     k = l; l <<= 1;
    1236             :     /* don't show this for the first several (short) fast forward phases. */
    1237       48503 :     if (DEBUGLEVEL >= 4 && (l>>7) > msg_mask)
    1238           0 :       err_printf("Rho: fast forward phase (%ld rounds of 64)...\n", l>>7);
    1239    17930860 :     for (k1=k; k1; k1--)
    1240             :     {
    1241    17882647 :       one_iter(&x, &P, x1, n, delta);
    1242    17880902 :       if ((k1 & 0x1f) == 0) gerepileall(av, 2, &x, &P);
    1243             :     }
    1244       48213 :     if (DEBUGLEVEL >= 4 && (l>>7) > msg_mask)
    1245           0 :       err_printf("Rho: time = %6ld ms,\t%3ld rounds, back to normal mode\n",
    1246           0 :                  timer_delay(&T), c0-(c>>5));
    1247       48213 :     affii(x,y); P = gerepileuptoint(av, P); x = y;
    1248             :   } /* forever */
    1249             : 
    1250        2020 : fin:
    1251             :   /* An accumulated gcd was > 1 */
    1252        2020 :   if  (!equalii(g,n))
    1253             :   { /* if it isn't n, and looks prime, return it */
    1254        1894 :     if (MR_Jaeschke(g))
    1255             :     {
    1256        1894 :       if (DEBUGLEVEL >= 4)
    1257             :       {
    1258           0 :         rho_dbg(&T, c0-(c>>5), 0);
    1259           0 :         err_printf("\tfound factor = %Ps\n",g);
    1260             :       }
    1261        1894 :       return g;
    1262             :     }
    1263           0 :     set_avma(av); g1 = icopy(g);  /* known composite, keep it safe */
    1264           0 :     av = avma;
    1265             :   }
    1266         126 :   else g1 = n; /* and work modulo g1 for backtracking */
    1267             : 
    1268             :   /* Here g1 is known composite */
    1269         126 :   if (DEBUGLEVEL >= 4 && size > 192)
    1270           0 :     err_printf("Rho: hang on a second, we got something here...\n");
    1271         126 :   x = y;
    1272             :   for(;;)
    1273             :   { /* backtrack until period recovered. Must terminate */
    1274        9450 :     x = addis(remii(sqri(x), g1), delta);
    1275        9450 :     g = gcdii(subii(x1, x), g1); if (!is_pm1(g)) break;
    1276             : 
    1277        9324 :     if (DEBUGLEVEL >= 4 && (--c & 0x1f) == 0) rho_dbg(&T, c0-(c>>5), msg_mask);
    1278             :   }
    1279             : 
    1280         126 :   if (g1 == n || equalii(g,g1))
    1281             :   {
    1282         126 :     if (g1 == n && equalii(g,g1))
    1283             :     { /* out of luck */
    1284           0 :       if (DEBUGLEVEL >= 4)
    1285             :       {
    1286           0 :         rho_dbg(&T, c0-(c>>5), 0);
    1287           0 :         err_printf("\tPollard-Brent failed.\n");
    1288             :       }
    1289           0 :       if (++retries >= 4) pari_err_BUG("");
    1290           0 :       goto PB_RETRY;
    1291             :     }
    1292             :     /* half lucky: we've split n, but g1 equals either g or n */
    1293         126 :     if (DEBUGLEVEL >= 4)
    1294             :     {
    1295           0 :       rho_dbg(&T, c0-(c>>5), 0);
    1296           0 :       err_printf("\tfound %sfactor = %Ps\n", (g1!=n ? "composite " : ""), g);
    1297             :     }
    1298         126 :     res = cgetg(7, t_VEC);
    1299             :     /* g^1: known composite when g1!=n */
    1300         126 :     INIT(res+1, g, gen_1, (g1!=n? gen_0: NULL));
    1301             :     /* cofactor^1: status unknown */
    1302         126 :     INIT(res+4, diviiexact(n,g), gen_1, NULL);
    1303         126 :     return res;
    1304             :   }
    1305             :   /* g < g1 < n : our lucky day -- we've split g1, too */
    1306           0 :   res = cgetg(10, t_VEC);
    1307             :   /* unknown status for all three factors */
    1308           0 :   INIT(res+1, g,                gen_1, NULL);
    1309           0 :   INIT(res+4, diviiexact(g1,g), gen_1, NULL);
    1310           0 :   INIT(res+7, diviiexact(n,g1), gen_1, NULL);
    1311           0 :   if (DEBUGLEVEL >= 4)
    1312             :   {
    1313           0 :     rho_dbg(&T, c0-(c>>5), 0);
    1314           0 :     err_printf("\tfound factors = %Ps, %Ps,\n\tand %Ps\n",
    1315           0 :                gel(res,1), gel(res,4), gel(res,7));
    1316             :   }
    1317           0 :   return res;
    1318             : }
    1319             : /* Tuning parameter:  for input up to 64 bits long, we must not spend more
    1320             :  * than a very short time, for fear of slowing things down on average.
    1321             :  * With the current tuning formula, increase our efforts somewhat at 49 bit
    1322             :  * input (an extra round for each bit at first),  and go up more and more
    1323             :  * rapidly after we pass 80 bits.-- Changed this to adjust for the presence of
    1324             :  * squfof, which will finish input up to 59 bits quickly. */
    1325             : static GEN
    1326        5433 : pollardbrent(GEN n)
    1327             : {
    1328        5433 :   const long tune_pb_min = 14; /* even 15 seems too much. */
    1329        5433 :   long c0, size = expi(n) + 1;
    1330        5433 :   if (size <= 28)
    1331           0 :     c0 = 32;/* amounts very nearly to 'insist'. Now that we have squfof(), we
    1332             :              * don't insist any more when input is 2^29 ... 2^32 */
    1333        5433 :   else if (size <= 42)
    1334        1512 :     c0 = tune_pb_min;
    1335        3921 :   else if (size <= 59) /* match squfof() cutoff point */
    1336        2189 :     c0 = tune_pb_min + ((size - 42)<<1);
    1337        1732 :   else if (size <= 72)
    1338         810 :     c0 = tune_pb_min + size - 24;
    1339         922 :   else if (size <= 301)
    1340             :     /* nonlinear increase in effort, kicking in around 80 bits */
    1341             :     /* 301 gives 48121 + tune_pb_min */
    1342        1816 :     c0 = tune_pb_min + size - 60 +
    1343         908 :       ((size-73)>>1)*((size-70)>>3)*((size-56)>>4);
    1344             :   else
    1345          14 :     c0 = 49152; /* ECM is faster when it'd take longer */
    1346        5433 :   return pollardbrent_i(n, size, c0, 0);
    1347             : }
    1348             : GEN
    1349           0 : Z_pollardbrent(GEN n, long rounds, long seed)
    1350             : {
    1351           0 :   pari_sp av = avma;
    1352           0 :   GEN v = pollardbrent_i(n, expi(n)+1, rounds, seed);
    1353           0 :   if (!v) return NULL;
    1354           0 :   if (typ(v) == t_INT) v = mkvec2(v, diviiexact(n,v));
    1355           0 :   else if (lg(v) == 7) v = mkvec2(gel(v,1), gel(v,4));
    1356           0 :   else v = mkvec3(gel(v,1), gel(v,4), gel(v,7));
    1357           0 :   return gerepilecopy(av, v);
    1358             : }
    1359             : 
    1360             : /***********************************************************************/
    1361             : /**              FACTORIZATION (Shanks' SQUFOF) --GN2000Sep30-Oct01   **/
    1362             : /**  squfof() returns a nontrivial factor of n, assuming n is odd,    **/
    1363             : /**  composite, not a pure square, and has no small prime divisor,    **/
    1364             : /**  or NULL if it fails to find one.  It works on two discriminants  **/
    1365             : /**  simultaneously  (n and 5n for n=1(4), 3n and 4n for n=3(4)).     **/
    1366             : /**  Present implementation is limited to input <2^59, and works most **/
    1367             : /**  of the time in signed arithmetic on integers <2^31 in absolute   **/
    1368             : /**  size. (Cf. Algo 8.7.2 in ACiCNT)                                 **/
    1369             : /***********************************************************************/
    1370             : 
    1371             : /* The following is invoked to walk back along the ambiguous cycle* until we
    1372             :  * hit an ambiguous form and thus the desired factor, which it returns.  If it
    1373             :  * fails for any reason, it returns 0.  It doesn't interfere with timing and
    1374             :  * diagnostics, which it leaves to squfof().
    1375             :  *
    1376             :  * Before we invoke this, we've found a form (A, B, -C) with A = a^2, where a
    1377             :  * isn't blacklisted and where gcd(a, B) = 1.  According to ACiCANT, we should
    1378             :  * now proceed reducing the form (a, -B, -aC), but it is easy to show that the
    1379             :  * first reduction step always sends this to (-aC, B, a), and the next one,
    1380             :  * with q computed as usual from B and a (occupying the c position), gives a
    1381             :  * reduced form, whose third member is easiest to recover by going back to D.
    1382             :  * From this point onwards, we're once again working with single-word numbers.
    1383             :  * No need to track signs, just work with the abs values of the coefficients. */
    1384             : static long
    1385        2980 : squfof_ambig(long a, long B, long dd, GEN D)
    1386             : {
    1387             :   long b, c, q, qa, qc, qcb, a0, b0, b1, c0;
    1388        2980 :   long cnt = 0; /* count reduction steps on the cycle */
    1389             : 
    1390        2980 :   q = (dd + (B>>1)) / a;
    1391        2980 :   qa = q * a;
    1392        2980 :   b = (qa - B) + qa; /* avoid overflow */
    1393             :   {
    1394        2980 :     pari_sp av = avma;
    1395        2980 :     c = itos(divis(shifti(subii(D, sqrs(b)), -2), a));
    1396        2980 :     set_avma(av);
    1397             :   }
    1398             : #ifdef DEBUG_SQUFOF
    1399             :   err_printf("SQUFOF: ambigous cycle of discriminant %Ps\n", D);
    1400             :   err_printf("SQUFOF: Form on ambigous cycle (%ld, %ld, %ld)\n", a, b, c);
    1401             : #endif
    1402             : 
    1403        2980 :   a0 = a; b0 = b1 = b;        /* end of loop detection and safeguard */
    1404             : 
    1405             :   for (;;) /* reduced cycles are finite */
    1406             :   { /* reduction step */
    1407    10360380 :     c0 = c;
    1408     5181680 :     if (c0 > dd)
    1409     1448015 :       q = 1;
    1410             :     else
    1411     3733665 :       q = (dd + (b>>1)) / c0;
    1412     5181680 :     if (q == 1)
    1413             :     {
    1414     2155453 :       qcb = c0 - b; b = c0 + qcb; c = a - qcb;
    1415             :     }
    1416             :     else
    1417             :     {
    1418     3026227 :       qc = q*c0; qcb = qc - b; b = qc + qcb; c = a - q*qcb;
    1419             :     }
    1420     5181680 :     a = c0;
    1421             : 
    1422     5181680 :     cnt++; if (b == b1) break;
    1423             : 
    1424             :     /* safeguard against infinite loop: recognize when we've walked the entire
    1425             :      * cycle in vain. (I don't think this can actually happen -- exercise.) */
    1426     5178700 :     if (b == b0 && a == a0) return 0;
    1427             : 
    1428     5178700 :     b1 = b;
    1429             :   }
    1430        2980 :   q = a&1 ? a : a>>1;
    1431        2980 :   if (DEBUGLEVEL >= 4)
    1432             :   {
    1433           0 :     if (q > 1)
    1434           0 :       err_printf("SQUFOF: found factor %ld from ambiguous form\n"
    1435             :                  "\tafter %ld steps on the ambiguous cycle\n",
    1436           0 :                  q / ugcd(q,15), cnt);
    1437             :     else
    1438           0 :       err_printf("SQUFOF: ...found nothing on the ambiguous cycle\n"
    1439             :                  "\tafter %ld steps there\n", cnt);
    1440           0 :     if (DEBUGLEVEL >= 6) err_printf("SQUFOF: squfof_ambig returned %ld\n", q);
    1441             :   }
    1442        2980 :   return q;
    1443             : }
    1444             : 
    1445             : #define SQUFOF_BLACKLIST_SZ 64
    1446             : 
    1447             : /* assume 2,3,5 do not divide n */
    1448             : static GEN
    1449        3413 : squfof(GEN n)
    1450             : {
    1451             :   ulong d1, d2;
    1452        3413 :   long tf = lgefint(n), nm4, cnt = 0;
    1453             :   long a1, b1, c1, dd1, L1, a2, b2, c2, dd2, L2, a, q, c, qc, qcb;
    1454             :   GEN D1, D2;
    1455        3413 :   pari_sp av = avma;
    1456             :   long blacklist1[SQUFOF_BLACKLIST_SZ], blacklist2[SQUFOF_BLACKLIST_SZ];
    1457        3413 :   long blp1 = 0, blp2 = 0;
    1458        3413 :   int act1 = 1, act2 = 1;
    1459             : 
    1460             : #ifdef LONG_IS_64BIT
    1461        2958 :   if (tf > 3 || (tf == 3 && uel(n,2)             >= (1UL << (BITS_IN_LONG-5))))
    1462             : #else  /* 32 bits */
    1463         455 :   if (tf > 4 || (tf == 4 && (ulong)(*int_MSW(n)) >= (1UL << (BITS_IN_LONG-5))))
    1464             : #endif
    1465        1070 :     return NULL; /* n too large */
    1466             : 
    1467             :   /* now we have 5 < n < 2^59 */
    1468        2343 :   nm4 = mod4(n);
    1469        2343 :   if (nm4 == 1)
    1470             :   { /* n = 1 (mod4):  run one iteration on D1 = n, another on D2 = 5n */
    1471        1202 :     D1 = n;
    1472        1202 :     D2 = mului(5,n); d2 = itou(sqrti(D2)); dd2 = (long)((d2>>1) + (d2&1));
    1473        1202 :     b2 = (long)((d2-1) | 1);        /* b1, b2 will always stay odd */
    1474             :   }
    1475             :   else
    1476             :   { /* n = 3 (mod4):  run one iteration on D1 = 3n, another on D2 = 4n */
    1477        1141 :     D1 = mului(3,n);
    1478        1141 :     D2 = shifti(n,2); dd2 = itou(sqrti(n)); d2 =  dd2 << 1;
    1479        1141 :     b2 = (long)(d2 & (~1UL)); /* largest even below d2, will stay even */
    1480             :   }
    1481        2343 :   d1 = itou(sqrti(D1));
    1482        2343 :   b1 = (long)((d1-1) | 1); /* largest odd number not exceeding d1 */
    1483        2343 :   c1 = itos(shifti(subii(D1, sqru((ulong)b1)), -2));
    1484        2343 :   if (!c1) pari_err_BUG("squfof [caller of] (n or 3n is a square)");
    1485        2343 :   c2 = itos(shifti(subii(D2, sqru((ulong)b2)), -2));
    1486        2343 :   if (!c2) pari_err_BUG("squfof [caller of] (5n is a square)");
    1487        2343 :   L1 = (long)usqrt(d1);
    1488        2343 :   L2 = (long)usqrt(d2);
    1489             :   /* dd1 used to compute floor((d1+b1)/2) as dd1+floor(b1/2), without
    1490             :    * overflowing the 31bit signed integer size limit. Same for dd2. */
    1491        2343 :   dd1 = (long) ((d1>>1) + (d1&1));
    1492        2343 :   a1 = a2 = 1;
    1493             : 
    1494             :   /* The two (identity) forms (a1,b1,-c1) and (a2,b2,-c2) are now set up.
    1495             :    *
    1496             :    * a1 and c1 represent the absolute values of the a,c coefficients; we keep
    1497             :    * track of the sign separately, via the iteration counter cnt: when cnt is
    1498             :    * even, c is understood to be negative, else c is positive and a < 0.
    1499             :    *
    1500             :    * L1, L2 are the limits for blacklisting small leading coefficients
    1501             :    * on the principal cycle, to guarantee that when we find a square form,
    1502             :    * its square root will belong to an ambiguous cycle  (i.e. won't be an
    1503             :    * earlier form on the principal cycle).
    1504             :    *
    1505             :    * When n = 3(mod 4), D2 = 12(mod 16), and b^2 is always 0 or 4 mod 16.
    1506             :    * It follows that 4*a*c must be 4 or 8 mod 16, respectively, so at most
    1507             :    * one of a,c can be divisible by 2 at most to the first power.  This fact
    1508             :    * is used a couple of times below.
    1509             :    *
    1510             :    * The flags act1, act2 remain true while the respective cycle is still
    1511             :    * active;  we drop them to false when we return to the identity form with-
    1512             :    * out having found a square form  (or when the blacklist overflows, which
    1513             :    * shouldn't happen). */
    1514        2343 :   if (DEBUGLEVEL >= 4)
    1515           0 :     err_printf("SQUFOF: entering main loop with forms\n"
    1516             :                "\t(1, %ld, %ld) and (1, %ld, %ld)\n\tof discriminants\n"
    1517             :                "\t%Ps and %Ps, respectively\n", b1, -c1, b2, -c2, D1, D2);
    1518             : 
    1519             :   /* MAIN LOOP: walk around the principal cycle looking for a square form.
    1520             :    * Blacklist small leading coefficients.
    1521             :    *
    1522             :    * The reduction operator can be computed entirely in 32-bit arithmetic:
    1523             :    * Let q = floor(floor((d1+b1)/2)/c1)  (when c1>dd1, q=1, which happens
    1524             :    * often enough to special-case it).  Then the new b1 = (q*c1-b1) + q*c1,
    1525             :    * which does not overflow, and the new c1 = a1 - q*(q*c1-b1), which is
    1526             :    * bounded by d1 in abs size since both the old and the new a1 are positive
    1527             :    * and bounded by d1. */
    1528     7713888 :   while (act1 || act2)
    1529             :   {
    1530     7713874 :     if (act1)
    1531             :     { /* send first form through reduction operator if active */
    1532     7713790 :       c = c1;
    1533     7713790 :       q = (c > dd1)? 1: (dd1 + (b1>>1)) / c;
    1534     7713790 :       if (q == 1)
    1535     3192107 :       { qcb = c - b1; b1 = c + qcb; c1 = a1 - qcb; }
    1536             :       else
    1537     4521683 :       { qc = q*c; qcb = qc - b1; b1 = qc + qcb; c1 = a1 - q*qcb; }
    1538     7713790 :       a1 = c;
    1539             : 
    1540     7713790 :       if (a1 <= L1)
    1541             :       { /* blacklist this */
    1542        2121 :         if (blp1 >= SQUFOF_BLACKLIST_SZ) /* overflows: shouldn't happen */
    1543           0 :           act1 = 0; /* silently */
    1544             :         else
    1545             :         {
    1546        2121 :           if (DEBUGLEVEL >= 6)
    1547           0 :             err_printf("SQUFOF: blacklisting a = %ld on first cycle\n", a1);
    1548        2121 :           blacklist1[blp1++] = a1;
    1549             :         }
    1550             :       }
    1551             :     }
    1552     7713874 :     if (act2)
    1553             :     { /* send second form through reduction operator if active */
    1554     7712684 :       c = c2;
    1555     7712684 :       q = (c > dd2)? 1: (dd2 + (b2>>1)) / c;
    1556     7712684 :       if (q == 1)
    1557     3202457 :       { qcb = c - b2; b2 = c + qcb; c2 = a2 - qcb; }
    1558             :       else
    1559     4510227 :       { qc = q*c; qcb = qc - b2; b2 = qc + qcb; c2 = a2 - q*qcb; }
    1560     7712684 :       a2 = c;
    1561             : 
    1562     7712684 :       if (a2 <= L2)
    1563             :       { /* blacklist this */
    1564        1751 :         if (blp2 >= SQUFOF_BLACKLIST_SZ) /* overflows: shouldn't happen */
    1565           0 :           act2 = 0; /* silently */
    1566             :         else
    1567             :         {
    1568        1751 :           if (DEBUGLEVEL >= 6)
    1569           0 :             err_printf("SQUFOF: blacklisting a = %ld on second cycle\n", a2);
    1570        1751 :           blacklist2[blp2++] = a2;
    1571             :         }
    1572             :       }
    1573             :     }
    1574             : 
    1575             :     /* bump counter, loop if this is an odd iteration (i.e. if the real
    1576             :      * leading coefficients are negative) */
    1577     7713874 :     if (++cnt & 1) continue;
    1578             : 
    1579             :     /* second half of main loop entered only when the leading coefficients
    1580             :      * are positive (i.e., during even-numbered iterations) */
    1581             : 
    1582             :     /* examine first form if active */
    1583     3856937 :     if (act1 && a1 == 1) /* back to identity */
    1584             :     { /* drop this discriminant */
    1585          14 :       act1 = 0;
    1586          14 :       if (DEBUGLEVEL >= 4)
    1587           0 :         err_printf("SQUFOF: first cycle exhausted after %ld iterations,\n"
    1588             :                    "\tdropping it\n", cnt);
    1589             :     }
    1590     3856937 :     if (act1)
    1591             :     {
    1592     3856881 :       if (uissquareall((ulong)a1, (ulong*)&a))
    1593             :       { /* square form */
    1594        2309 :         if (DEBUGLEVEL >= 4)
    1595           0 :           err_printf("SQUFOF: square form (%ld^2, %ld, %ld) on first cycle\n"
    1596             :                      "\tafter %ld iterations\n", a, b1, -c1, cnt);
    1597        2309 :         if (a <= L1)
    1598             :         { /* blacklisted? */
    1599             :           long j;
    1600        4549 :           for (j = 0; j < blp1; j++)
    1601        3199 :             if (a == blacklist1[j]) { a = 0; break; }
    1602             :         }
    1603        2309 :         if (a > 0)
    1604             :         { /* not blacklisted */
    1605        1350 :           q = ugcd(a, b1); /* imprimitive form? */
    1606        1350 :           if (q > 1)
    1607             :           { /* q^2 divides D1 hence n [ assuming n % 3 != 0 ] */
    1608           0 :             set_avma(av);
    1609           0 :             if (DEBUGLEVEL >= 4) err_printf("SQUFOF: found factor %ld^2\n", q);
    1610           0 :             return mkvec3(utoipos(q), gen_2, NULL);/* exponent 2, unknown status */
    1611             :           }
    1612             :           /* chase the inverse root form back along the ambiguous cycle */
    1613        1350 :           q = squfof_ambig(a, b1, dd1, D1);
    1614        1350 :           if (nm4 == 3 && q % 3 == 0) q /= 3;
    1615        1350 :           if (q > 1) { set_avma(av); return utoipos(q); } /* SUCCESS! */
    1616             :         }
    1617         959 :         else if (DEBUGLEVEL >= 4) /* blacklisted */
    1618           0 :           err_printf("SQUFOF: ...but the root form seems to be on the "
    1619             :                      "principal cycle\n");
    1620             :       }
    1621             :     }
    1622             : 
    1623             :     /* examine second form if active */
    1624     3855832 :     if (act2 && a2 == 1) /* back to identity form */
    1625             :     { /* drop this discriminant */
    1626          21 :       act2 = 0;
    1627          21 :       if (DEBUGLEVEL >= 4)
    1628           0 :         err_printf("SQUFOF: second cycle exhausted after %ld iterations,\n"
    1629             :                    "\tdropping it\n", cnt);
    1630             :     }
    1631     3855832 :     if (act2)
    1632             :     {
    1633     3855223 :       if (uissquareall((ulong)a2, (ulong*)&a))
    1634             :       { /* square form */
    1635        2113 :         if (DEBUGLEVEL >= 4)
    1636           0 :           err_printf("SQUFOF: square form (%ld^2, %ld, %ld) on second cycle\n"
    1637             :                      "\tafter %ld iterations\n", a, b2, -c2, cnt);
    1638        2113 :         if (a <= L2)
    1639             :         { /* blacklisted? */
    1640             :           long j;
    1641        3738 :           for (j = 0; j < blp2; j++)
    1642        2108 :             if (a == blacklist2[j]) { a = 0; break; }
    1643             :         }
    1644        2113 :         if (a > 0)
    1645             :         { /* not blacklisted */
    1646        1630 :           q = ugcd(a, b2); /* imprimitive form? */
    1647             :           /* NB if b2 is even, a is odd, so the gcd is always odd */
    1648        1630 :           if (q > 1)
    1649             :           { /* q^2 divides D2 hence n [ assuming n % 5 != 0 ] */
    1650           0 :             set_avma(av);
    1651           0 :             if (DEBUGLEVEL >= 4) err_printf("SQUFOF: found factor %ld^2\n", q);
    1652           0 :             return mkvec3(utoipos(q), gen_2, NULL);/* exponent 2, unknown status */
    1653             :           }
    1654             :           /* chase the inverse root form along the ambiguous cycle */
    1655        1630 :           q = squfof_ambig(a, b2, dd2, D2);
    1656        1630 :           if (nm4 == 1 && q % 5 == 0) q /= 5;
    1657        1630 :           if (q > 1) { set_avma(av); return utoipos(q); } /* SUCCESS! */
    1658             :         }
    1659         483 :         else if (DEBUGLEVEL >= 4)        /* blacklisted */
    1660           0 :           err_printf("SQUFOF: ...but the root form seems to be on the "
    1661             :                      "principal cycle\n");
    1662             :       }
    1663             :     }
    1664             :   } /* end main loop */
    1665             : 
    1666             :   /* both discriminants turned out to be useless. */
    1667          14 :   if (DEBUGLEVEL>=4) err_printf("SQUFOF: giving up\n");
    1668          14 :   return gc_NULL(av);
    1669             : }
    1670             : 
    1671             : /***********************************************************************/
    1672             : /*                    DETECTING ODD POWERS  --GN1998Jun28              */
    1673             : /*   Factoring engines like MPQS which ultimately rely on computing    */
    1674             : /*   gcd(N, x^2-y^2) to find a nontrivial factor of N can't split      */
    1675             : /*   N = p^k for an odd prime p, since (Z/p^k)^* is then cyclic. Here  */
    1676             : /*   is an analogue of Z_issquareall() for 3rd, 5th and 7th powers.    */
    1677             : /*   The general case is handled by is_kth_power                       */
    1678             : /***********************************************************************/
    1679             : 
    1680             : /* Multistage sieve. First stages work mod 211, 209, 61, 203 in this order
    1681             :  * (first reduce mod the product of these and then take the remainder apart).
    1682             :  * Second stages use 117, 31, 43, 71. Moduli which are no longer interesting
    1683             :  * are skipped. Everything is encoded in a table of 106 24-bit masks. We only
    1684             :  * need the first half of the residues.  Three bits per modulus indicate which
    1685             :  * residues are 7th (bit 2), 5th (bit 1) or 3rd (bit 0) powers; the eight
    1686             :  * moduli above are assigned right-to-left. The table was generated using: */
    1687             : 
    1688             : #if 0
    1689             : L = [71, 43, 31, [O(3^2),O(13)], [O(7),O(29)], 61, [O(11),O(19)], 211];
    1690             : ispow(x, N, k)=
    1691             : {
    1692             :   if (type(N) == "t_INT", return (ispower(Mod(x,N), k)));
    1693             :   for (i = 1, #N, if (!ispower(x + N[i], k), return (0))); 1
    1694             : }
    1695             : check(r) =
    1696             : {
    1697             :   print1("  0");
    1698             :   for (i=1,#L,
    1699             :     N = 0;
    1700             :     if (ispow(r, L[i], 3), N += 1);
    1701             :     if (ispow(r, L[i], 5), N += 2);
    1702             :     if (ispow(r, L[i], 7), N += 4);
    1703             :     print1(N);
    1704             :   ); print("ul,  /* ", r, " */")
    1705             : }
    1706             : for (r = 0, 105, check(r))
    1707             : #endif
    1708             : static ulong powersmod[106] = {
    1709             :   077777777ul,  /* 0 */
    1710             :   077777777ul,  /* 1 */
    1711             :   013562440ul,  /* 2 */
    1712             :   012402540ul,  /* 3 */
    1713             :   013562440ul,  /* 4 */
    1714             :   052662441ul,  /* 5 */
    1715             :   016603440ul,  /* 6 */
    1716             :   016463450ul,  /* 7 */
    1717             :   013573551ul,  /* 8 */
    1718             :   012462540ul,  /* 9 */
    1719             :   012462464ul,  /* 10 */
    1720             :   013462771ul,  /* 11 */
    1721             :   012406473ul,  /* 12 */
    1722             :   012463641ul,  /* 13 */
    1723             :   052463646ul,  /* 14 */
    1724             :   012503446ul,  /* 15 */
    1725             :   013562440ul,  /* 16 */
    1726             :   052466440ul,  /* 17 */
    1727             :   012472451ul,  /* 18 */
    1728             :   012462454ul,  /* 19 */
    1729             :   032463550ul,  /* 20 */
    1730             :   013403664ul,  /* 21 */
    1731             :   013463460ul,  /* 22 */
    1732             :   032562565ul,  /* 23 */
    1733             :   012402540ul,  /* 24 */
    1734             :   052662441ul,  /* 25 */
    1735             :   032672452ul,  /* 26 */
    1736             :   013573551ul,  /* 27 */
    1737             :   012467541ul,  /* 28 */
    1738             :   012567640ul,  /* 29 */
    1739             :   032706450ul,  /* 30 */
    1740             :   012762452ul,  /* 31 */
    1741             :   033762662ul,  /* 32 */
    1742             :   012502562ul,  /* 33 */
    1743             :   032463562ul,  /* 34 */
    1744             :   013563440ul,  /* 35 */
    1745             :   016663440ul,  /* 36 */
    1746             :   036662550ul,  /* 37 */
    1747             :   012462552ul,  /* 38 */
    1748             :   033502450ul,  /* 39 */
    1749             :   012462643ul,  /* 40 */
    1750             :   033467540ul,  /* 41 */
    1751             :   017403441ul,  /* 42 */
    1752             :   017463462ul,  /* 43 */
    1753             :   017472460ul,  /* 44 */
    1754             :   033462470ul,  /* 45 */
    1755             :   052566450ul,  /* 46 */
    1756             :   013562640ul,  /* 47 */
    1757             :   032403640ul,  /* 48 */
    1758             :   016463450ul,  /* 49 */
    1759             :   016463752ul,  /* 50 */
    1760             :   033402440ul,  /* 51 */
    1761             :   012462540ul,  /* 52 */
    1762             :   012472540ul,  /* 53 */
    1763             :   053562462ul,  /* 54 */
    1764             :   012463465ul,  /* 55 */
    1765             :   012663470ul,  /* 56 */
    1766             :   052607450ul,  /* 57 */
    1767             :   012566553ul,  /* 58 */
    1768             :   013466440ul,  /* 59 */
    1769             :   012502741ul,  /* 60 */
    1770             :   012762744ul,  /* 61 */
    1771             :   012763740ul,  /* 62 */
    1772             :   012763443ul,  /* 63 */
    1773             :   013573551ul,  /* 64 */
    1774             :   013462471ul,  /* 65 */
    1775             :   052502460ul,  /* 66 */
    1776             :   012662463ul,  /* 67 */
    1777             :   012662451ul,  /* 68 */
    1778             :   012403550ul,  /* 69 */
    1779             :   073567540ul,  /* 70 */
    1780             :   072463445ul,  /* 71 */
    1781             :   072462740ul,  /* 72 */
    1782             :   012472442ul,  /* 73 */
    1783             :   012462644ul,  /* 74 */
    1784             :   013406650ul,  /* 75 */
    1785             :   052463471ul,  /* 76 */
    1786             :   012563474ul,  /* 77 */
    1787             :   013503460ul,  /* 78 */
    1788             :   016462441ul,  /* 79 */
    1789             :   016462440ul,  /* 80 */
    1790             :   012462540ul,  /* 81 */
    1791             :   013462641ul,  /* 82 */
    1792             :   012463454ul,  /* 83 */
    1793             :   013403550ul,  /* 84 */
    1794             :   057563540ul,  /* 85 */
    1795             :   017466441ul,  /* 86 */
    1796             :   017606471ul,  /* 87 */
    1797             :   053666573ul,  /* 88 */
    1798             :   012562561ul,  /* 89 */
    1799             :   013473641ul,  /* 90 */
    1800             :   032573440ul,  /* 91 */
    1801             :   016763440ul,  /* 92 */
    1802             :   016702640ul,  /* 93 */
    1803             :   033762552ul,  /* 94 */
    1804             :   012562550ul,  /* 95 */
    1805             :   052402451ul,  /* 96 */
    1806             :   033563441ul,  /* 97 */
    1807             :   012663561ul,  /* 98 */
    1808             :   012677560ul,  /* 99 */
    1809             :   012462464ul,  /* 100 */
    1810             :   032562642ul,  /* 101 */
    1811             :   013402551ul,  /* 102 */
    1812             :   032462450ul,  /* 103 */
    1813             :   012467445ul,  /* 104 */
    1814             :   032403440ul,  /* 105 */
    1815             : };
    1816             : 
    1817             : static int
    1818     2693163 : check_res(ulong x, ulong N, int shift, ulong *mask)
    1819             : {
    1820     2693163 :   long r = x%N; if ((ulong)r> (N>>1)) r = N - r;
    1821     2693163 :   *mask &= (powersmod[r] >> shift);
    1822     2693163 :   return *mask;
    1823             : }
    1824             : 
    1825             : /* is x mod 211*209*61*203*117*31*43*71 a 3rd, 5th or 7th power ? */
    1826             : int
    1827     1603846 : uis_357_powermod(ulong x, ulong *mask)
    1828             : {
    1829     1603846 :   if (             !check_res(x, 211UL, 0, mask)) return 0;
    1830      701682 :   if (*mask & 3 && !check_res(x, 209UL, 3, mask)) return 0;
    1831      306063 :   if (*mask & 3 && !check_res(x,  61UL, 6, mask)) return 0;
    1832      188793 :   if (*mask & 5 && !check_res(x, 203UL, 9, mask)) return 0;
    1833       46320 :   if (*mask & 1 && !check_res(x, 117UL,12, mask)) return 0;
    1834       31419 :   if (*mask & 3 && !check_res(x,  31UL,15, mask)) return 0;
    1835       23835 :   if (*mask & 5 && !check_res(x,  43UL,18, mask)) return 0;
    1836        7041 :   if (*mask & 6 && !check_res(x,  71UL,21, mask)) return 0;
    1837        3621 :   return 1;
    1838             : }
    1839             : /* asume x > 0 and pt != NULL */
    1840             : int
    1841     1559532 : uis_357_power(ulong x, ulong *pt, ulong *mask)
    1842             : {
    1843             :   double logx;
    1844     1559532 :   if (!odd(x))
    1845             :   {
    1846        8905 :     long v = vals(x);
    1847        8905 :     if (v % 7) *mask &= ~4;
    1848        8905 :     if (v % 5) *mask &= ~2;
    1849        8905 :     if (v % 3) *mask &= ~1;
    1850        8905 :     if (!*mask) return 0;
    1851             :   }
    1852     1552016 :   if (!uis_357_powermod(x, mask)) return 0;
    1853        2960 :   logx = log((double)x);
    1854        3756 :   while (*mask)
    1855             :   {
    1856             :     long e, b;
    1857             :     ulong y, ye;
    1858        2960 :     if (*mask & 1)      { b = 1; e = 3; }
    1859         882 :     else if (*mask & 2) { b = 2; e = 5; }
    1860         355 :     else                { b = 4; e = 7; }
    1861        2960 :     y = (ulong)(exp(logx / e) + 0.5);
    1862        2960 :     ye = upowuu(y,e);
    1863        2960 :     if (ye == x) { *pt = y; return e; }
    1864             : #ifdef LONG_IS_64BIT
    1865         684 :     if (ye > x) y--; else y++;
    1866         684 :     ye = upowuu(y,e);
    1867         684 :     if (ye == x) { *pt = y; return e; }
    1868             : #endif
    1869         796 :     *mask &= ~b; /* turn the bit off */
    1870             :   }
    1871         796 :   return 0;
    1872             : }
    1873             : 
    1874             : #ifndef LONG_IS_64BIT
    1875             : /* as above, split in two functions */
    1876             : /* is x mod 211*209*61*203 a 3rd, 5th or 7th power ? */
    1877             : static int
    1878       12095 : uis_357_powermod_32bit_1(ulong x, ulong *mask)
    1879             : {
    1880       12095 :   if (             !check_res(x, 211UL, 0, mask)) return 0;
    1881        6653 :   if (*mask & 3 && !check_res(x, 209UL, 3, mask)) return 0;
    1882        3430 :   if (*mask & 3 && !check_res(x,  61UL, 6, mask)) return 0;
    1883        2397 :   if (*mask & 5 && !check_res(x, 203UL, 9, mask)) return 0;
    1884         666 :   return 1;
    1885             : }
    1886             : /* is x mod 117*31*43*71 a 3rd, 5th or 7th power ? */
    1887             : static int
    1888         666 : uis_357_powermod_32bit_2(ulong x, ulong *mask)
    1889             : {
    1890         666 :   if (*mask & 1 && !check_res(x, 117UL,12, mask)) return 0;
    1891         520 :   if (*mask & 3 && !check_res(x,  31UL,15, mask)) return 0;
    1892         419 :   if (*mask & 5 && !check_res(x,  43UL,18, mask)) return 0;
    1893         199 :   if (*mask & 6 && !check_res(x,  71UL,21, mask)) return 0;
    1894         150 :   return 1;
    1895             : }
    1896             : #endif
    1897             : 
    1898             : /* Returns 3, 5, or 7 if x is a cube (but not a 5th or 7th power),  a 5th
    1899             :  * power (but not a 7th),  or a 7th power, and in this case creates the
    1900             :  * base on the stack and assigns its address to *pt.  Otherwise returns 0.
    1901             :  * x must be of type t_INT and positive;  this is not checked.  The *mask
    1902             :  * argument tells us which things to check -- bit 0: 3rd, bit 1: 5th,
    1903             :  * bit 2: 7th pwr;  set a bit to have the corresponding power examined --
    1904             :  * and is updated appropriately for a possible follow-up call */
    1905             : int
    1906     1980020 : is_357_power(GEN x, GEN *pt, ulong *mask)
    1907             : {
    1908     1980020 :   long lx = lgefint(x);
    1909             :   ulong r;
    1910             :   pari_sp av;
    1911             :   GEN y;
    1912             : 
    1913     1980020 :   if (!*mask) return 0; /* useful when running in a loop */
    1914     1610084 :   if (DEBUGLEVEL>4)
    1915           0 :     err_printf("OddPwrs: examining %ld-bit integer\n", expi(x)+1);
    1916     1610084 :   if (lgefint(x) == 3) {
    1917             :     ulong t;
    1918     1546160 :     long e = uis_357_power(x[2], &t, mask);
    1919     1546160 :     if (e)
    1920             :     {
    1921        2138 :       if (pt) *pt = utoi(t);
    1922        2138 :       return e;
    1923             :     }
    1924     1544022 :     return 0;
    1925             :   }
    1926             : #ifdef LONG_IS_64BIT
    1927       51829 :   r = (lx == 3)? uel(x,2): umodiu(x, 6046846918939827UL);
    1928       51830 :   if (!uis_357_powermod(r, mask)) return 0;
    1929             : #else
    1930       12095 :   r = (lx == 3)? uel(x,2): umodiu(x, 211*209*61*203);
    1931       12095 :   if (!uis_357_powermod_32bit_1(r, mask)) return 0;
    1932         666 :   r = (lx == 3)? uel(x,2): umodiu(x, 117*31*43*71);
    1933         666 :   if (!uis_357_powermod_32bit_2(r, mask)) return 0;
    1934             : #endif
    1935         811 :   av = avma;
    1936         879 :   while (*mask)
    1937             :   {
    1938             :     long e, b;
    1939             :     /* priority to higher powers: if we have a 21st, it is easier to rediscover
    1940             :      * that its 7th root is a cube than that its cube root is a 7th power */
    1941         811 :          if (*mask & 4) { b = 4; e = 7; }
    1942         709 :     else if (*mask & 2) { b = 2; e = 5; }
    1943         309 :     else                { b = 1; e = 3; }
    1944         811 :     y = mpround( sqrtnr(itor(x, nbits2prec(64 + bit_accuracy(lx) / e)), e) );
    1945         811 :     if (equalii(powiu(y,e), x))
    1946             :     {
    1947         743 :       if (!pt) return gc_int(av,e);
    1948         743 :       set_avma((pari_sp)y); *pt = gerepileuptoint(av, y);
    1949         743 :       return e;
    1950             :     }
    1951          68 :     *mask &= ~b; /* turn the bit off */
    1952          68 :     set_avma(av);
    1953             :   }
    1954          68 :   return 0;
    1955             : }
    1956             : 
    1957             : /* Is x a n-th power ?
    1958             :  * if d = NULL, n not necessarily prime, otherwise, n prime and d the
    1959             :  * corresponding diffptr to go on looping over primes.
    1960             :  * If pt != NULL, it receives the n-th root */
    1961             : ulong
    1962      344654 : is_kth_power(GEN x, ulong n, GEN *pt)
    1963             : {
    1964             :   forprime_t T;
    1965             :   long j;
    1966             :   ulong q, residue;
    1967             :   GEN y;
    1968      344654 :   pari_sp av = avma;
    1969             : 
    1970      344654 :   (void)u_forprime_arith_init(&T, odd(n)? 2*n+1: n+1, ULONG_MAX, 1,n);
    1971             :   /* we'll start at q, smallest prime >= n */
    1972             : 
    1973             :   /* Modular checks, use small primes q congruent 1 mod n */
    1974             :   /* A non n-th power nevertheless passes the test with proba n^(-#checks),
    1975             :    * We'd like this < 1e-6 but let j = floor(log(1e-6) / log(n)) which
    1976             :    * ensures much less. */
    1977      344663 :   if (n < 16)
    1978       93484 :     j = 5;
    1979      251179 :   else if (n < 32)
    1980       92094 :     j = 4;
    1981      159085 :   else if (n < 101)
    1982      137171 :     j = 3;
    1983       21914 :   else if (n < 1001)
    1984        5577 :     j = 2;
    1985       16337 :   else if (n < 17886697) /* smallest such that smallest suitable q is > 2^32 */
    1986       16303 :     j = 1;
    1987             :   else
    1988          35 :     j = 0;
    1989      374640 :   for (; j > 0; j--)
    1990             :   {
    1991      373770 :     if (!(q = u_forprime_next(&T))) break;
    1992             :     /* q a prime = 1 mod n */
    1993      373761 :     residue = umodiu(x, q);
    1994      373776 :     if (residue == 0)
    1995             :     {
    1996         161 :       if (Z_lval(x,q) % n) return gc_ulong(av,0);
    1997          49 :       continue;
    1998             :     }
    1999             :     /* n-th power mod q ? */
    2000      373615 :     if (Fl_powu(residue, (q-1)/n, q) != 1) return gc_ulong(av,0);
    2001             :   }
    2002         870 :   set_avma(av);
    2003             : 
    2004         867 :   if (DEBUGLEVEL>4) err_printf("\nOddPwrs: [%lu] passed modular checks\n",n);
    2005             :   /* go to the horse's mouth... */
    2006         867 :   y = roundr( sqrtnr(itor(x, nbits2prec(expi(x)/n + 16)), n) );
    2007         867 :   if (!equalii(powiu(y, n), x)) {
    2008          90 :     if (DEBUGLEVEL>4) err_printf("\tBut it wasn't a pure power.\n");
    2009          90 :     return gc_ulong(av,0);
    2010             :   }
    2011         777 :   if (!pt) set_avma(av); else { set_avma((pari_sp)y); *pt = gerepileuptoint(av,y); }
    2012         777 :   return 1;
    2013             : }
    2014             : 
    2015             : /* is x a p^i-th power, p >= 11 prime ? Similar to is_357_power(), but instead
    2016             :  * of the mask, we keep the current test exponent around. Cut off when
    2017             :  * log_2 x^(1/k) < cutoffbits since we would have found it by trial division.
    2018             :  * Everything needed here (primitive roots etc.) is computed from scratch on
    2019             :  * the fly; compared to the size of numbers under consideration, these
    2020             :  * word-sized computations take negligible time.
    2021             :  * Any cutoffbits > 0 is safe, but direct root extraction attempts are faster
    2022             :  * when trial division has been used to discover very small bases. We become
    2023             :  * competitive at cutoffbits ~ 10 */
    2024             : int
    2025       55116 : is_pth_power(GEN x, GEN *pt, forprime_t *T, ulong cutoffbits)
    2026             : {
    2027       55116 :   long cnt=0, size = expi(x) /* not +1 */;
    2028             :   ulong p;
    2029       55116 :   pari_sp av = avma;
    2030      346640 :   while ((p = u_forprime_next(T)) && size/p >= cutoffbits) {
    2031      291562 :     long v = 1;
    2032      291562 :     if (DEBUGLEVEL>5 && cnt++==2000)
    2033           0 :       { cnt=0; err_printf("%lu%% ", 100*p*cutoffbits/size); }
    2034      291618 :     while (is_kth_power(x, p, pt)) {
    2035          56 :       v *= p; x = *pt;
    2036          56 :       size = expi(x);
    2037             :     }
    2038      291566 :     if (v > 1)
    2039             :     {
    2040          42 :       if (DEBUGLEVEL>5) err_printf("\nOddPwrs: is a %ld power\n",v);
    2041          42 :       return v;
    2042             :     }
    2043             :   }
    2044       55074 :   if (DEBUGLEVEL>5) err_printf("\nOddPwrs: not a power\n",p);
    2045       55074 :   return gc_int(av,0); /* give up */
    2046             : }
    2047             : 
    2048             : /***********************************************************************/
    2049             : /**                FACTORIZATION  (master iteration)                  **/
    2050             : /**      Driver for the various methods of finding large factors      **/
    2051             : /**      (after trial division has cast out the very small ones).     **/
    2052             : /**                        GN1998Jun24--30                            **/
    2053             : /***********************************************************************/
    2054             : 
    2055             : /* Direct use:
    2056             :  *  ifac_start_hint(n,moebius,hint) registers with the iterative factorizer
    2057             :  *  - an integer n (without prime factors  < tridiv_bound(n))
    2058             :  *  - registers whether or not we should terminate early if we find a square
    2059             :  *    factor,
    2060             :  *  - a hint about which method(s) to use.
    2061             :  *  This must always be called first. If input is not composite, oo loop.
    2062             :  *  The routine decomposes n nontrivially into a product of two factors except
    2063             :  *  in squarefreeness ('Moebius') mode.
    2064             :  *
    2065             :  *  ifac_start(n,moebius) same using default hint.
    2066             :  *
    2067             :  *  ifac_primary_factor()  returns a prime divisor (not necessarily the
    2068             :  *    smallest) and the corresponding exponent.
    2069             :  *
    2070             :  * Encapsulated user interface: Many arithmetic functions have a 'contributor'
    2071             :  * ifac_xxx, to be called on any large composite cofactor left over after trial
    2072             :  * division by small primes: xxx is one of moebius, issquarefree, totient, etc.
    2073             :  *
    2074             :  * We never test whether the input number is prime or composite, since
    2075             :  * presumably it will have come out of the small factors finder stage
    2076             :  * (which doesn't really exist yet but which will test the left-over
    2077             :  * cofactor for primality once it does). */
    2078             : 
    2079             : /* The data structure in which we preserve whatever we know about our number N
    2080             :  * is kept on the PARI stack, and updated as needed.
    2081             :  * This makes the machinery re-entrant, and avoids memory leaks when a lengthy
    2082             :  * factorization is interrupted. We try to keep the whole affair connected,
    2083             :  * and the parent object is always older than its children.  This may in
    2084             :  * rare cases lead to some extra copying around, and knowing what is garbage
    2085             :  * at any given time is not trivial. See below for examples how to do it right.
    2086             :  * (Connectedness is destroyed if callers of ifac_main() create stuff on the
    2087             :  * stack in between calls. This is harmless as long as ifac_realloc() is used
    2088             :  * to re-create a connected object at the head of the stack just before
    2089             :  * collecting garbage.)
    2090             :  * A t_INT may well have > 10^6 distinct prime factors larger than 2^16. Since
    2091             :  * we need not find factors in order of increasing size, we must be prepared to
    2092             :  * drag a very large amount of data around.  We start with a small structure
    2093             :  * and extend it when necessary. */
    2094             : 
    2095             : /* The idea of the algorithm is:
    2096             :  * Let N0 be whatever is currently left of N after dividing off all the
    2097             :  * prime powers we have already returned to the caller.  Then we maintain
    2098             :  * N0 as a product
    2099             :  * (1) N0 = \prod_i P_i^{e_i} * \prod_j Q_j^{f_j} * \prod_k C_k^{g_k}
    2100             :  * where the P_i and Q_j are distinct primes, each C_k is known composite,
    2101             :  * none of the P_i divides any C_k, and we also know the total ordering
    2102             :  * of all the P_i, Q_j and C_k; in particular, we will never try to divide
    2103             :  * a C_k by a larger Q_j.  Some of the C_k may have common factors.
    2104             :  *
    2105             :  * Caveat implementor:  Taking gcds among C_k's is very likely to cost at
    2106             :  * least as much time as dividing off any primes as we find them, and book-
    2107             :  * keeping would be tough (since D=gcd(C_1,C_2) can still have common factors
    2108             :  * with both C_1/D and C_2/D, and so on...).
    2109             :  *
    2110             :  * At startup, we just initialize the structure to
    2111             :  * (2) N = C_1^1   (composite).
    2112             :  *
    2113             :  * Whenever ifac_primary_factor() or one of the arithmetic user interface
    2114             :  * routines needs a primary factor, and the smallest thing in our list is P_1,
    2115             :  * we return that and its exponent, and remove it from our list. (When nothing
    2116             :  * is left, we return a sentinel value -- gen_1.  And in Moebius mode, when we
    2117             :  * see something with exponent > 1, whether prime or composite, we return gen_0
    2118             :  * or 0, depending on the function). In all other cases, ifac_main() iterates
    2119             :  * the following steps until we have a P_1 in the smallest position.
    2120             :  *
    2121             :  * When the smallest item is C_1, as it is initially:
    2122             :  * (3.1) Crack C_1 into a nontrivial product  U_1 * U_2  by whatever method
    2123             :  * comes to mind for this size. (U for 'unknown'.)  Cracking will detect
    2124             :  * perfect powers, so we may instead see a power of some U_1 here, or even
    2125             :  * something of the form U_1^k*U_2^k; of course the exponent already attached
    2126             :  * to C_1 is taken into account in the following.
    2127             :  * (3.2) If we have U_1*U_2, sort the two factors (distinct: squares are caught
    2128             :  * in stage 3.1). N.B. U_1 and U_2 are smaller than anything else in our list.
    2129             :  * (3.3) Check U_1 and U_2 for primality, and flag them accordingly.
    2130             :  * (3.4) Iterate.
    2131             :  *
    2132             :  * When the smallest item is Q_1:
    2133             :  * This is the unpleasant case.  We go through the entire list and try to
    2134             :  * divide Q_1 off each of the current C_k's, which usually fails, but may
    2135             :  * succeed several times. When a division was successful, the corresponding
    2136             :  * C_k is removed from our list, and the cofactor becomes a U_l for the moment
    2137             :  * unless it is 1 (which happens when C_k was a power of Q_1).  When we're
    2138             :  * through we upgrade Q_1 to P_1 status, then do a primality check on each U_l
    2139             :  * and sort it back into the list either as a Q_j or as a C_k.  If during the
    2140             :  * insertion sort we discover that some U_l equals some P_i or Q_j or C_k we
    2141             :  * already have, we just add U_l's exponent to that of its twin. (The sorting
    2142             :  * therefore happens before the primality test). Since this may produce one or
    2143             :  * more elements smaller than the P_1 we just confirmed, we may have to repeat
    2144             :  * the iteration.
    2145             :  * A trick avoids some Q_1 instances: just after the sweep classifying
    2146             :  * all current unknowns as either composites or primes, we do another downward
    2147             :  * sweep beginning with the largest current factor and stopping just above the
    2148             :  * largest current composite.  Every Q_j we pass is turned into a P_i.
    2149             :  * (Different primes are automatically coprime among each other, and primes do
    2150             :  * not divide smaller composites.)
    2151             :  * NB: We have no use for comparing the square of a prime to N0.  Normally
    2152             :  * we will get called after casting out only the smallest primes, and
    2153             :  * since we cannot guarantee that we see the large prime factors in as-
    2154             :  * cending order, we cannot stop when we find one larger than sqrt(N0). */
    2155             : 
    2156             : /* Data structure: We keep everything in a single t_VEC of t_INTs.  The
    2157             :  * first 2 components are read-only:
    2158             :  * 1) the first records whether we're doing full (NULL) or Moebius (gen_1)
    2159             :  * factorization; in the latter case subroutines return a sentinel value as
    2160             :  * soon as they spot an exponent > 1.
    2161             :  * 2) the second records the hint from factorint()'s optional flag, for use by
    2162             :  * ifac_crack().
    2163             :  *
    2164             :  * The remaining components (initially 15) are used in groups of three:
    2165             :  * [ factor (t_INT), exponent (t_INT), factor class ], where factor class is
    2166             :  *  NULL : unknown
    2167             :  *  gen_0: known composite C_k
    2168             :  *  gen_1: known prime Q_j awaiting trial division
    2169             :  *  gen_2: finished prime P_i.
    2170             :  * When during the division stage we re-sort a C_k-turned-U_l to a lower
    2171             :  * position, we rotate any intervening material upward towards its old
    2172             :  * slot.  When a C_k was divided down to 1, its slot is left empty at
    2173             :  * first; similarly when the re-sorting detects a repeated factor.
    2174             :  * After the sorting phase, we de-fragment the list and squeeze all the
    2175             :  * occupied slots together to the high end, so that ifac_crack() has room
    2176             :  * for new factors.  When this doesn't suffice, we abandon the current vector
    2177             :  * and allocate a somewhat larger one, defragmenting again while copying.
    2178             :  *
    2179             :  * For internal use: note that all exponents will fit into C longs, given
    2180             :  * PARI's lgefint field size.  When we work with them, we sometimes read
    2181             :  * out the GEN pointer, and sometimes do an itos, whatever is more con-
    2182             :  * venient for the task at hand. */
    2183             : 
    2184             : /*** Overview ***/
    2185             : 
    2186             : /* The '*where' argument in the following points into *partial at the first of
    2187             :  * the three fields of the first occupied slot.  It's there because the caller
    2188             :  * would already know where 'here' is, so we don't want to search for it again.
    2189             :  * We do not preserve this from one user-interface call to the next. */
    2190             : 
    2191             : /* In the most cases, control flows from the user interface to ifac_main() and
    2192             :  * then to a succession of ifac_crack()s and ifac_divide()s, with (typically)
    2193             :  * none of the latter finding anything. */
    2194             : 
    2195             : #define LAST(x) x+lg(x)-3
    2196             : #define FIRST(x) x+3
    2197             : 
    2198             : #define MOEBIUS(x) gel(x,1)
    2199             : #define HINT(x) gel(x,2)
    2200             : 
    2201             : /* y <- x */
    2202             : INLINE void
    2203           0 : SHALLOWCOPY(GEN x, GEN y) {
    2204           0 :   VALUE(y) = VALUE(x);
    2205           0 :   EXPON(y) = EXPON(x);
    2206           0 :   CLASS(y) = CLASS(x);
    2207           0 : }
    2208             : /* y <- x */
    2209             : INLINE void
    2210           0 : COPY(GEN x, GEN y) {
    2211           0 :   icopyifstack(VALUE(x), VALUE(y));
    2212           0 :   icopyifstack(EXPON(x), EXPON(y));
    2213           0 :   CLASS(y) = CLASS(x);
    2214           0 : }
    2215             : 
    2216             : /* Diagnostics */
    2217             : static void
    2218           0 : ifac_factor_dbg(GEN x)
    2219             : {
    2220           0 :   GEN c = CLASS(x), v = VALUE(x);
    2221           0 :   if (c == gen_2) err_printf("IFAC: factor %Ps\n\tis prime (finished)\n", v);
    2222           0 :   else if (c == gen_1) err_printf("IFAC: factor %Ps\n\tis prime\n", v);
    2223           0 :   else if (c == gen_0) err_printf("IFAC: factor %Ps\n\tis composite\n", v);
    2224           0 : }
    2225             : static void
    2226           0 : ifac_check(GEN partial, GEN where)
    2227             : {
    2228           0 :   if (!where || where < FIRST(partial) || where > LAST(partial))
    2229           0 :     pari_err_BUG("ifac_check ['where' out of bounds]");
    2230           0 : }
    2231             : static void
    2232           0 : ifac_print(GEN part, GEN where)
    2233             : {
    2234           0 :   long l = lg(part);
    2235             :   GEN p;
    2236             : 
    2237           0 :   err_printf("ifac partial factorization structure: %ld slots, ", (l-3)/3);
    2238           0 :   if (MOEBIUS(part)) err_printf("Moebius mode, ");
    2239           0 :   err_printf("hint = %ld\n", itos(HINT(part)));
    2240           0 :   ifac_check(part, where);
    2241           0 :   for (p = part+3; p < part + l; p += 3)
    2242             :   {
    2243           0 :     GEN v = VALUE(p), e = EXPON(p), c = CLASS(p);
    2244           0 :     const char *s = "";
    2245           0 :     if (!v) { err_printf("[empty slot]\n"); continue; }
    2246           0 :     if (c == NULL) s = "unknown";
    2247           0 :     else if (c == gen_0) s = "composite";
    2248           0 :     else if (c == gen_1) s = "unfinished prime";
    2249           0 :     else if (c == gen_2) s = "prime";
    2250           0 :     else pari_err_BUG("unknown factor class");
    2251           0 :     err_printf("[%Ps, %Ps, %s]\n", v, e, s);
    2252             :   }
    2253           0 :   err_printf("Done.\n");
    2254           0 : }
    2255             : 
    2256             : static const long decomp_default_hint = 0;
    2257             : /* assume n > 0, which we can assign to */
    2258             : /* return initial data structure, see ifac_crack() for the hint argument */
    2259             : static GEN
    2260        6143 : ifac_start_hint(GEN n, int moebius, long hint)
    2261             : {
    2262        6143 :   const long ifac_initial_length = 3 + 7*3;
    2263             :   /* codeword, moebius, hint, 7 slots -- a 512-bit product of distinct 8-bit
    2264             :    * primes needs at most 7 slots at a time) */
    2265        6143 :   GEN here, part = cgetg(ifac_initial_length, t_VEC);
    2266             : 
    2267        6143 :   MOEBIUS(part) = moebius? gen_1 : NULL;
    2268        6143 :   HINT(part) = stoi(hint);
    2269             :   /* fill first slot at the top end */
    2270        6143 :   here = part + ifac_initial_length - 3; /* LAST(part) */
    2271        6143 :   INIT(here, n,gen_1,gen_0); /* n^1: composite */
    2272       43001 :   while ((here -= 3) > part) ifac_delete(here);
    2273        6143 :   return part;
    2274             : }
    2275             : GEN
    2276        1722 : ifac_start(GEN n, int moebius)
    2277        1722 : { return ifac_start_hint(n,moebius,decomp_default_hint); }
    2278             : 
    2279             : /* Return next nonempty slot after 'here', NULL if none exist */
    2280             : static GEN
    2281       18192 : ifac_find(GEN partial)
    2282             : {
    2283       18192 :   GEN scan, end = partial + lg(partial);
    2284             : 
    2285             : #ifdef IFAC_DEBUG
    2286             :   ifac_check(partial, partial);
    2287             : #endif
    2288      133256 :   for (scan = partial+3; scan < end; scan += 3)
    2289      127162 :     if (VALUE(scan)) return scan;
    2290        6094 :   return NULL;
    2291             : }
    2292             : 
    2293             : /* Defragment: squeeze out unoccupied slots above *where. Unoccupied slots
    2294             :  * arise when a composite factor dissolves completely whilst dividing off a
    2295             :  * prime, or when ifac_resort() spots a coincidence and merges two factors.
    2296             :  * Update *where */
    2297             : static void
    2298         224 : ifac_defrag(GEN *partial, GEN *where)
    2299             : {
    2300         224 :   GEN scan_new = LAST(*partial), scan_old;
    2301             : 
    2302         672 :   for (scan_old = scan_new; scan_old >= *where; scan_old -= 3)
    2303             :   {
    2304         448 :     if (!VALUE(scan_old)) continue; /* empty slot */
    2305         448 :     if (scan_old < scan_new) SHALLOWCOPY(scan_old, scan_new);
    2306         448 :     scan_new -= 3; /* point at next slot to be written */
    2307             :   }
    2308         224 :   scan_new += 3; /* back up to last slot written */
    2309         224 :   *where = scan_new;
    2310        1344 :   while ((scan_new -= 3) > *partial) ifac_delete(scan_new); /* erase junk */
    2311         224 : }
    2312             : 
    2313             : /* Move to a larger main vector, updating *where if it points into it, and
    2314             :  * *partial in any case. Can be used as a specialized gcopy before
    2315             :  * a gerepileupto() (pass 0 as the new length). Normally, one would pass
    2316             :  * new_lg=1 to let this function guess the new size.  To be used sparingly.
    2317             :  * Complex version of ifac_defrag(), combined with reallocation.  If new_lg
    2318             :  * is 0, use the old length, so this acts just like gcopy except that the
    2319             :  * 'where' pointer is carried along; if it is 1, we make an educated guess.
    2320             :  * Exception:  If new_lg is 0, the vector is full to the brim, and the first
    2321             :  * entry is composite, we make it longer to avoid being called again a
    2322             :  * microsecond later. It is safe to call this with *where = NULL:
    2323             :  * if it doesn't point anywhere within the old structure, it is left alone */
    2324             : static void
    2325           0 : ifac_realloc(GEN *partial, GEN *where, long new_lg)
    2326             : {
    2327           0 :   long old_lg = lg(*partial);
    2328             :   GEN newpart, scan_new, scan_old;
    2329             : 
    2330           0 :   if (new_lg == 1)
    2331           0 :     new_lg = 2*old_lg - 6;        /* from 7 slots to 13 to 25... */
    2332           0 :   else if (new_lg <= old_lg)        /* includes case new_lg == 0 */
    2333             :   {
    2334           0 :     GEN first = *partial + 3;
    2335           0 :     new_lg = old_lg;
    2336             :     /* structure full and first entry composite or unknown */
    2337           0 :     if (VALUE(first) && (CLASS(first) == gen_0 || CLASS(first)==NULL))
    2338           0 :       new_lg += 6; /* give it a little more breathing space */
    2339             :   }
    2340           0 :   newpart = cgetg(new_lg, t_VEC);
    2341           0 :   if (DEBUGMEM >= 3)
    2342           0 :     err_printf("IFAC: new partial factorization structure (%ld slots)\n",
    2343           0 :                (new_lg - 3)/3);
    2344           0 :   MOEBIUS(newpart) = MOEBIUS(*partial);
    2345           0 :   icopyifstack(HINT(*partial), HINT(newpart));
    2346             :   /* Downward sweep through the old *partial. Pick up 'where' and carry it
    2347             :    * over if we pass it. (Only useful if it pointed at a nonempty slot.)
    2348             :    * Factors are COPY'd so that we again have a nice object (parent older
    2349             :    * than children, connected), except the one factor that may still be living
    2350             :    * in a clone where n originally was; exponents are similarly copied if they
    2351             :    * aren't global constants; class-of-factor fields are global constants so we
    2352             :    * need only copy them as pointers. Caller may then do a gerepileupto() */
    2353           0 :   scan_new = newpart + new_lg - 3; /* LAST(newpart) */
    2354           0 :   scan_old = *partial + old_lg - 3; /* LAST(*partial) */
    2355           0 :   for (; scan_old > *partial + 2; scan_old -= 3)
    2356             :   {
    2357           0 :     if (*where == scan_old) *where = scan_new;
    2358           0 :     if (!VALUE(scan_old)) continue; /* skip empty slots */
    2359           0 :     COPY(scan_old, scan_new); scan_new -= 3;
    2360             :   }
    2361           0 :   scan_new += 3; /* back up to last slot written */
    2362           0 :   while ((scan_new -= 3) > newpart) ifac_delete(scan_new);
    2363           0 :   *partial = newpart;
    2364           0 : }
    2365             : 
    2366             : /* Re-sort one (typically unknown) entry from washere to a new position,
    2367             :  * rotating intervening entries upward to fill the vacant space. If the new
    2368             :  * position is the same as the old one, or the new value of the entry coincides
    2369             :  * with a value already occupying a lower slot, then we just add exponents (and
    2370             :  * use the 'more known' class, and return 1 immediately when in Moebius mode).
    2371             :  * Slots between *where and washere must be in sorted order, so a sweep using
    2372             :  * this to re-sort several unknowns must proceed upward, see ifac_resort().
    2373             :  * Bubble-sort-of-thing sort. Won't be exercised frequently, so this is ok */
    2374             : static void
    2375         112 : ifac_sort_one(GEN *where, GEN washere)
    2376             : {
    2377         112 :   GEN old, scan = washere - 3;
    2378             :   GEN value, exponent, class0, class1;
    2379             :   long cmp_res;
    2380             : 
    2381         112 :   if (scan < *where) return; /* nothing to do, washere==*where */
    2382         112 :   value    = VALUE(washere);
    2383         112 :   exponent = EXPON(washere);
    2384         112 :   class0 = CLASS(washere);
    2385         112 :   cmp_res = -1; /* sentinel */
    2386         112 :   while (scan >= *where) /* at least once */
    2387             :   {
    2388         112 :     if (VALUE(scan))
    2389             :     { /* current slot nonempty, check against where */
    2390         112 :       cmp_res = cmpii(value, VALUE(scan));
    2391         112 :       if (cmp_res >= 0) break; /* have found where to stop */
    2392             :     }
    2393             :     /* copy current slot upward by one position and move pointers down */
    2394           0 :     SHALLOWCOPY(scan, scan+3);
    2395           0 :     scan -= 3;
    2396             :   }
    2397         112 :   scan += 3;
    2398             :   /* At this point there are the following possibilities:
    2399             :    * 1) cmp_res == -1. Either value is less than that at *where, or *where was
    2400             :    * pointing at vacant slots and any factors we saw en route were larger than
    2401             :    * value. At any rate, scan == *where now, and scan is pointing at an empty
    2402             :    * slot, into which we'll stash our entry.
    2403             :    * 2) cmp_res == 0. The entry at scan-3 is the one, we compare class0
    2404             :    * fields and add exponents, and put it all into the vacated scan slot,
    2405             :    * NULLing the one at scan-3 (and possibly updating *where).
    2406             :    * 3) cmp_res == 1. The slot at scan is the one to store our entry into. */
    2407         112 :   if (cmp_res)
    2408             :   {
    2409         112 :     if (cmp_res < 0 && scan != *where)
    2410           0 :       pari_err_BUG("ifact_sort_one [misaligned partial]");
    2411         112 :     INIT(scan, value, exponent, class0); return;
    2412             :   }
    2413             :   /* case cmp_res == 0: repeated factor detected */
    2414           0 :   if (DEBUGLEVEL >= 4)
    2415           0 :     err_printf("IFAC: repeated factor %Ps\n\tin ifac_sort_one\n", value);
    2416           0 :   old = scan - 3;
    2417             :   /* if old class0 was composite and new is prime, or vice versa, complain
    2418             :    * (and if one class0 was unknown and the other wasn't, use the known one) */
    2419           0 :   class1 = CLASS(old);
    2420           0 :   if (class0) /* should never be used */
    2421             :   {
    2422           0 :     if (class1)
    2423             :     {
    2424           0 :       if (class0 == gen_0 && class1 != gen_0)
    2425           0 :         pari_err_BUG("ifac_sort_one (composite = prime)");
    2426           0 :       else if (class0 != gen_0 && class1 == gen_0)
    2427           0 :         pari_err_BUG("ifac_sort_one (prime = composite)");
    2428           0 :       else if (class0 == gen_2)
    2429           0 :         CLASS(scan) = class0;
    2430             :     }
    2431             :     else
    2432           0 :       CLASS(scan) = class0;
    2433             :   }
    2434             :   /* else stay with the existing known class0 */
    2435           0 :   CLASS(scan) = class1;
    2436             :   /* in any case, add exponents */
    2437           0 :   if (EXPON(old) == gen_1 && exponent == gen_1)
    2438           0 :     EXPON(scan) = gen_2;
    2439             :   else
    2440           0 :     EXPON(scan) = addii(EXPON(old), exponent);
    2441             :   /* move the value over and null out the vacated slot below */
    2442           0 :   old = scan - 3;
    2443           0 :   *scan = *old;
    2444           0 :   ifac_delete(old);
    2445             :   /* finally, see whether *where should be pulled in */
    2446           0 :   if (old == *where) *where += 3;
    2447             : }
    2448             : 
    2449             : /* Sort all current unknowns downward to where they belong. Sweeps in the
    2450             :  * upward direction. Not needed after ifac_crack(), only when ifac_divide()
    2451             :  * returned true. Update *where. */
    2452             : static void
    2453         112 : ifac_resort(GEN *partial, GEN *where)
    2454             : {
    2455             :   GEN scan, end;
    2456         112 :   ifac_defrag(partial, where); end = LAST(*partial);
    2457         336 :   for (scan = *where; scan <= end; scan += 3)
    2458         224 :     if (VALUE(scan) && !CLASS(scan)) ifac_sort_one(where, scan); /*unknown*/
    2459         112 :   ifac_defrag(partial, where); /* remove newly created gaps */
    2460         112 : }
    2461             : 
    2462             : /* Let x be a t_INT known not to have small divisors (< 2^14). Return 0 if x
    2463             :  * is a proven composite. Return 1 if we believe it to be prime (fully proven
    2464             :  * prime if factor_proven is set).  */
    2465             : int
    2466       45748 : ifac_isprime(GEN x)
    2467             : {
    2468       45748 :   if (!BPSW_psp_nosmalldiv(x)) return 0; /* composite */
    2469       18725 :   if (factor_proven && ! BPSW_isprime(x))
    2470             :   {
    2471           0 :     pari_warn(warner,
    2472             :               "IFAC: pseudo-prime %Ps\n\tis not prime. PLEASE REPORT!\n", x);
    2473           0 :     return 0;
    2474             :   }
    2475       18725 :   return 1;
    2476             : }
    2477             : 
    2478             : static int
    2479       12047 : ifac_checkprime(GEN x)
    2480             : {
    2481       12047 :   int res = ifac_isprime(VALUE(x));
    2482       12047 :   CLASS(x) = res? gen_1: gen_0;
    2483       12047 :   if (DEBUGLEVEL>2) ifac_factor_dbg(x);
    2484       12047 :   return res;
    2485             : }
    2486             : 
    2487             : /* Determine primality or compositeness of all current unknowns, and set
    2488             :  * class Q primes to finished (class P) if everything larger is already
    2489             :  * known to be prime.  When after_crack >= 0, only look at the
    2490             :  * first after_crack things in the list (do nothing when it's 0) */
    2491             : static void
    2492        6292 : ifac_whoiswho(GEN *partial, GEN *where, long after_crack)
    2493             : {
    2494        6292 :   GEN scan, scan_end = LAST(*partial);
    2495             : 
    2496             : #ifdef IFAC_DEBUG
    2497             :   ifac_check(*partial, *where);
    2498             : #endif
    2499        6292 :   if (after_crack == 0) return;
    2500        5594 :   if (after_crack > 0) /* check at most after_crack entries */
    2501        5482 :     scan = *where + 3*(after_crack - 1); /* assert(scan <= scan_end) */
    2502             :   else
    2503         322 :     for (scan = scan_end; scan >= *where; scan -= 3)
    2504             :     {
    2505         217 :       if (CLASS(scan))
    2506             :       { /* known class of factor */
    2507         105 :         if (CLASS(scan) == gen_0) break;
    2508         105 :         if (CLASS(scan) == gen_1)
    2509             :         {
    2510           0 :           if (DEBUGLEVEL>=3)
    2511             :           {
    2512           0 :             err_printf("IFAC: factor %Ps\n\tis prime (no larger composite)\n",
    2513           0 :                        VALUE(*where));
    2514           0 :             err_printf("IFAC: prime %Ps\n\tappears with exponent = %ld\n",
    2515           0 :                        VALUE(*where), itos(EXPON(*where)));
    2516             :           }
    2517           0 :           CLASS(scan) = gen_2;
    2518             :         }
    2519         105 :         continue;
    2520             :       }
    2521         112 :       if (!ifac_checkprime(scan)) break; /* must disable Q-to-P */
    2522         105 :       CLASS(scan) = gen_2; /* P_i, finished prime */
    2523         105 :       if (DEBUGLEVEL>2) ifac_factor_dbg(scan);
    2524             :     }
    2525             :   /* go on, Q-to-P trick now disabled */
    2526       16747 :   for (; scan >= *where; scan -= 3)
    2527             :   {
    2528       11153 :     if (CLASS(scan)) continue;
    2529       11132 :     (void)ifac_checkprime(scan); /* Qj | Ck */
    2530             :   }
    2531             : }
    2532             : 
    2533             : /* Divide all current composites by first (prime, class Q) entry, updating its
    2534             :  * exponent, and turning it into a finished prime (class P).  Return 1 if any
    2535             :  * such divisions succeeded  (in Moebius mode, the update may then not have
    2536             :  * been completed), or 0 if none of them succeeded.  Doesn't modify *where.
    2537             :  * Here we normally do not check that the first entry is a not-finished
    2538             :  * prime.  Stack management: we may allocate a new exponent */
    2539             : static long
    2540       11364 : ifac_divide(GEN *partial, GEN *where, long moebius_mode)
    2541             : {
    2542       11364 :   GEN scan, scan_end = LAST(*partial);
    2543       11364 :   long res = 0, exponent, newexp, otherexp;
    2544             : 
    2545             : #ifdef IFAC_DEBUG
    2546             :   ifac_check(*partial, *where);
    2547             :   if (CLASS(*where) != gen_1)
    2548             :     pari_err_BUG("ifac_divide [division by composite or finished prime]");
    2549             :   if (!VALUE(*where)) pari_err_BUG("ifac_divide [division by nothing]");
    2550             : #endif
    2551       11364 :   newexp = exponent = itos(EXPON(*where));
    2552       11364 :   if (exponent > 1 && moebius_mode) return 1;
    2553             :   /* should've been caught by caller */
    2554             : 
    2555       17196 :   for (scan = *where+3; scan <= scan_end; scan += 3)
    2556             :   {
    2557        5839 :     if (CLASS(scan) != gen_0) continue; /* the other thing ain't composite */
    2558         452 :     otherexp = 0;
    2559             :     /* divide in place to keep stack clutter minimal */
    2560         571 :     while (dvdiiz(VALUE(scan), VALUE(*where), VALUE(scan)))
    2561             :     {
    2562         126 :       if (moebius_mode) return 1; /* immediately */
    2563         119 :       if (!otherexp) otherexp = itos(EXPON(scan));
    2564         119 :       newexp += otherexp;
    2565             :     }
    2566         445 :     if (newexp > exponent)        /* did anything happen? */
    2567             :     {
    2568         112 :       EXPON(*where) = (newexp == 2 ? gen_2 : utoipos(newexp));
    2569         112 :       exponent = newexp;
    2570         112 :       if (is_pm1((GEN)*scan)) /* factor dissolved completely */
    2571             :       {
    2572           0 :         ifac_delete(scan);
    2573           0 :         if (DEBUGLEVEL >= 4)
    2574           0 :           err_printf("IFAC: a factor was a power of another prime factor\n");
    2575             :       } else {
    2576         112 :         CLASS(scan) = NULL;        /* at any rate it's Unknown now */
    2577         112 :         if (DEBUGLEVEL >= 4)
    2578           0 :           err_printf("IFAC: a factor was divisible by another prime factor,\n"
    2579             :                      "\tleaving a cofactor = %Ps\n", VALUE(scan));
    2580             :       }
    2581         112 :       res = 1;
    2582         112 :       if (DEBUGLEVEL >= 5)
    2583           0 :         err_printf("IFAC: prime %Ps\n\tappears at least to the power %ld\n",
    2584           0 :                    VALUE(*where), newexp);
    2585             :     }
    2586             :   } /* for */
    2587       11357 :   CLASS(*where) = gen_2; /* make it a finished prime */
    2588       11357 :   if (DEBUGLEVEL >= 3)
    2589           0 :     err_printf("IFAC: prime %Ps\n\tappears with exponent = %ld\n",
    2590           0 :                VALUE(*where), newexp);
    2591       11357 :   return res;
    2592             : }
    2593             : 
    2594             : /* found out our integer was factor^exp. Update */
    2595             : static void
    2596        1006 : update_pow(GEN where, GEN factor, long exp, pari_sp *av)
    2597             : {
    2598        1006 :   GEN ex = EXPON(where);
    2599        1006 :   if (DEBUGLEVEL>3)
    2600           0 :     err_printf("IFAC: found %Ps =\n\t%Ps ^%ld\n", *where, factor, exp);
    2601        1006 :   affii(factor, VALUE(where)); set_avma(*av);
    2602        1006 :   if (ex == gen_1)
    2603         796 :   { EXPON(where) = exp == 2? gen_2: utoipos(exp); *av = avma; }
    2604         210 :   else if (ex == gen_2)
    2605         189 :   { EXPON(where) = utoipos(exp<<1); *av = avma; }
    2606             :   else
    2607          21 :     affsi(exp * itos(ex), EXPON(where));
    2608        1006 : }
    2609             : /* hint = 0 : Use a default strategy
    2610             :  * hint & 1 : avoid MPQS
    2611             :  * hint & 2 : avoid first-stage ECM (may fall back to ECM if MPQS gives up)
    2612             :  * hint & 4 : avoid Pollard and SQUFOF stages.
    2613             :  * hint & 8 : avoid final ECM; may flag a composite as prime. */
    2614             : #define get_hint(partial) (itos(HINT(*partial)) & 15)
    2615             : 
    2616             : /* Complete ifac_crack's job when a factoring engine splits the current factor
    2617             :  * into a product of three or more new factors. Makes room for them if
    2618             :  * necessary, sorts them, gives them the right exponents and class. Returns the
    2619             :  * number of factors actually written, which may be less than #facvec if there
    2620             :  * are duplicates. Vectors of factors (cf pollardbrent() or mpqs()) contain
    2621             :  * 'slots' of 3 GENs per factor, interpreted as in our partial factorization
    2622             :  * data structure. Thus engines can tell us what they already know about
    2623             :  * factors being prime/composite or appearing to a power larger than thefirst.
    2624             :  * Don't collect garbage.  No diagnostics: engine has printed what it found.
    2625             :  * facvec contains slots of three components per factor; repeated factors are
    2626             :  * allowed (their classes shouldn't contradict each other whereas their
    2627             :  * exponents will be added up) */
    2628             : static long
    2629        1213 : ifac_insert_multiplet(GEN *partial, GEN *where, GEN facvec, long moebius_mode)
    2630             : {
    2631        1213 :   long j,k=1, lfv=lg(facvec)-1, nf=lfv/3, room=(long)(*where-*partial);
    2632             :   /* one of the factors will go into the *where slot, so room is now 3 times
    2633             :    * the number of slots we can use */
    2634        1213 :   long needroom = lfv - room;
    2635        1213 :   GEN newexp, cur, sorted, auxvec = cgetg(nf+1, t_VEC), factor;
    2636        1213 :   long E = itos(EXPON(*where)); /* the old exponent */
    2637             : 
    2638        1213 :   if (DEBUGLEVEL >= 5) /* squfof may return a single squared factor as a set */
    2639           0 :     err_printf("IFAC: incorporating set of %ld factor(s)\n", nf);
    2640        1213 :   if (needroom > 0) ifac_realloc(partial, where, lg(*partial) + needroom);
    2641             : 
    2642             :   /* create sort permutation from the values of the factors */
    2643        3821 :   for (j=nf; j; j--) gel(auxvec,j) = gel(facvec,3*j-2);
    2644        1213 :   sorted = ZV_indexsort(auxvec);
    2645             :   /* store factors, beginning at *where, and catching any duplicates */
    2646        1213 :   cur = facvec + 3*sorted[nf]-2; /* adjust for triple spacing */
    2647        1213 :   VALUE(*where) = VALUE(cur);
    2648        1213 :   newexp = EXPON(cur);
    2649             :   /* if new exponent is 1, the old exponent already in place will do */
    2650        1213 :   if (newexp != gen_1) EXPON(*where) = mului(E,newexp);
    2651        1213 :   CLASS(*where) = CLASS(cur);
    2652        1213 :   if (DEBUGLEVEL >= 6) err_printf("\tstored (largest) factor no. %ld...\n", nf);
    2653             : 
    2654        2608 :   for (j=nf-1; j; j--)
    2655             :   {
    2656             :     GEN e;
    2657        1395 :     cur = facvec + 3*sorted[j]-2;
    2658        1395 :     factor = VALUE(cur);
    2659        1395 :     if (equalii(factor, VALUE(*where)))
    2660             :     {
    2661           0 :       if (DEBUGLEVEL >= 6)
    2662           0 :         err_printf("\tfactor no. %ld is a duplicate%s\n", j, (j>1? "...": ""));
    2663             :       /* update exponent, ignore class which would already have been set,
    2664             :        * then forget current factor */
    2665           0 :       newexp = EXPON(cur);
    2666           0 :       if (newexp != gen_1) /* new exp > 1 */
    2667           0 :         e = addiu(EXPON(*where), E * itou(newexp));
    2668           0 :       else if (EXPON(*where) == gen_1 && E == 1)
    2669           0 :         e = gen_2;
    2670             :       else
    2671           0 :         e = addiu(EXPON(*where), E);
    2672           0 :       EXPON(*where) = e;
    2673             : 
    2674           0 :       if (moebius_mode) return 0; /* stop now, with exponent updated */
    2675           0 :       continue;
    2676             :     }
    2677             : 
    2678        1395 :     *where -= 3;
    2679        1395 :     CLASS(*where) = CLASS(cur); /* class as given */
    2680        1395 :     newexp = EXPON(cur);
    2681        1395 :     if (newexp != gen_1) /* new exp > 1 */
    2682          28 :       e = (E == 1 && newexp == gen_2)? gen_2: mului(E, newexp);
    2683             :     else /* inherit parent's exponent */
    2684        1367 :       e = (E == 1 ? gen_1 : (E == 2 ? gen_2 : utoipos(E)));
    2685        1395 :     EXPON(*where) = e;
    2686             :     /* keep components younger than *partial */
    2687        1395 :     icopyifstack(factor, VALUE(*where));
    2688        1395 :     k++;
    2689        1395 :     if (DEBUGLEVEL >= 6)
    2690           0 :       err_printf("\tfactor no. %ld was unique%s\n", j, j>1? " (so far)...": "");
    2691             :   }
    2692        1213 :   return k;
    2693             : }
    2694             : 
    2695             : /* Split the first (composite) entry.  There _must_ already be room for another
    2696             :  * factor below *where, and *where is updated. Two cases:
    2697             :  * - entry = factor^k is a pure power: factor^k is inserted, leaving *where
    2698             :  *   unchanged;
    2699             :  * - entry = factor * cofactor (not necessarily coprime): both factors are
    2700             :  *   inserted in the correct order, updating *where
    2701             :  * The inserted factors class is set to unknown, they inherit the exponent
    2702             :  * (or a multiple thereof) of their ancestor.
    2703             :  *
    2704             :  * Returns number of factors written into the structure, normally 2 (1 if pure
    2705             :  * power, maybe > 2 if a factoring engine returned a vector of factors instead
    2706             :  * of a single factor). Can reallocate the data structure in the
    2707             :  * vector-of-factors case, not in the most common single-factor case.
    2708             :  * Stack housekeeping:  this routine may create one or more objects  (a new
    2709             :  * factor, or possibly several, and perhaps one or more new exponents > 2) */
    2710             : static long
    2711        6187 : ifac_crack(GEN *partial, GEN *where, long moebius_mode)
    2712             : {
    2713        6187 :   long cmp_res, hint = get_hint(partial);
    2714             :   GEN factor, exponent;
    2715             : 
    2716             : #ifdef IFAC_DEBUG
    2717             :   ifac_check(*partial, *where);
    2718             :   if (*where < *partial + 6)
    2719             :     pari_err_BUG("ifac_crack ['*where' out of bounds]");
    2720             :   if (!(VALUE(*where)) || typ(VALUE(*where)) != t_INT)
    2721             :     pari_err_BUG("ifac_crack [incorrect VALUE(*where)]");
    2722             :   if (CLASS(*where) != gen_0)
    2723             :     pari_err_BUG("ifac_crack [operand not known composite]");
    2724             : #endif
    2725             : 
    2726        6187 :   if (DEBUGLEVEL>2) {
    2727           0 :     err_printf("IFAC: cracking composite\n\t%Ps\n", **where);
    2728           0 :     if (DEBUGLEVEL>3) err_printf("IFAC: checking for pure square\n");
    2729             :   }
    2730             :   /* MPQS cannot factor prime powers. Look for pure powers even if MPQS is
    2731             :    * blocked by hint: fast and useful in bounded factorization */
    2732             :   {
    2733             :     forprime_t T;
    2734        6187 :     ulong exp = 1, mask = 7;
    2735        6187 :     long good = 0;
    2736        6187 :     pari_sp av = avma;
    2737        6187 :     (void)u_forprime_init(&T, 11, ULONG_MAX);
    2738             :     /* crack squares */
    2739        7144 :     while (Z_issquareall(VALUE(*where), &factor))
    2740             :     {
    2741         964 :       good = 1; /* remember we succeeded once */
    2742         964 :       update_pow(*where, factor, 2, &av);
    2743        1662 :       if (moebius_mode) return 0; /* no need to carry on */
    2744             :     }
    2745        6222 :     while ( (exp = is_357_power(VALUE(*where), &factor, &mask)) )
    2746             :     {
    2747          42 :       good = 1; /* remember we succeeded once */
    2748          42 :       update_pow(*where, factor, exp, &av);
    2749          42 :       if (moebius_mode) return 0; /* no need to carry on */
    2750             :     }
    2751             :     /* cutoff at 14 bits as trial division must have found everything below */
    2752        6180 :     while ( (exp = is_pth_power(VALUE(*where), &factor, &T, 15)) )
    2753             :     {
    2754           0 :       good = 1; /* remember we succeeded once */
    2755           0 :       update_pow(*where, factor, exp, &av);
    2756           0 :       if (moebius_mode) return 0; /* no need to carry on */
    2757             :     }
    2758             : 
    2759        6180 :     if (good && hint != 15 && ifac_checkprime(*where))
    2760             :     { /* our composite was a prime power */
    2761         698 :       if (DEBUGLEVEL>3)
    2762           0 :         err_printf("IFAC: factor %Ps\n\tis prime\n", VALUE(*where));
    2763         698 :       return 0; /* bypass subsequent ifac_whoiswho() call */
    2764             :     }
    2765             :   } /* pure power stage */
    2766             : 
    2767        5482 :   factor = NULL;
    2768        5482 :   if (!(hint & 4))
    2769             :   { /* pollardbrent() Rho usually gets a first chance */
    2770        5433 :     if (DEBUGLEVEL >= 4) err_printf("IFAC: trying Pollard-Brent rho method\n");
    2771        5433 :     factor = pollardbrent(VALUE(*where));
    2772        5433 :     if (!factor)
    2773             :     { /* Shanks' squfof() */
    2774        3413 :       if (DEBUGLEVEL >= 4)
    2775           0 :         err_printf("IFAC: trying Shanks' SQUFOF, will fail silently if input\n"
    2776             :                    "      is too large for it.\n");
    2777        3413 :       factor = squfof(VALUE(*where));
    2778             :     }
    2779             :   }
    2780        5482 :   if (!factor && !(hint & 2))
    2781             :   { /* First ECM stage */
    2782        1084 :     if (DEBUGLEVEL >= 4) err_printf("IFAC: trying Lenstra-Montgomery ECM\n");
    2783        1084 :     factor = ellfacteur(VALUE(*where), 0); /* do not insist */
    2784             :   }
    2785        5482 :   if (!factor && !(hint & 1))
    2786             :   { /* MPQS stage */
    2787        1094 :     if (DEBUGLEVEL >= 4) err_printf("IFAC: trying MPQS\n");
    2788        1094 :     factor = mpqs(VALUE(*where));
    2789             :   }
    2790        5482 :   if (!factor)
    2791             :   {
    2792          21 :     if (!(hint & 8))
    2793             :     { /* still no luck? Final ECM stage, guaranteed to succeed */
    2794          14 :       if (DEBUGLEVEL >= 4)
    2795           0 :         err_printf("IFAC: forcing ECM, may take some time\n");
    2796          14 :       factor = ellfacteur(VALUE(*where), 1);
    2797             :     }
    2798             :     else
    2799             :     { /* limited factorization */
    2800           7 :       if (DEBUGLEVEL >= 2)
    2801             :       {
    2802           0 :         if (hint != 15)
    2803           0 :           pari_warn(warner, "IFAC: unfactored composite declared prime");
    2804             :         else
    2805           0 :           pari_warn(warner, "IFAC: untested integer declared prime");
    2806             : 
    2807             :         /* don't print it out at level 3 or above, where it would appear
    2808             :          * several times before and after this message already */
    2809           0 :         if (DEBUGLEVEL == 2) err_printf("\t%Ps\n", VALUE(*where));
    2810             :       }
    2811           7 :       CLASS(*where) = gen_1; /* might as well trial-divide by it... */
    2812           7 :       return 1;
    2813             :     }
    2814             :   }
    2815        5475 :   if (typ(factor) == t_VEC) /* delegate this case */
    2816        1213 :     return ifac_insert_multiplet(partial, where, factor, moebius_mode);
    2817             :   /* typ(factor) == t_INT */
    2818             :   /* got single integer back:  work out the cofactor (in place) */
    2819        4262 :   if (!dvdiiz(VALUE(*where), factor, VALUE(*where)))
    2820             :   {
    2821           0 :     err_printf("IFAC: factoring %Ps\n", VALUE(*where));
    2822           0 :     err_printf("\tyielded 'factor' %Ps\n\twhich isn't!\n", factor);
    2823           0 :     pari_err_BUG("factoring");
    2824             :   }
    2825             :   /* factoring engines report the factor found; tell about the cofactor */
    2826        4262 :   if (DEBUGLEVEL >= 4) err_printf("IFAC: cofactor = %Ps\n", VALUE(*where));
    2827             : 
    2828             :   /* The two factors are 'factor' and VALUE(*where), find out which is larger */
    2829        4262 :   cmp_res = cmpii(factor, VALUE(*where));
    2830        4262 :   CLASS(*where) = NULL; /* mark factor /cofactor 'unknown' */
    2831        4262 :   exponent = EXPON(*where);
    2832        4262 :   *where -= 3;
    2833        4262 :   CLASS(*where) = NULL; /* mark factor /cofactor 'unknown' */
    2834        4262 :   icopyifstack(exponent, EXPON(*where));
    2835        4262 :   if (cmp_res < 0)
    2836        3800 :     VALUE(*where) = factor; /* common case */
    2837         462 :   else if (cmp_res > 0)
    2838             :   { /* factor > cofactor, rearrange */
    2839         462 :     GEN old = *where + 3;
    2840         462 :     VALUE(*where) = VALUE(old); /* move cofactor pointer to lowest slot */
    2841         462 :     VALUE(old) = factor; /* save factor */
    2842             :   }
    2843           0 :   else pari_err_BUG("ifac_crack [Z_issquareall miss]");
    2844        4262 :   return 2;
    2845             : }
    2846             : 
    2847             : /* main loop:  iterate until smallest entry is a finished prime;  returns
    2848             :  * a 'where' pointer, or NULL if nothing left, or gen_0 in Moebius mode if
    2849             :  * we aren't squarefree */
    2850             : static GEN
    2851       17238 : ifac_main(GEN *partial)
    2852             : {
    2853       17238 :   const long moebius_mode = !!MOEBIUS(*partial);
    2854       17238 :   GEN here = ifac_find(*partial);
    2855             :   long nf;
    2856             : 
    2857       17238 :   if (!here) return NULL; /* nothing left */
    2858             :   /* loop until first entry is a finished prime.  May involve reallocations,
    2859             :    * thus updates of *partial */
    2860       28999 :   while (CLASS(here) != gen_2)
    2861             :   {
    2862       17551 :     if (CLASS(here) == gen_0) /* composite: crack it */
    2863             :     { /* make sure there's room for another factor */
    2864        6187 :       if (here < *partial + 6)
    2865             :       {
    2866           0 :         ifac_defrag(partial, &here);
    2867           0 :         if (here < *partial + 6) ifac_realloc(partial, &here, 1); /* no luck */
    2868             :       }
    2869        6187 :       nf = ifac_crack(partial, &here, moebius_mode);
    2870        6187 :       if (moebius_mode && EXPON(here) != gen_1) /* that was a power */
    2871             :       {
    2872           7 :         if (DEBUGLEVEL >= 3)
    2873           0 :           err_printf("IFAC: main loop: repeated new factor\n\t%Ps\n", *here);
    2874           7 :         return gen_0;
    2875             :       }
    2876             :       /* deal with the new unknowns.  No sort: ifac_crack did it */
    2877        6180 :       ifac_whoiswho(partial, &here, nf);
    2878        6180 :       continue;
    2879             :     }
    2880       11364 :     if (CLASS(here) == gen_1) /* prime but not yet finished: finish it */
    2881             :     {
    2882       11364 :       if (ifac_divide(partial, &here, moebius_mode))
    2883             :       {
    2884         119 :         if (moebius_mode)
    2885             :         {
    2886           7 :           if (DEBUGLEVEL >= 3)
    2887           0 :             err_printf("IFAC: main loop: another factor was divisible by\n"
    2888             :                        "\t%Ps\n", *here);
    2889           7 :           return gen_0;
    2890             :         }
    2891         112 :         ifac_resort(partial, &here); /* sort new cofactors down */
    2892         112 :         ifac_whoiswho(partial, &here, -1);
    2893             :       }
    2894       11357 :       continue;
    2895             :     }
    2896           0 :     pari_err_BUG("ifac_main [nonexistent factor class]");
    2897             :   } /* while */
    2898       11448 :   if (moebius_mode && EXPON(here) != gen_1)
    2899             :   {
    2900           0 :     if (DEBUGLEVEL >= 3)
    2901           0 :       err_printf("IFAC: after main loop: repeated old factor\n\t%Ps\n", *here);
    2902           0 :     return gen_0;
    2903             :   }
    2904       11448 :   if (DEBUGLEVEL >= 4)
    2905             :   {
    2906           0 :     nf = (*partial + lg(*partial) - here - 3)/3;
    2907           0 :     if (nf)
    2908           0 :       err_printf("IFAC: main loop: %ld factor%s left\n", nf, (nf>1)? "s": "");
    2909             :     else
    2910           0 :       err_printf("IFAC: main loop: this was the last factor\n");
    2911             :   }
    2912       11448 :   if (factor_add_primes && !(get_hint(partial) & 8))
    2913             :   {
    2914           0 :     GEN p = VALUE(here);
    2915           0 :     if (lgefint(p)>3 || uel(p,2) > 0x1000000UL) (void)addprimes(p);
    2916             :   }
    2917       11448 :   return here;
    2918             : }
    2919             : 
    2920             : /* Encapsulated routines */
    2921             : 
    2922             : /* prime/exponent pairs need to appear contiguously on the stack, but we also
    2923             :  * need our data structure somewhere, and we don't know in advance how many
    2924             :  * primes will turn up.  The following discipline achieves this:  When
    2925             :  * ifac_decomp() is called, n should point at an object older than the oldest
    2926             :  * small prime/exponent pair  (ifactor() guarantees this).
    2927             :  * We allocate sufficient space to accommodate several pairs -- eleven pairs
    2928             :  * ought to fit in a space not much larger than n itself -- before calling
    2929             :  * ifac_start().  If we manage to complete the factorization before we run out
    2930             :  * of space, we free the data structure and cull the excess reserved space
    2931             :  * before returning.  When we do run out, we have to leapfrog to generate more
    2932             :  * (guesstimating the requirements from what is left in the partial
    2933             :  * factorization structure);  room for fresh pairs is allocated at the head of
    2934             :  * the stack, followed by an ifac_realloc() to reconnect the data structure and
    2935             :  * move it out of the way, followed by a few pointer tweaks to connect the new
    2936             :  * pairs space to the old one. This whole affair translates into a surprisingly
    2937             :  * compact routine. */
    2938             : 
    2939             : /* find primary factors of n; destroy n */
    2940             : static long
    2941        3247 : ifac_decomp(GEN n, long hint)
    2942             : {
    2943        3247 :   pari_sp av = avma;
    2944        3247 :   long nb = 0;
    2945        3247 :   GEN part, here, workspc, pairs = (GEN)av;
    2946             : 
    2947             :   /* workspc will be doled out in pairs of smaller t_INTs. For n = prod p^{e_p}
    2948             :    * (p not necessarily prime), need room to store all p and e_p [ cgeti(3) ],
    2949             :    * bounded by
    2950             :    *    sum_{p | n} ( log_{2^BIL} (p) + 6 ) <= log_{2^BIL} n + 6 log_2 n */
    2951        3247 :   workspc = new_chunk((expi(n) + 1) * 7);
    2952        3247 :   part = ifac_start_hint(n, 0, hint);
    2953             :   for (;;)
    2954             :   {
    2955        9660 :     here = ifac_main(&part);
    2956        9660 :     if (!here) break;
    2957        6413 :     if (gc_needed(av,1))
    2958             :     {
    2959             :       long offset;
    2960           0 :       if(DEBUGMEM>1)
    2961             :       {
    2962           0 :         pari_warn(warnmem,"[2] ifac_decomp");
    2963           0 :         ifac_print(part, here);
    2964             :       }
    2965           0 :       ifac_realloc(&part, &here, 0);
    2966           0 :       offset = here - part;
    2967           0 :       part = gerepileupto((pari_sp)workspc, part);
    2968           0 :       here = part + offset;
    2969             :     }
    2970        6413 :     nb++;
    2971        6413 :     pairs = icopy_avma(VALUE(here), (pari_sp)pairs);
    2972        6413 :     pairs = icopy_avma(EXPON(here), (pari_sp)pairs);
    2973        6413 :     ifac_delete(here);
    2974             :   }
    2975        3247 :   set_avma((pari_sp)pairs);
    2976        3247 :   if (DEBUGLEVEL >= 3)
    2977           0 :     err_printf("IFAC: found %ld large prime (power) factor%s.\n",
    2978             :                nb, (nb>1? "s": ""));
    2979        3247 :   return nb;
    2980             : }
    2981             : 
    2982             : /***********************************************************************/
    2983             : /**            ARITHMETIC FUNCTIONS WITH EARLY-ABORT                  **/
    2984             : /**  needing direct access to the factoring machinery to avoid work:  **/
    2985             : /**  e.g. if we find a square factor, moebius returns 0, core doesn't **/
    2986             : /**  need to factor it, etc.                                          **/
    2987             : /***********************************************************************/
    2988             : /* memory management */
    2989             : static void
    2990           0 : ifac_GC(pari_sp av, GEN *part)
    2991             : {
    2992           0 :   GEN here = NULL;
    2993           0 :   if(DEBUGMEM>1) pari_warn(warnmem,"ifac_xxx");
    2994           0 :   ifac_realloc(part, &here, 0);
    2995           0 :   *part = gerepileupto(av, *part);
    2996           0 : }
    2997             : 
    2998             : /* destroys n */
    2999             : static long
    3000         211 : ifac_moebius(GEN n)
    3001             : {
    3002         211 :   long mu = 1;
    3003         211 :   pari_sp av = avma;
    3004         211 :   GEN part = ifac_start(n, 1);
    3005             :   for(;;)
    3006         394 :   {
    3007             :     long v;
    3008             :     GEN p;
    3009         605 :     if (!ifac_next(&part,&p,&v)) return v? 0: mu;
    3010         394 :     mu = -mu;
    3011         394 :     if (gc_needed(av,1)) ifac_GC(av,&part);
    3012             :   }
    3013             : }
    3014             : 
    3015             : int
    3016         658 : ifac_read(GEN part, GEN *p, long *e)
    3017             : {
    3018         658 :   GEN here = ifac_find(part);
    3019         658 :   if (!here) return 0;
    3020         340 :   *p = VALUE(here);
    3021         340 :   *e = EXPON(here)[2];
    3022         340 :   return 1;
    3023             : }
    3024             : void
    3025         296 : ifac_skip(GEN part)
    3026             : {
    3027         296 :   GEN here = ifac_find(part);
    3028         296 :   if (here) ifac_delete(here);
    3029         296 : }
    3030             : 
    3031             : /* destroys n */
    3032             : static int
    3033           7 : ifac_ispowerful(GEN n)
    3034             : {
    3035           7 :   pari_sp av = avma;
    3036           7 :   GEN part = ifac_start(n, 0);
    3037             :   for(;;)
    3038           7 :   {
    3039             :     long e;
    3040             :     GEN p;
    3041          14 :     if (!ifac_read(part,&p,&e)) return 1;
    3042             :     /* power: skip */
    3043           7 :     if (e != 1 || Z_isanypower(p,NULL)) { ifac_skip(part); continue; }
    3044           0 :     if (!ifac_next(&part,&p,&e)) return 1;
    3045           0 :     if (e == 1) return 0;
    3046           0 :     if (gc_needed(av,1)) ifac_GC(av,&part);
    3047             :   }
    3048             : }
    3049             : /* destroys n */
    3050             : static GEN
    3051         311 : ifac_core(GEN n)
    3052             : {
    3053         311 :   GEN m = gen_1, c = cgeti(lgefint(n));
    3054         311 :   pari_sp av = avma;
    3055         311 :   GEN part = ifac_start(n, 0);
    3056             :   for(;;)
    3057         333 :   {
    3058             :     long e;
    3059             :     GEN p;
    3060         644 :     if (!ifac_read(part,&p,&e)) return m;
    3061             :     /* square: skip */
    3062         333 :     if (!odd(e) || Z_issquare(p)) { ifac_skip(part); continue; }
    3063          44 :     if (!ifac_next(&part,&p,&e)) return m;
    3064          44 :     if (odd(e)) m = mulii(m, p);
    3065          44 :     if (gc_needed(av,1)) { affii(m,c); m=c; ifac_GC(av,&part); }
    3066             :   }
    3067             : }
    3068             : 
    3069             : /* Where to stop trial dividing in factorization. Guaranteed >= 2^14 */
    3070             : ulong
    3071      832642 : tridiv_bound(GEN n)
    3072             : {
    3073      832642 :   ulong l = (ulong)expi(n) + 1;
    3074      832652 :   if (l <= 32)  return 1UL<<14;
    3075       72918 :   if (l <= 512) return (l-16) << 10;
    3076         642 :   return 1UL<<19; /* Rho is generally faster above this */
    3077             : }
    3078             : 
    3079             : /* return a value <= (48 << 10) = 49152 < primelinit */
    3080             : static ulong
    3081    16513700 : utridiv_bound(ulong n)
    3082             : {
    3083             : #ifdef LONG_IS_64BIT
    3084    14125502 :   if (n & HIGHMASK)
    3085       89654 :     return ((ulong)expu(n) + 1 - 16) << 10;
    3086             : #else
    3087             :   (void)n;
    3088             : #endif
    3089    16424046 :   return 1UL<<14;
    3090             : }
    3091             : 
    3092             : /* destroys n */
    3093             : static void
    3094        1174 : ifac_factoru(GEN n, long hint, GEN P, GEN E, long *pi)
    3095             : {
    3096        1174 :   GEN part = ifac_start_hint(n, 0, hint);
    3097             :   for(;;)
    3098        2288 :   {
    3099             :     long v;
    3100             :     GEN p;
    3101        3462 :     if (!ifac_next(&part,&p,&v)) return;
    3102        2288 :     P[*pi] = itou(p);
    3103        2288 :     E[*pi] = v;
    3104        2288 :     (*pi)++;
    3105             :   }
    3106             : }
    3107             : /* destroys n */
    3108             : static long
    3109        1074 : ifac_moebiusu(GEN n)
    3110             : {
    3111        1074 :   GEN part = ifac_start(n, 1);
    3112        1074 :   long s = 1;
    3113             :   for(;;)
    3114        2148 :   {
    3115             :     long v;
    3116             :     GEN p;
    3117        3222 :     if (!ifac_next(&part,&p,&v)) return v? 0: s;
    3118        2148 :     s = -s;
    3119             :   }
    3120             : }
    3121             : 
    3122             : INLINE ulong
    3123   672454240 : u_forprime_next_fast(forprime_t *T)
    3124             : {
    3125   672454240 :   if (*(T->d))
    3126             :   {
    3127   672458932 :     NEXT_PRIME_VIADIFF(T->p, T->d);
    3128   672458932 :     return T->p > T->b ? 0: T->p;
    3129             :   }
    3130       17849 :   return u_forprime_next(T);
    3131             : }
    3132             : 
    3133             : /* Factor n and output [p,e] where
    3134             :  * p, e are vecsmall with n = prod{p[i]^e[i]}. If all != 0:
    3135             :  * if pU is not NULL, set it to unfactored composite; else include it
    3136             :  * in factorization */
    3137             : static GEN
    3138    16260754 : factoru_sign(ulong n, ulong all, long hint, ulong *pU1, ulong *pU2)
    3139             : {
    3140             :   GEN f, E, E2, P, P2;
    3141             :   pari_sp av;
    3142             :   ulong p, lim;
    3143             :   long i;
    3144             :   forprime_t S;
    3145             : 
    3146    16260754 :   if (pU1) *pU1 = *pU2 = 1;
    3147    16260754 :   if (n == 0) retmkvec2(mkvecsmall(0), mkvecsmall(1));
    3148    16260754 :   if (n == 1) retmkvec2(cgetg(1,t_VECSMALL), cgetg(1,t_VECSMALL));
    3149             : 
    3150    15891445 :   f = cgetg(3,t_VEC); av = avma;
    3151    15891521 :   lim = all; if (!lim) lim = utridiv_bound(n);
    3152             :   /* enough room to store <= 15 primes and exponents (OK if n < 2^64) */
    3153    15891509 :   (void)new_chunk(16*2);
    3154    15891491 :   P = cgetg(16, t_VECSMALL); i = 1;
    3155    15891526 :   E = cgetg(16, t_VECSMALL);
    3156    15891578 :   if (lim > 2)
    3157             :   {
    3158    15891581 :     long v = vals(n), oldi;
    3159    15891502 :     if (v)
    3160             :     {
    3161     9926351 :       P[1] = 2; E[1] = v; i = 2;
    3162     9926351 :       n >>= v; if (n == 1) goto END;
    3163             :     }
    3164    13168756 :     u_forprime_init(&S, 3, lim-1);
    3165    13168913 :     oldi = i;
    3166   125495729 :     while ( (p = u_forprime_next_fast(&S)) )
    3167             :     {
    3168             :       int stop;
    3169             :       /* tiny integers without small factors are often primes */
    3170   125493759 :       if (p == 673)
    3171             :       {
    3172       34413 :         oldi = i;
    3173    13180124 :         if (uisprime_661(n)) { P[i] = n; E[i] = 1; i++; goto END; }
    3174             :       }
    3175   125472451 :       v = u_lvalrem_stop(&n, p, &stop);
    3176   125472527 :       if (v) {
    3177    12212601 :         P[i] = p;
    3178    12212601 :         E[i] = v; i++;
    3179             :       }
    3180   125472527 :       if (stop) {
    3181    13145711 :         if (n != 1) { P[i] = n; E[i] = 1; i++; }
    3182    13145711 :         goto END;
    3183             :       }
    3184             :     }
    3185        2073 :     if (oldi != i && !all && uisprime_661(n))
    3186         258 :     { P[i] = n; E[i] = 1; i++; goto END; }
    3187             :   }
    3188        1812 :   if (all)
    3189             :   { /* smallfact: look for easy pure powers then stop */
    3190             : #ifdef LONG_IS_64BIT
    3191         630 :     ulong mask = all > 563 ? (all > 7129 ? 1: 3): 7;
    3192             : #else
    3193           8 :     ulong mask = all > 22 ? (all > 83 ? 1: 3): 7;
    3194             : #endif
    3195         638 :     long k = 1, ex;
    3196        1108 :     while (uissquareall(n, &n)) k <<= 1;
    3197         651 :     while ( (ex = uis_357_power(n, &n, &mask)) ) k *= ex;
    3198         638 :     if (pU1 && !uisprime(n))
    3199         236 :     { *pU1 = n; *pU2 = (ulong)k; }
    3200             :     else
    3201         402 :     { P[i] = n; E[i] = k; i++; }
    3202         638 :     goto END;
    3203             :   }
    3204             :   {
    3205             :     GEN perm;
    3206        1174 :     ifac_factoru(utoipos(n), hint, P, E, &i);
    3207        1174 :     setlg(P, i);
    3208        1174 :     perm = vecsmall_indexsort(P);
    3209        1174 :     P = vecsmallpermute(P, perm);
    3210        1174 :     E = vecsmallpermute(E, perm);
    3211             :   }
    3212    15891835 : END:
    3213    15891835 :   set_avma(av);
    3214    15891767 :   P2 = cgetg(i, t_VECSMALL); gel(f,1) = P2;
    3215    15891720 :   E2 = cgetg(i, t_VECSMALL); gel(f,2) = E2;
    3216    49008286 :   while (--i >= 1) { P2[i] = P[i]; E2[i] = E[i]; }
    3217    15891715 :   return f;
    3218             : }
    3219             : GEN
    3220     5534560 : factoru(ulong n)
    3221     5534560 : { return factoru_sign(n, 0, decomp_default_hint, NULL, NULL); }
    3222             : 
    3223             : ulong
    3224           0 : radicalu(ulong n)
    3225             : {
    3226           0 :   pari_sp av = avma;
    3227           0 :   return gc_long(av, zv_prod(gel(factoru(n),1)));
    3228             : }
    3229             : 
    3230             : long
    3231       54173 : moebiusu_fact(GEN f)
    3232             : {
    3233       54173 :   GEN E = gel(f,2);
    3234       54173 :   long i, l = lg(E);
    3235       93541 :   for (i = 1; i < l; i++)
    3236       57813 :     if (E[i] > 1) return 0;
    3237       35728 :   return odd(l)? 1: -1;
    3238             : }
    3239             : 
    3240             : long
    3241     2505970 : moebiusu(ulong n)
    3242             : {
    3243             :   pari_sp av;
    3244             :   ulong p;
    3245             :   long s, v, test_prime;
    3246             :   forprime_t S;
    3247             : 
    3248     2505970 :   switch(n)
    3249             :   {
    3250           0 :     case 0: (void)check_arith_non0(gen_0,"moebius");/*error*/
    3251      568653 :     case 1: return  1;
    3252      106665 :     case 2: return -1;
    3253             :   }
    3254     1849191 :   v = vals(n);
    3255     1844657 :   if (v == 0)
    3256     1733242 :     s = 1;
    3257             :   else
    3258             :   {
    3259      111415 :     if (v > 1) return 0;
    3260       23322 :     n >>= 1;
    3261       23322 :     s = -1;
    3262             :   }
    3263     1756564 :   av = avma;
    3264     1756564 :   u_forprime_init(&S, 3, utridiv_bound(n));
    3265     1767560 :   test_prime = 0;
    3266    30926981 :   while ((p = u_forprime_next_fast(&S)))
    3267             :   {
    3268             :     int stop;
    3269             :     /* tiny integers without small factors are often primes */
    3270    30929960 :     if (p == 673)
    3271             :     {
    3272        3752 :       test_prime = 0;
    3273     1775795 :       if (uisprime_661(n)) return gc_long(av,-s);
    3274             :     }
    3275    30928512 :     v = u_lvalrem_stop(&n, p, &stop);
    3276    30927755 :     if (v) {
    3277     1320382 :       if (v > 1) return gc_long(av,0);
    3278     1138429 :       test_prime = 1;
    3279     1138429 :       s = -s;
    3280             :     }
    3281    30745802 :     if (stop) return gc_long(av, n==1? s: -s);
    3282             :   }
    3283        1270 :   set_avma(av);
    3284        1524 :   if (test_prime && uisprime_661(n)) return -s;
    3285             :   else
    3286             :   {
    3287        1074 :     long t = ifac_moebiusu(utoipos(n));
    3288        1074 :     set_avma(av);
    3289        1074 :     if (t == 0) return 0;
    3290        1074 :     return (s == t)? 1: -1;
    3291             :   }
    3292             : }
    3293             : 
    3294             : long
    3295       55160 : moebius(GEN n)
    3296             : {
    3297       55160 :   pari_sp av = avma;
    3298             :   GEN F;
    3299             :   ulong p;
    3300             :   long i, l, s, v;
    3301             :   forprime_t S;
    3302             : 
    3303       55160 :   if ((F = check_arith_non0(n,"moebius")))
    3304             :   {
    3305             :     GEN E;
    3306         752 :     F = clean_Z_factor(F);
    3307         728 :     E = gel(F,2);
    3308         728 :     l = lg(E);
    3309        1428 :     for(i = 1; i < l; i++)
    3310         980 :       if (!equali1(gel(E,i))) return gc_long(av,0);
    3311         448 :     return gc_long(av, odd(l)? 1: -1);
    3312             :   }
    3313       54803 :   if (lgefint(n) == 3) return moebiusu(uel(n,2));
    3314         808 :   p = mod4(n); if (!p) return 0;
    3315         808 :   if (p == 2) { s = -1; n = shifti(n, -1); } else { s = 1; n = icopy(n); }
    3316         808 :   setabssign(n);
    3317             : 
    3318         808 :   u_forprime_init(&S, 3, tridiv_bound(n));
    3319     2322026 :   while ((p = u_forprime_next_fast(&S)))
    3320             :   {
    3321             :     int stop;
    3322     2321446 :     v = Z_lvalrem_stop(&n, p, &stop);
    3323     2321446 :     if (v)
    3324             :     {
    3325        1540 :       if (v > 1) return gc_long(av,0);
    3326        1312 :       s = -s;
    3327        1312 :       if (stop) return gc_long(av, is_pm1(n)? s: -s);
    3328             :     }
    3329             :   }
    3330         580 :   l = lg(primetab);
    3331         590 :   for (i = 1; i < l; i++)
    3332             :   {
    3333          25 :     v = Z_pvalrem(n, gel(primetab,i), &n);
    3334          25 :     if (v)
    3335             :     {
    3336          25 :       if (v > 1) return gc_long(av,0);
    3337          11 :       s = -s;
    3338          11 :       if (is_pm1(n)) return gc_long(av,s);
    3339             :     }
    3340             :   }
    3341         565 :   if (ifac_isprime(n)) return gc_long(av,-s);
    3342             :   /* large composite without small factors */
    3343         211 :   v = ifac_moebius(n);
    3344         211 :   return gc_long(av, s < 0? -v: v); /* correct also if v==0 */
    3345             : }
    3346             : 
    3347             : long
    3348        1708 : ispowerful(GEN n)
    3349             : {
    3350        1708 :   pari_sp av = avma;
    3351             :   GEN F;
    3352             :   ulong p, bound;
    3353             :   long i, l, v;
    3354             :   forprime_t S;
    3355             : 
    3356        1708 :   if ((F = check_arith_all(n, "ispowerful")))
    3357             :   {
    3358         742 :     GEN p, P = gel(F,1), E = gel(F,2);
    3359         742 :     if (lg(P) == 1) return 1; /* 1 */
    3360         728 :     p = gel(P,1);
    3361         728 :     if (!signe(p)) return 1; /* 0 */
    3362         707 :     i = is_pm1(p)? 2: 1; /* skip -1 */
    3363         707 :     l = lg(E);
    3364         980 :     for (; i < l; i++)
    3365         847 :       if (equali1(gel(E,i))) return 0;
    3366         133 :     return 1;
    3367             :   }
    3368         966 :   if (!signe(n)) return 1;
    3369             : 
    3370         952 :   if (mod4(n) == 2) return 0;
    3371         623 :   n = shifti(n, -vali(n));
    3372         623 :   if (is_pm1(n)) return 1;
    3373         546 :   setabssign(n);
    3374         546 :   bound = tridiv_bound(n);
    3375         546 :   u_forprime_init(&S, 3, bound);
    3376      307797 :   while ((p = u_forprime_next_fast(&S)))
    3377             :   {
    3378             :     int stop;
    3379      307790 :     v = Z_lvalrem_stop(&n, p, &stop);
    3380      307790 :     if (v)
    3381             :     {
    3382         742 :       if (v == 1) return gc_long(av,0);
    3383         203 :       if (stop) return gc_long(av, is_pm1(n));
    3384             :     }
    3385             :   }
    3386           7 :   l = lg(primetab);
    3387           7 :   for (i = 1; i < l; i++)
    3388             :   {
    3389           0 :     v = Z_pvalrem(n, gel(primetab,i), &n);
    3390           0 :     if (v)
    3391             :     {
    3392           0 :       if (v == 1) return gc_long(av,0);
    3393           0 :       if (is_pm1(n)) return gc_long(av,1);
    3394             :     }
    3395             :   }
    3396             :   /* no need to factor: must be p^2 or not powerful */
    3397           7 :   if (cmpii(powuu(bound+1, 3), n) > 0) return gc_long(av,  Z_issquare(n));
    3398             : 
    3399           7 :   if (ifac_isprime(n)) return gc_long(av,0);
    3400             :   /* large composite without small factors */
    3401           7 :   return gc_long(av, ifac_ispowerful(n));
    3402             : }
    3403             : 
    3404             : ulong
    3405       59032 : coreu_fact(GEN f)
    3406             : {
    3407       59032 :   GEN P = gel(f,1), E = gel(f,2);
    3408       59032 :   long i, l = lg(P), m = 1;
    3409      106418 :   for (i = 1; i < l; i++)
    3410             :   {
    3411       47386 :     ulong p = P[i], e = E[i];
    3412       47386 :     if (e & 1) m *= p;
    3413             :   }
    3414       59032 :   return m;
    3415             : }
    3416             : ulong
    3417       59032 : coreu(ulong n)
    3418             : {
    3419             :   pari_sp av;
    3420       59032 :   if (n == 0) return 0;
    3421       59032 :   av = avma; return gc_ulong(av, coreu_fact(factoru(n)));
    3422             : }
    3423             : GEN
    3424      706205 : core(GEN n)
    3425             : {
    3426      706205 :   pari_sp av = avma;
    3427             :   GEN m, F;
    3428             :   ulong p;
    3429             :   long i, l, v;
    3430             :   forprime_t S;
    3431             : 
    3432      706205 :   if ((F = check_arith_all(n, "core")))
    3433             :   {
    3434      646861 :     GEN p, x, P = gel(F,1), E = gel(F,2);
    3435      646861 :     long j = 1;
    3436      646861 :     if (lg(P) == 1) return gen_1;
    3437      646833 :     p = gel(P,1);
    3438      646833 :     if (!signe(p)) return gen_0;
    3439      646791 :     l = lg(P); x = cgetg(l, t_VEC);
    3440     2284253 :     for (i = 1; i < l; i++)
    3441     1637480 :       if (mpodd(gel(E,i))) gel(x,j++) = gel(P,i);
    3442      646773 :     setlg(x, j); return ZV_prod(x);
    3443             :   }
    3444       59353 :   switch(lgefint(n))
    3445             :   {
    3446          28 :     case 2: return gen_0;
    3447       58976 :     case 3:
    3448       58976 :       p = coreu(uel(n,2));
    3449       58976 :       return signe(n) > 0? utoipos(p): utoineg(p);
    3450             :   }
    3451             : 
    3452         349 :   m = signe(n) < 0? gen_m1: gen_1;
    3453         349 :   n = absi_shallow(n);
    3454         349 :   u_forprime_init(&S, 2, tridiv_bound(n));
    3455     4994430 :   while ((p = u_forprime_next_fast(&S)))
    3456             :   {
    3457             :     int stop;
    3458     4994101 :     v = Z_lvalrem_stop(&n, p, &stop);
    3459     4994101 :     if (v)
    3460             :     {
    3461         965 :       if (v & 1) m = muliu(m, p);
    3462         965 :       if (stop)
    3463             :       {
    3464          20 :         if (!is_pm1(n)) m = mulii(m, n);
    3465          20 :         return gerepileuptoint(av, m);
    3466             :       }
    3467             :     }
    3468             :   }
    3469         329 :   l = lg(primetab);
    3470         823 :   for (i = 1; i < l; i++)
    3471             :   {
    3472         502 :     GEN q = gel(primetab,i);
    3473         502 :     v = Z_pvalrem(n, q, &n);
    3474         502 :     if (v)
    3475             :     {
    3476          32 :       if (v & 1) m = mulii(m, q);
    3477          32 :       if (is_pm1(n)) return gerepileuptoint(av, m);
    3478             :     }
    3479             :   }
    3480         321 :   if (ifac_isprime(n)) { m = mulii(m, n); return gerepileuptoint(av, m); }
    3481         311 :   if (m == gen_1) n = icopy(n); /* ifac_core destroys n */
    3482             :   /* large composite without small factors */
    3483         311 :   return gerepileuptoint(av, mulii(m, ifac_core(n)));
    3484             : }
    3485             : 
    3486             : long
    3487           0 : Z_issmooth(GEN m, ulong lim)
    3488             : {
    3489           0 :   pari_sp av = avma;
    3490           0 :   ulong p = 2;
    3491             :   forprime_t S;
    3492           0 :   u_forprime_init(&S, 2, lim);
    3493           0 :   while ((p = u_forprime_next_fast(&S)))
    3494             :   {
    3495             :     int stop;
    3496           0 :     (void)Z_lvalrem_stop(&m, p, &stop);
    3497           0 :     if (stop) return gc_long(av, abscmpiu(m,lim) <= 0);
    3498             :   }
    3499           0 :   return gc_long(av,0);
    3500             : }
    3501             : 
    3502             : GEN
    3503      198365 : Z_issmooth_fact(GEN m, ulong lim)
    3504             : {
    3505      198365 :   pari_sp av = avma;
    3506             :   GEN F, P, E;
    3507             :   ulong p;
    3508      198365 :   long i = 1, l = expi(m)+1;
    3509             :   forprime_t S;
    3510      198371 :   P = cgetg(l, t_VECSMALL);
    3511      198370 :   E = cgetg(l, t_VECSMALL);
    3512      198341 :   F = mkmat2(P,E);
    3513      198240 :   u_forprime_init(&S, 2, lim);
    3514    50790918 :   while ((p = u_forprime_next_fast(&S)))
    3515             :   {
    3516             :     long v;
    3517             :     int stop;
    3518    50703602 :     if ((v = Z_lvalrem_stop(&m, p, &stop)))
    3519             :     {
    3520      753001 :       P[i] = p;
    3521      753001 :       E[i] = v; i++;
    3522      753001 :       if (stop)
    3523             :       {
    3524      136249 :         if (abscmpiu(m,lim) > 0) break;
    3525      115650 :         if (m[2] > 1) { P[i] = m[2]; E[i] = 1; i++; }
    3526      115650 :         setlg(P, i);
    3527      115975 :         setlg(E, i); return gc_const((pari_sp)F, F);
    3528             :       }
    3529             :     }
    3530             :   }
    3531       73012 :   return gc_NULL(av);
    3532             : }
    3533             : 
    3534             : /***********************************************************************/
    3535             : /**                                                                   **/
    3536             : /**       COMPUTING THE MATRIX OF PRIME DIVISORS AND EXPONENTS        **/
    3537             : /**                                                                   **/
    3538             : /***********************************************************************/
    3539             : static GEN
    3540       79986 : aux_end(GEN M, GEN n, long nb)
    3541             : {
    3542       79986 :   GEN P,E, z = (GEN)avma;
    3543             :   long i;
    3544             : 
    3545       79986 :   guncloneNULL(n);
    3546       79986 :   P = cgetg(nb+1,t_COL);
    3547       79986 :   E = cgetg(nb+1,t_COL);
    3548      696536 :   for (i=nb; i; i--)
    3549             :   { /* allow a stackdummy in the middle */
    3550      616550 :     while (typ(z) != t_INT) z += lg(z);
    3551      616550 :     gel(E,i) = z; z += lg(z);
    3552      616550 :     gel(P,i) = z; z += lg(z);
    3553             :   }
    3554       79986 :   gel(M,1) = P;
    3555       79986 :   gel(M,2) = E;
    3556       79986 :   return sort_factor(M, (void*)&abscmpii, cmp_nodata);
    3557             : }
    3558             : 
    3559             : static void
    3560      610137 : STORE(long *nb, GEN x, long e) { (*nb)++; (void)x; (void)utoipos(e); }
    3561             : static void
    3562      571390 : STOREu(long *nb, ulong x, long e) { STORE(nb, utoipos(x), e); }
    3563             : static void
    3564       38733 : STOREi(long *nb, GEN x, long e) { STORE(nb, icopy(x), e); }
    3565             : /* no prime less than p divides n; return 1 if factored completely */
    3566             : static int
    3567       17954 : special_primes(GEN n, ulong p, long *nb, GEN T)
    3568             : {
    3569       17954 :   long i, l = lg(T);
    3570       17954 :   if (l > 1)
    3571             :   { /* pp = square of biggest p tried so far */
    3572         498 :     long pp[] = { evaltyp(t_INT)|_evallg(4), 0,0,0 };
    3573         498 :     pari_sp av = avma; affii(sqru(p), pp); set_avma(av);
    3574             : 
    3575        1015 :     for (i = 1; i < l; i++)
    3576         650 :       if (dvdiiz(n, gel(T,i), n))
    3577             :       {
    3578         329 :         long k = 1; while (dvdiiz(n, gel(T,i), n)) k++;
    3579         231 :         STOREi(nb, gel(T,i), k);
    3580         231 :         if (abscmpii(pp, n) > 0)
    3581             :         {
    3582         133 :           if (!is_pm1(n)) STOREi(nb, n, 1);
    3583         133 :           return 1;
    3584             :         }
    3585             :       }
    3586             :   }
    3587       17821 :   return 0;
    3588             : }
    3589             : 
    3590             : /* factor(sn*|n|), where sn = -1 or 1.
    3591             :  * all != 0 : only look for prime divisors < all. If pU is not NULL,
    3592             :  * set it to unfactored composite */
    3593             : static GEN
    3594    10806120 : ifactor_sign(GEN n, ulong all, long hint, long sn, GEN *pU)
    3595             : {
    3596             :   GEN M, N;
    3597             :   pari_sp av;
    3598    10806120 :   long nb = 0, nb0 = 0, i;
    3599             :   ulong lim;
    3600             :   forprime_t T;
    3601             : 
    3602    10806120 :   if (lgefint(n) == 3)
    3603             :   { /* small integer */
    3604    10726149 :     GEN f, Pf, Ef, P, E, F = cgetg(3, t_MAT);
    3605             :     ulong U1, U2;
    3606             :     long l;
    3607    10726277 :     av = avma;
    3608             :     /* enough room to store <= 15 primes and exponents (OK if n < 2^64) */
    3609    10726277 :     (void)new_chunk((15*3 + 15 + 1) * 2);
    3610    10726239 :     f = factoru_sign(uel(n,2), all, hint, pU? &U1: NULL, pU? &U2: NULL);
    3611    10726379 :     set_avma(av);
    3612    10726377 :     Pf = gel(f,1);
    3613    10726377 :     Ef = gel(f,2);
    3614    10726377 :     l = lg(Pf);
    3615    10726377 :     if (sn < 0)
    3616             :     { /* add sign */
    3617        6181 :       long L = l+1;
    3618        6181 :       gel(F,1) = P = cgetg(L, t_COL);
    3619        6181 :       gel(F,2) = E = cgetg(L, t_COL);
    3620        6181 :       gel(P,1) = gen_m1; P++;
    3621        6181 :       gel(E,1) = gen_1;  E++;
    3622             :     }
    3623             :     else
    3624             :     {
    3625    10720196 :       gel(F,1) = P = cgetg(l, t_COL);
    3626    10720223 :       gel(F,2) = E = cgetg(l, t_COL);
    3627             :     }
    3628    33471323 :     for (i = 1; i < l; i++)
    3629             :     {
    3630    22744939 :       gel(P,i) = utoipos(Pf[i]);
    3631    22744939 :       gel(E,i) = utoipos(Ef[i]);
    3632             :     }
    3633    10726384 :     if (pU) *pU = U1 == 1? NULL: mkvec2(utoipos(U1), utoipos(U2));
    3634    10726361 :     return F;
    3635             :   }
    3636       79971 :   if (pU) *pU = NULL;
    3637       79971 :   M = cgetg(3,t_MAT);
    3638       79986 :   if (sn < 0) STORE(&nb, utoineg(1), 1);
    3639       79986 :   if (is_pm1(n)) return aux_end(M,NULL,nb);
    3640             : 
    3641       79986 :   n = N = gclone(n); setabssign(n);
    3642             :   /* trial division bound */
    3643       79986 :   lim = all; if (!lim) lim = tridiv_bound(n);
    3644       79986 :   if (lim > 2)
    3645             :   {
    3646             :     ulong maxp, p;
    3647             :     pari_sp av2;
    3648       79972 :     i = vali(n);
    3649       79972 :     if (i)
    3650             :     {
    3651       61386 :       STOREu(&nb, 2, i);
    3652       61386 :       av = avma; affii(shifti(n,-i), n); set_avma(av);
    3653             :     }
    3654       79971 :     if (is_pm1(n)) return aux_end(M,n,nb);
    3655             :     /* trial division */
    3656       79834 :     maxp = maxprime();
    3657       79834 :     av = avma; u_forprime_init(&T, 3, minss(lim, maxp)); av2 = avma;
    3658             :     /* first pass: known to fit in private prime table */
    3659   457600454 :     while ((p = u_forprime_next_fast(&T)))
    3660             :     {
    3661   457850387 :       pari_sp av3 = avma;
    3662             :       int stop;
    3663   457850387 :       long k = Z_lvalrem_stop(&n, p, &stop);
    3664   457576938 :       if (k)
    3665             :       {
    3666      509955 :         affii(n, N); n = N; set_avma(av3);
    3667      509955 :         STOREu(&nb, p, k);
    3668             :       }
    3669   457582507 :       if (p == 16381 && bit_accuracy(lgefint(n)) < 2048)
    3670       27168 :       { stop = ifac_isprime(n); nb0 = nb; }
    3671   457582507 :       if (stop)
    3672             :       {
    3673       61888 :         if (!is_pm1(n)) STOREi(&nb, n, 1);
    3674       61888 :         stackdummy(av, av2);
    3675       61888 :         return aux_end(M,n,nb);
    3676             :       }
    3677             :     }
    3678       15408 :     stackdummy(av, av2);
    3679       17947 :     if (lim > maxp)
    3680             :     { /* second pass, usually empty: outside private prime table */
    3681        5302 :       av = avma; u_forprime_init(&T, maxp+1, lim); av2 = avma;
    3682      549041 :       while ((p = u_forprime_next(&T)))
    3683             :       {
    3684      543746 :         pari_sp av3 = avma;
    3685             :         int stop;
    3686      543746 :         long k = Z_lvalrem_stop(&n, p, &stop);
    3687      543746 :         if (k)
    3688             :         {
    3689          49 :           affii(n, N); n = N; set_avma(av3);
    3690          49 :           STOREu(&nb, p, k);
    3691             :         }
    3692      543746 :         if (stop)
    3693             :         {
    3694           7 :           if (!is_pm1(n)) STOREi(&nb, n, 1);
    3695           7 :           stackdummy(av, av2);
    3696           7 :           return aux_end(M,n,nb);
    3697             :         }
    3698             :       }
    3699        5295 :       stackdummy(av, av2);
    3700             :     }
    3701             :   }
    3702       17954 :   if (special_primes(n, lim, &nb, primetab)) return aux_end(M,n, nb);
    3703       17821 :   if (all)
    3704             :   { /* smallfact: look for easy pure powers then stop. Cf Z_isanypower */
    3705             :     GEN x;
    3706             :     long k;
    3707       14405 :     av = avma;
    3708       14405 :     k = isanypower_nosmalldiv(n, &x);
    3709       14405 :     if (k > 1) affii(x, n);
    3710       14405 :     if (pU)
    3711             :     {
    3712             :       GEN F;
    3713       10412 :       if (abscmpiu(n, lim) <= 0
    3714       10412 :           || cmpii(n, sqru(lim)) <= 0
    3715        6620 :           || ((nb > nb0 || k > 1)
    3716        4980 :               && bit_accuracy(lgefint(n)) < 2048 && ifac_isprime(n)))
    3717       10412 :       { set_avma(av); STOREi(&nb, n, k); return aux_end(M,n, nb); }
    3718        5601 :       set_avma(av); F = aux_end(M, NULL, nb); /* don't destroy n */
    3719        5601 :       *pU = mkvec2(icopy(n), utoipos(k)); /* composite cofactor */
    3720        5601 :       gunclone(n); return F;
    3721             :     }
    3722             :     else
    3723        3993 :     { set_avma(av); STOREi(&nb, n, k); }
    3724        3993 :     if (DEBUGLEVEL >= 2) {
    3725           0 :       pari_warn(warner,
    3726           0 :         "IFAC: untested %ld-bit integer declared prime", expi(n)+1);
    3727           0 :       if (expi(n) <= 256) err_printf("\t%Ps\n", n);
    3728             :     }
    3729             :   }
    3730        3416 :   else if (nb > nb0 && ifac_isprime(n)) STOREi(&nb, n, 1);
    3731        3247 :   else nb += ifac_decomp(n, hint);
    3732        7409 :   return aux_end(M,n, nb);
    3733             : }
    3734             : 
    3735             : static GEN
    3736     9076598 : ifactor(GEN n, ulong all, long hint)
    3737             : {
    3738     9076598 :   long s = signe(n);
    3739     9076598 :   if (!s) retmkmat2(mkcol(gen_0), mkcol(gen_1));
    3740     9076549 :   return ifactor_sign(n, all, hint, s, NULL);
    3741             : }
    3742             : 
    3743             : int
    3744        7578 : ifac_next(GEN *part, GEN *p, long *e)
    3745             : {
    3746        7578 :   GEN here = ifac_main(part);
    3747        7578 :   if (here == gen_0) { *p = NULL; *e = 1; return 0; }
    3748        7564 :   if (!here) { *p = NULL; *e = 0; return 0; }
    3749        5035 :   *p = VALUE(here);
    3750        5035 :   *e = EXPON(here)[2];
    3751        5035 :   ifac_delete(here); return 1;
    3752             : }
    3753             : 
    3754             : /* see before ifac_crack for current semantics of 'hint' (factorint's 'flag') */
    3755             : GEN
    3756       10276 : factorint(GEN n, long flag)
    3757             : {
    3758             :   GEN F;
    3759       10276 :   if ((F = check_arith_all(n,"factorint"))) return gcopy(F);
    3760       10276 :   return ifactor(n,0,flag);
    3761             : }
    3762             : 
    3763             : GEN
    3764       21654 : Z_factor_limit(GEN n, ulong all)
    3765             : {
    3766       21654 :   if (!all) all = GP_DATA->primelimit + 1;
    3767       21654 :   return ifactor(n, all, decomp_default_hint);
    3768             : }
    3769             : GEN
    3770      887552 : absZ_factor_limit_strict(GEN n, ulong all, GEN *pU)
    3771             : {
    3772             :   GEN F, U;
    3773      887552 :   if (!signe(n))
    3774             :   {
    3775           0 :     if (pU) *pU = NULL;
    3776           0 :     retmkmat2(mkcol(gen_0), mkcol(gen_1));
    3777             :   }
    3778      887552 :   if (!all) all = GP_DATA->primelimit + 1;
    3779      887552 :   F = ifactor_sign(n, all, decomp_default_hint, 1, &U);
    3780      887600 :   if (pU) *pU = U;
    3781      887600 :   return F;
    3782             : }
    3783             : GEN
    3784      276620 : absZ_factor_limit(GEN n, ulong all)
    3785             : {
    3786      276620 :   if (!signe(n)) retmkmat2(mkcol(gen_0), mkcol(gen_1));
    3787      276620 :   if (!all) all = GP_DATA->primelimit + 1;
    3788      276620 :   return ifactor_sign(n, all, decomp_default_hint, 1, NULL);
    3789             : }
    3790             : GEN
    3791     9044634 : Z_factor(GEN n)
    3792     9044634 : { return ifactor(n,0,decomp_default_hint); }
    3793             : GEN
    3794      565209 : absZ_factor(GEN n)
    3795             : {
    3796      565209 :   if (!signe(n)) retmkmat2(mkcol(gen_0), mkcol(gen_1));
    3797      565195 :   return ifactor_sign(n, 0, decomp_default_hint, 1, NULL);
    3798             : }
    3799             : /* Factor until the unfactored part is smaller than limit. Return the
    3800             :  * factored part. Hence factorback(output) may be smaller than n */
    3801             : GEN
    3802          98 : Z_factor_until(GEN n, GEN limit)
    3803             : {
    3804          98 :   pari_sp av = avma;
    3805          98 :   long s = signe(n), eq;
    3806             :   GEN q, F, U;
    3807             : 
    3808          98 :   if (!s) retmkmat2(mkcol(gen_0), mkcol(gen_1));
    3809          98 :   F = ifactor_sign(n, tridiv_bound(n), decomp_default_hint, s, &U);
    3810          98 :   if (!U) return F;
    3811          28 :   q = gel(U,1); /* composite, q^eq = unfactored part */
    3812          28 :   eq = itou(gel(U,2));
    3813          28 :   if (cmpii(eq == 1? q: powiu(q, eq), limit) > 0)
    3814             :   { /* factor further */
    3815          21 :     long l2 = expi(q)+1;
    3816             :     GEN P2, E2, F2, part;
    3817          21 :     if (eq > 1) limit = sqrtnint(limit, eq);
    3818          21 :     P2 = coltrunc_init(l2);
    3819          21 :     E2 = coltrunc_init(l2); F2 = mkmat2(P2,E2);
    3820          21 :     part = ifac_start(icopy(q), 0); /* ifac_next would destroy q */
    3821             :     for(;;)
    3822           0 :     {
    3823             :       long e;
    3824             :       GEN p;
    3825          21 :       if (!ifac_next(&part,&p,&e)) break;
    3826          21 :       vectrunc_append(P2, p);
    3827          21 :       vectrunc_append(E2, utoipos(e * eq));
    3828          21 :       q = diviiexact(q, powiu(p, e));
    3829          21 :       if (cmpii(q, limit) <= 0) break;
    3830             :     }
    3831          21 :     F2 = sort_factor(F2, (void*)&abscmpii, cmp_nodata);
    3832          21 :     F = merge_factor(F, F2, (void*)&abscmpii, cmp_nodata);
    3833             :   }
    3834          28 :   return gerepilecopy(av, F);
    3835             : }
    3836             : 
    3837             : static void
    3838   108974803 : matsmalltrunc_append(GEN m, ulong p, ulong e)
    3839             : {
    3840   108974803 :   GEN P = gel(m,1), E = gel(m,2);
    3841   108974803 :   long l = lg(P);
    3842   108974803 :   P[l] = p; lg_increase(P);
    3843   109036531 :   E[l] = e; lg_increase(E);
    3844   108983430 : }
    3845             : static GEN
    3846    43708128 : matsmalltrunc_init(long l)
    3847             : {
    3848    43708128 :   GEN P = vecsmalltrunc_init(l);
    3849    43476807 :   GEN E = vecsmalltrunc_init(l); return mkvec2(P,E);
    3850             : }
    3851             : 
    3852             : /* return optimal N s.t. omega(b) <= N for all b <= x */
    3853             : long
    3854       52720 : maxomegau(ulong x)
    3855             : { /* P=primes(15); for(i=1,15, print([i, vecprod(P[1..i])])) */
    3856       52720 :   if (x < 30030UL)/* rare trivial cases */
    3857             :   {
    3858       25703 :     if (x < 2UL) return 0;
    3859        7475 :     if (x < 6UL) return 1;
    3860        1875 :     if (x < 30UL) return 2;
    3861        1182 :     if (x < 210UL) return 3;
    3862         972 :     if (x < 2310UL) return 4;
    3863         909 :     return 5;
    3864             :   }
    3865       27017 :   if (x < 510510UL) return 6; /* most frequent case */
    3866       13419 :   if (x < 9699690UL) return 7;
    3867           7 :   if (x < 223092870UL) return 8;
    3868             : #ifdef LONG_IS_64BIT
    3869           6 :   if (x < 6469693230UL) return 9;
    3870           0 :   if (x < 200560490130UL) return 10;
    3871           0 :   if (x < 7420738134810UL) return 11;
    3872           0 :   if (x < 304250263527210UL) return 12;
    3873           0 :   if (x < 13082761331670030UL) return 13;
    3874           0 :   if (x < 614889782588491410UL) return 14;
    3875           0 :   return 15;
    3876             : #else
    3877           1 :   return 9;
    3878             : #endif
    3879             : }
    3880             : /* return optimal N s.t. omega(b) <= N for all odd b <= x */
    3881             : long
    3882        2951 : maxomegaoddu(ulong x)
    3883             : { /* P=primes(15+1); for(i=1,15, print([i, vecprod(P[2..i+1])])) */
    3884        2951 :   if (x < 255255UL)/* rare trivial cases */
    3885             :   {
    3886        1766 :     if (x < 3UL) return 0;
    3887        1766 :     if (x < 15UL) return 1;
    3888        1766 :     if (x < 105UL) return 2;
    3889        1766 :     if (x < 1155UL) return 3;
    3890        1738 :     if (x < 15015UL) return 4;
    3891        1738 :     return 5;
    3892             :   }
    3893        1185 :   if (x < 4849845UL) return 6; /* most frequent case */
    3894           0 :   if (x < 111546435UL) return 7;
    3895           0 :   if (x < 3234846615UL) return 8;
    3896             : #ifdef LONG_IS_64BIT
    3897           0 :   if (x < 100280245065UL) return 9;
    3898           0 :   if (x < 3710369067405UL) return 10;
    3899           0 :   if (x < 152125131763605UL) return 11;
    3900           0 :   if (x < 6541380665835015UL) return 12;
    3901           0 :   if (x < 307444891294245705UL) return 13;
    3902           0 :   if (x < 16294579238595022365UL) return 14;
    3903           0 :   return 15;
    3904             : #else
    3905           0 :   return 9;
    3906             : #endif
    3907             : }
    3908             : 
    3909             : /* If a <= c <= b , factoru(c) = L[c-a+1] */
    3910             : GEN
    3911       38587 : vecfactoru_i(ulong a, ulong b)
    3912             : {
    3913       38587 :   ulong k, p, n = b-a+1, N = maxomegau(b) + 1;
    3914       38588 :   GEN v = const_vecsmall(n, 1);
    3915       38588 :   GEN L = cgetg(n+1, t_VEC);
    3916             :   forprime_t T;
    3917    20774793 :   for (k = 1; k <= n; k++) gel(L,k) = matsmalltrunc_init(N);
    3918       38588 :   u_forprime_init(&T, 2, usqrt(b));
    3919     1676089 :   while ((p = u_forprime_next(&T)))
    3920             :   { /* p <= sqrt(b) */
    3921     1647024 :     ulong pk = p, K = ulogint(b, p);
    3922     5725207 :     for (k = 1; k <= K; k++)
    3923             :     {
    3924     4087706 :       ulong j, t = a / pk, ap = t * pk;
    3925     4087706 :       if (ap < a) { ap += pk; t++; }
    3926             :       /* t = (j+a-1) \ pk */
    3927     4087706 :       t %= p;
    3928    61531724 :       for (j = ap-a+1; j <= n; j += pk)
    3929             :       {
    3930    57453563 :         if (t) { v[j] *= pk; matsmalltrunc_append(gel(L,j), p,k); }
    3931    57444018 :         if (++t == p) t = 0;
    3932             :       }
    3933     4078161 :       pk *= p;
    3934             :     }
    3935             :   }
    3936             :   /* complete factorisation of non-sqrt(b)-smooth numbers */
    3937    20843866 :   for (k = 1, N = a; k <= n; k++, N++)
    3938    20810837 :     if (uel(v,k) != N) matsmalltrunc_append(gel(L,k), N/uel(v,k),1UL);
    3939       33029 :   return L;
    3940             : }
    3941             : GEN
    3942           0 : vecfactoru(ulong a, ulong b)
    3943             : {
    3944           0 :   pari_sp av = avma;
    3945           0 :   return gerepilecopy(av, vecfactoru_i(a,b));
    3946             : }
    3947             : 
    3948             : /* Assume a and b odd, return L s.t. L[k] = factoru(a + 2*(k-1))
    3949             :  * If a <= c <= b odd, factoru(c) = L[(c-a)>>1 + 1] */
    3950             : GEN
    3951        2951 : vecfactoroddu_i(ulong a, ulong b)
    3952             : {
    3953        2951 :   ulong k, p, n = ((b-a)>>1) + 1, N = maxomegaoddu(b) + 1;
    3954        2951 :   GEN v = const_vecsmall(n, 1);
    3955        2951 :   GEN L = cgetg(n+1, t_VEC);
    3956             :   forprime_t T;
    3957             : 
    3958    23480339 :   for (k = 1; k <= n; k++) gel(L,k) = matsmalltrunc_init(N);
    3959        2951 :   u_forprime_init(&T, 3, usqrt(b));
    3960      241170 :   while ((p = u_forprime_next(&T)))
    3961             :   { /* p <= sqrt(b) */
    3962      247384 :     ulong pk = p, K = ulogint(b, p);
    3963      833313 :     for (k = 1; k <= K; k++)
    3964             :     {
    3965      595094 :       ulong j, t = (a / pk) | 1UL, ap = t * pk;
    3966             :       /* t and ap are odd, ap multiple of pk = p^k */
    3967      595094 :       if (ap < a) { ap += pk<<1; t+=2; }
    3968             :       /* c=t*p^k by steps of 2*p^k; factorization of c*=p^k if (t,p)=1 */
    3969      595094 :       t %= p;
    3970    43446529 :       for (j = ((ap-a)>>1)+1; j <= n; j += pk)
    3971             :       {
    3972    42860643 :         if (t) { v[j] *= pk; matsmalltrunc_append(gel(L,j), p,k); }
    3973    42851435 :         t += 2; if (t >= p) t -= p;
    3974             :       }
    3975      585886 :       pk *= p;
    3976             :     }
    3977             :   }
    3978             :   /* complete factorisation of non-sqrt(b)-smooth numbers */
    3979    23580501 :   for (k = 1, N = a; k <= n; k++, N+=2)
    3980    23579166 :     if (uel(v,k) != N) matsmalltrunc_append(gel(L,k), N/uel(v,k),1UL);
    3981        1335 :   return L;
    3982             : }
    3983             : GEN
    3984           0 : vecfactoroddu(ulong a, ulong b)
    3985             : {
    3986           0 :   pari_sp av = avma;
    3987           0 :   return gerepilecopy(av, vecfactoroddu_i(a,b));
    3988             : }
    3989             : 
    3990             : /* If 0 <= a <= c <= b; L[c-a+1] = factoru(c)[,1] if c squarefree, else NULL */
    3991             : GEN
    3992       13692 : vecfactorsquarefreeu(ulong a, ulong b)
    3993             : {
    3994       13692 :   ulong k, p, n = b-a+1, N = maxomegau(b) + 1;
    3995       13692 :   GEN v = const_vecsmall(n, 1);
    3996       13692 :   GEN L = cgetg(n+1, t_VEC);
    3997             :   forprime_t T;
    3998    14013916 :   for (k = 1; k <= n; k++) gel(L,k) = vecsmalltrunc_init(N);
    3999       13692 :   u_forprime_init(&T, 2, usqrt(b));
    4000     1637300 :   while ((p = u_forprime_next(&T)))
    4001             :   { /* p <= sqrt(b), kill nonsquarefree */
    4002     1623608 :     ulong j, pk = p*p, t = a / pk, ap = t * pk;
    4003     1623608 :     if (ap < a) ap += pk;
    4004     7952378 :     for (j = ap-a+1; j <= n; j += pk) gel(L,j) = NULL;
    4005             : 
    4006     1623608 :     t = a / p; ap = t * p;
    4007     1623608 :     if (ap < a) { ap += p; t++; }
    4008    31338244 :     for (j = ap-a+1; j <= n; j += p, t++)
    4009    29714636 :       if (gel(L,j)) { v[j] *= p; vecsmalltrunc_append(gel(L,j), p); }
    4010             :   }
    4011             :   /* complete factorisation of non-sqrt(b)-smooth numbers */
    4012    14013916 :   for (k = 1, N = a; k <= n; k++, N++)
    4013    14000224 :     if (gel(L,k) && uel(v,k) != N) vecsmalltrunc_append(gel(L,k), N/uel(v,k));
    4014       13692 :   return L;
    4015             : }
    4016             : /* If 0 <= a <= c <= b; L[c-a+1] = factoru(c)[,1] if c squarefree and coprime
    4017             :  * to all the primes in sorted zv P, else NULL */
    4018             : GEN
    4019         364 : vecfactorsquarefreeu_coprime(ulong a, ulong b, GEN P)
    4020             : {
    4021         364 :   ulong k, p, n = b-a+1, sqb = usqrt(b), N = maxomegau(b) + 1;
    4022         364 :   GEN v = const_vecsmall(n, 1);
    4023         364 :   GEN L = cgetg(n+1, t_VEC);
    4024             :   forprime_t T;
    4025      770364 :   for (k = 1; k <= n; k++) gel(L,k) = vecsmalltrunc_init(N);
    4026         364 :   u_forprime_init(&T, 2, sqb);
    4027       16513 :   while ((p = u_forprime_next(&T)))
    4028             :   { /* p <= sqrt(b), kill nonsquarefree */
    4029       16149 :     ulong j, t, ap, bad = zv_search(P, p), pk = bad ? p: p * p;
    4030       16149 :     t = a / pk; ap = t * pk; if (ap < a) ap += pk;
    4031      727258 :     for (j = ap-a+1; j <= n; j += pk) gel(L,j) = NULL;
    4032       16149 :     if (bad) continue;
    4033             : 
    4034       15421 :     t = a / p; ap = t * p;
    4035       15421 :     if (ap < a) { ap += p; t++; }
    4036      851620 :     for (j = ap-a+1; j <= n; j += p, t++)
    4037      836199 :       if (gel(L,j)) { v[j] *= p; vecsmalltrunc_append(gel(L,j), p); }
    4038             :   }
    4039         364 :   if (uel(P,lg(P)-1) <= sqb) P = NULL;
    4040             :   /* complete factorisation of non-sqrt(b)-smooth numbers */
    4041      770364 :   for (k = 1, N = a; k <= n; k++, N++)
    4042      770000 :     if (gel(L,k) && uel(v,k) != N)
    4043             :     {
    4044      206325 :       ulong q = N / uel(v,k);
    4045      206325 :       if (!P || !zv_search(P, q)) vecsmalltrunc_append(gel(L,k), q);
    4046             :     }
    4047         364 :   return L;
    4048             : }
    4049             : 
    4050             : GEN
    4051          49 : vecsquarefreeu(ulong a, ulong b)
    4052             : {
    4053          49 :   ulong j, k, p, n = b-a+1;
    4054          49 :   GEN L = const_vecsmall(n, 1);
    4055             :   forprime_t T;
    4056          49 :   u_forprime_init(&T, 2, usqrt(b));
    4057         462 :   while ((p = u_forprime_next(&T)))
    4058             :   { /* p <= sqrt(b), kill nonsquarefree */
    4059         413 :     ulong pk = p*p, t = a / pk, ap = t * pk;
    4060         413 :     if (ap < a) { ap += pk; t++; }
    4061             :     /* t = (j+a-1) \ pk */
    4062       21777 :     for (j = ap-a+1; j <= n; j += pk, t++) L[j] = 0;
    4063             :   }
    4064       48258 :   for (k = j = 1; k <= n; k++)
    4065       48209 :     if (L[k]) L[j++] = a+k-1;
    4066          49 :   setlg(L,j); return L;
    4067             : }

Generated by: LCOV version 1.13