Code coverage tests

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

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

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

LCOV - code coverage report
Current view: top level - basemath - ifactor1.c (source / functions) Hit Total Coverage
Test: PARI/GP v2.8.0 lcov report (development 19352-1b11b25) Lines: 1385 1698 81.6 %
Date: 2016-08-25 06:11:27 Functions: 75 84 89.3 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.11