source: git/factory/cf_gcd.cc @ 59d00e

spielwiese
Last change on this file since 59d00e was d83c0b, checked in by Martin Lee <martinlee84@…>, 11 years ago
fix: memory leak deleted unnecessary stuff using NTL in non-word size case
  • Property mode set to 100644
File size: 34.8 KB
Line 
1/* emacs edit mode for this file is -*- C++ -*- */
2
3#ifdef HAVE_CONFIG_H
4#include "config.h"
5#endif /* HAVE_CONFIG_H */
6
7#include "timing.h"
8#include "cf_assert.h"
9#include "debug.h"
10
11#include "cf_defs.h"
12#include "canonicalform.h"
13#include "cf_iter.h"
14#include "cf_reval.h"
15#include "cf_primes.h"
16#include "cf_algorithm.h"
17#include "cf_factory.h"
18#include "fac_util.h"
19#include "templates/ftmpl_functions.h"
20#include "algext.h"
21#include "cf_gcd_smallp.h"
22#include "cf_map_ext.h"
23#include "cf_util.h"
24#include "gfops.h"
25
26#ifdef HAVE_NTL
27#include <NTL/ZZX.h>
28#include "NTLconvert.h"
29bool isPurePoly(const CanonicalForm & );
30#ifndef HAVE_FLINT
31static CanonicalForm gcd_univar_ntl0( const CanonicalForm &, const CanonicalForm & );
32static CanonicalForm gcd_univar_ntlp( const CanonicalForm &, const CanonicalForm & );
33#endif
34#endif
35
36#ifdef HAVE_FLINT
37#include "FLINTconvert.h"
38static CanonicalForm gcd_univar_flint0 (const CanonicalForm &, const CanonicalForm &);
39static CanonicalForm gcd_univar_flintp (const CanonicalForm &, const CanonicalForm &);
40#endif
41
42static CanonicalForm cf_content ( const CanonicalForm &, const CanonicalForm & );
43
44void out_cf(const char *s1,const CanonicalForm &f,const char *s2);
45
46CanonicalForm chinrem_gcd(const CanonicalForm & FF,const CanonicalForm & GG);
47
48bool
49gcd_test_one ( const CanonicalForm & f, const CanonicalForm & g, bool swap, int & d )
50{
51    d= 0;
52    int count = 0;
53    // assume polys have same level;
54
55    Variable v= Variable (1);
56    bool algExtension= (hasFirstAlgVar (f, v) || hasFirstAlgVar (g, v));
57    CanonicalForm lcf, lcg;
58    if ( swap )
59    {
60        lcf = swapvar( LC( f ), Variable(1), f.mvar() );
61        lcg = swapvar( LC( g ), Variable(1), f.mvar() );
62    }
63    else
64    {
65        lcf = LC( f, Variable(1) );
66        lcg = LC( g, Variable(1) );
67    }
68
69    CanonicalForm F, G;
70    if ( swap )
71    {
72        F=swapvar( f, Variable(1), f.mvar() );
73        G=swapvar( g, Variable(1), g.mvar() );
74    }
75    else
76    {
77        F = f;
78        G = g;
79    }
80
81    #define TEST_ONE_MAX 50
82    int p= getCharacteristic();
83    bool passToGF= false;
84    int k= 1;
85    if (p > 0 && p < TEST_ONE_MAX && CFFactory::gettype() != GaloisFieldDomain && !algExtension)
86    {
87      if (p == 2)
88        setCharacteristic (2, 6, 'Z');
89      else if (p == 3)
90        setCharacteristic (3, 4, 'Z');
91      else if (p == 5 || p == 7)
92        setCharacteristic (p, 3, 'Z');
93      else
94        setCharacteristic (p, 2, 'Z');
95      passToGF= true;
96    }
97    else if (p > 0 && CFFactory::gettype() == GaloisFieldDomain && ipower (p , getGFDegree()) < TEST_ONE_MAX)
98    {
99      k= getGFDegree();
100      if (ipower (p, 2*k) > TEST_ONE_MAX)
101        setCharacteristic (p, 2*k, gf_name);
102      else
103        setCharacteristic (p, 3*k, gf_name);
104      F= GFMapUp (F, k);
105      G= GFMapUp (G, k);
106      lcf= GFMapUp (lcf, k);
107      lcg= GFMapUp (lcg, k);
108    }
109    else if (p > 0 && p < TEST_ONE_MAX && algExtension)
110    {
111      bool extOfExt= false;
112#ifdef HAVE_NTL
113      int d= degree (getMipo (v));
114      CFList source, dest;
115      Variable v2;
116      CanonicalForm primElem, imPrimElem;
117      if (p == 2 && d < 6)
118      {
119        if (fac_NTL_char != 2)
120        {
121          fac_NTL_char= 2;
122          zz_p::init (p);
123        }
124        bool primFail= false;
125        Variable vBuf;
126        primElem= primitiveElement (v, vBuf, primFail);
127        ASSERT (!primFail, "failure in integer factorizer");
128        if (d < 3)
129        {
130          zz_pX NTLIrredpoly;
131          BuildIrred (NTLIrredpoly, d*3);
132          CanonicalForm newMipo= convertNTLzzpX2CF (NTLIrredpoly, Variable (1));
133          v2= rootOf (newMipo);
134        }
135        else
136        {
137          zz_pX NTLIrredpoly;
138          BuildIrred (NTLIrredpoly, d*2);
139          CanonicalForm newMipo= convertNTLzzpX2CF (NTLIrredpoly, Variable (1));
140          v2= rootOf (newMipo);
141        }
142        imPrimElem= mapPrimElem (primElem, v, v2);
143        extOfExt= true;
144      }
145      else if ((p == 3 && d < 4) || ((p == 5 || p == 7) && d < 3))
146      {
147        if (fac_NTL_char != p)
148        {
149          fac_NTL_char= p;
150          zz_p::init (p);
151        }
152        bool primFail= false;
153        Variable vBuf;
154        primElem= primitiveElement (v, vBuf, primFail);
155        ASSERT (!primFail, "failure in integer factorizer");
156        zz_pX NTLIrredpoly;
157        BuildIrred (NTLIrredpoly, d*2);
158        CanonicalForm newMipo= convertNTLzzpX2CF (NTLIrredpoly, Variable (1));
159        v2= rootOf (newMipo);
160        imPrimElem= mapPrimElem (primElem, v, v2);
161        extOfExt= true;
162      }
163      if (extOfExt)
164      {
165        F= mapUp (F, v, v2, primElem, imPrimElem, source, dest);
166        G= mapUp (G, v, v2, primElem, imPrimElem, source, dest);
167        lcf= mapUp (lcf, v, v2, primElem, imPrimElem, source, dest);
168        lcg= mapUp (lcg, v, v2, primElem, imPrimElem, source, dest);
169        v= v2;
170      }
171#endif
172    }
173
174    CFRandom * sample;
175    if ((!algExtension && p > 0) || p == 0)
176      sample = CFRandomFactory::generate();
177    else
178      sample = AlgExtRandomF (v).clone();
179
180    REvaluation e( 2, tmax( f.level(), g.level() ), *sample );
181    delete sample;
182
183    if (passToGF)
184    {
185      lcf= lcf.mapinto();
186      lcg= lcg.mapinto();
187    }
188
189    CanonicalForm eval1, eval2;
190    if (passToGF)
191    {
192      eval1= e (lcf);
193      eval2= e (lcg);
194    }
195    else
196    {
197      eval1= e (lcf);
198      eval2= e (lcg);
199    }
200
201    while ( ( eval1.isZero() || eval2.isZero() ) && count < TEST_ONE_MAX )
202    {
203        e.nextpoint();
204        count++;
205        eval1= e (lcf);
206        eval2= e (lcg);
207    }
208    if ( count >= TEST_ONE_MAX )
209    {
210        if (passToGF)
211          setCharacteristic (p);
212        if (k > 1)
213          setCharacteristic (p, k, gf_name);
214        return false;
215    }
216
217
218    if (passToGF)
219    {
220      F= F.mapinto();
221      G= G.mapinto();
222      eval1= e (F);
223      eval2= e (G);
224    }
225    else
226    {
227      eval1= e (F);
228      eval2= e (G);
229    }
230
231    CanonicalForm c= gcd (eval1, eval2);
232    d= c.degree();
233    bool result= d < 1;
234    if (d < 0)
235      d= 0;
236
237    if (passToGF)
238      setCharacteristic (p);
239    if (k > 1)
240      setCharacteristic (p, k, gf_name);
241    return result;
242}
243
244//{{{ static CanonicalForm icontent ( const CanonicalForm & f, const CanonicalForm & c )
245//{{{ docu
246//
247// icontent() - return gcd of c and all coefficients of f which
248//   are in a coefficient domain.
249//
250// Used by icontent().
251//
252//}}}
253static CanonicalForm
254icontent ( const CanonicalForm & f, const CanonicalForm & c )
255{
256    if ( f.inBaseDomain() )
257    {
258      if (c.isZero()) return abs(f);
259      return bgcd( f, c );
260    }
261    //else if ( f.inCoeffDomain() )
262    //   return gcd(f,c);
263    else
264    {
265        CanonicalForm g = c;
266        for ( CFIterator i = f; i.hasTerms() && ! g.isOne(); i++ )
267            g = icontent( i.coeff(), g );
268        return g;
269    }
270}
271//}}}
272
273//{{{ CanonicalForm icontent ( const CanonicalForm & f )
274//{{{ docu
275//
276// icontent() - return gcd over all coefficients of f which are
277//   in a coefficient domain.
278//
279//}}}
280CanonicalForm
281icontent ( const CanonicalForm & f )
282{
283    return icontent( f, 0 );
284}
285//}}}
286
287//{{{ CanonicalForm extgcd ( const CanonicalForm & f, const CanonicalForm & g, CanonicalForm & a, CanonicalForm & b )
288//{{{ docu
289//
290// extgcd() - returns polynomial extended gcd of f and g.
291//
292// Returns gcd(f, g) and a and b sucht that f*a+g*b=gcd(f, g).
293// The gcd is calculated using an extended euclidean polynomial
294// remainder sequence, so f and g should be polynomials over an
295// euclidean domain.  Normalizes result.
296//
297// Note: be sure that f and g have the same level!
298//
299//}}}
300CanonicalForm
301extgcd ( const CanonicalForm & f, const CanonicalForm & g, CanonicalForm & a, CanonicalForm & b )
302{
303  if (f.isZero())
304  {
305    a= 0;
306    b= 1;
307    return g;
308  }
309  else if (g.isZero())
310  {
311    a= 1;
312    b= 0;
313    return f;
314  }
315#ifdef HAVE_NTL
316#ifdef HAVE_FLINT
317  if (( getCharacteristic() > 0 ) && (CFFactory::gettype() != GaloisFieldDomain)
318  &&  (f.level()==g.level()) && isPurePoly(f) && isPurePoly(g))
319  {
320    nmod_poly_t F1, G1, A, B, R;
321    convertFacCF2nmod_poly_t (F1, f);
322    convertFacCF2nmod_poly_t (G1, g);
323    nmod_poly_init (R, getCharacteristic());
324    nmod_poly_init (A, getCharacteristic());
325    nmod_poly_init (B, getCharacteristic());
326    nmod_poly_xgcd (R, A, B, F1, G1);
327    a= convertnmod_poly_t2FacCF (A, f.mvar());
328    b= convertnmod_poly_t2FacCF (B, f.mvar());
329    CanonicalForm r= convertnmod_poly_t2FacCF (R, f.mvar());
330    nmod_poly_clear (F1);
331    nmod_poly_clear (G1);
332    nmod_poly_clear (A);
333    nmod_poly_clear (B);
334    nmod_poly_clear (R);
335    return r;
336  }
337#else
338  if (isOn(SW_USE_NTL_GCD_P) && ( getCharacteristic() > 0 ) && (CFFactory::gettype() != GaloisFieldDomain)
339  &&  (f.level()==g.level()) && isPurePoly(f) && isPurePoly(g))
340  {
341    if (fac_NTL_char!=getCharacteristic())
342    {
343      fac_NTL_char=getCharacteristic();
344      zz_p::init(getCharacteristic());
345    }
346    zz_pX F1=convertFacCF2NTLzzpX(f);
347    zz_pX G1=convertFacCF2NTLzzpX(g);
348    zz_pX R;
349    zz_pX A,B;
350    XGCD(R,A,B,F1,G1);
351    a=convertNTLzzpX2CF(A,f.mvar());
352    b=convertNTLzzpX2CF(B,f.mvar());
353    return convertNTLzzpX2CF(R,f.mvar());
354  }
355#endif
356#ifdef HAVE_FLINT
357  if (( getCharacteristic() ==0) && (f.level()==g.level())
358       && isPurePoly(f) && isPurePoly(g))
359  {
360    fmpq_poly_t F1, G1;
361    convertFacCF2Fmpq_poly_t (F1, f);
362    convertFacCF2Fmpq_poly_t (G1, g);
363    fmpq_poly_t R, A, B;
364    fmpq_poly_init (R);
365    fmpq_poly_init (A);
366    fmpq_poly_init (B);
367    fmpq_poly_xgcd (R, A, B, F1, G1);
368    a= convertFmpq_poly_t2FacCF (A, f.mvar());
369    b= convertFmpq_poly_t2FacCF (B, f.mvar());
370    CanonicalForm r= convertFmpq_poly_t2FacCF (R, f.mvar());
371    fmpq_poly_clear (F1);
372    fmpq_poly_clear (G1);
373    fmpq_poly_clear (A);
374    fmpq_poly_clear (B);
375    fmpq_poly_clear (R);
376    return r;
377  }
378#else
379  if (isOn(SW_USE_NTL_GCD_0) && ( getCharacteristic() ==0)
380  && (f.level()==g.level()) && isPurePoly(f) && isPurePoly(g))
381  {
382    CanonicalForm fc=bCommonDen(f);
383    CanonicalForm gc=bCommonDen(g);
384    ZZX F1=convertFacCF2NTLZZX(f*fc);
385    ZZX G1=convertFacCF2NTLZZX(g*gc);
386    ZZX R=GCD(F1,G1);
387    CanonicalForm r=convertNTLZZX2CF(R,f.mvar());
388    ZZ RR;
389    ZZX A,B;
390    if (r.inCoeffDomain())
391    {
392      XGCD(RR,A,B,F1,G1,1);
393      CanonicalForm rr=convertZZ2CF(RR);
394      ASSERT (!rr.isZero(), "NTL:XGCD failed");
395      a=convertNTLZZX2CF(A,f.mvar())*fc/rr;
396      b=convertNTLZZX2CF(B,f.mvar())*gc/rr;
397      return CanonicalForm(1);
398    }
399    else
400    {
401      fc=bCommonDen(f);
402      gc=bCommonDen(g);
403      F1=convertFacCF2NTLZZX(f*fc/r);
404      G1=convertFacCF2NTLZZX(g*gc/r);
405      XGCD(RR,A,B,F1,G1,1);
406      a=convertNTLZZX2CF(A,f.mvar())*fc;
407      b=convertNTLZZX2CF(B,f.mvar())*gc;
408      CanonicalForm rr=convertZZ2CF(RR);
409      ASSERT (!rr.isZero(), "NTL:XGCD failed");
410      a /= rr;
411      b /= rr;
412      return r;
413    }
414  }
415#endif
416#endif
417  // may contain bug in the co-factors, see track 107
418  CanonicalForm contf = content( f );
419  CanonicalForm contg = content( g );
420
421  CanonicalForm p0 = f / contf, p1 = g / contg;
422  CanonicalForm f0 = 1, f1 = 0, g0 = 0, g1 = 1, q, r;
423
424  while ( ! p1.isZero() )
425  {
426      divrem( p0, p1, q, r );
427      p0 = p1; p1 = r;
428      r = g0 - g1 * q;
429      g0 = g1; g1 = r;
430      r = f0 - f1 * q;
431      f0 = f1; f1 = r;
432  }
433  CanonicalForm contp0 = content( p0 );
434  a = f0 / ( contf * contp0 );
435  b = g0 / ( contg * contp0 );
436  p0 /= contp0;
437  if ( p0.sign() < 0 )
438  {
439      p0 = -p0;
440      a = -a;
441      b = -b;
442  }
443  return p0;
444}
445//}}}
446
447//{{{ static CanonicalForm balance_p ( const CanonicalForm & f, const CanonicalForm & q )
448//{{{ docu
449//
450// balance_p() - map f from positive to symmetric representation
451//   mod q.
452//
453// This makes sense for univariate polynomials over Z only.
454// q should be an integer.
455//
456// Used by gcd_poly_univar0().
457//
458//}}}
459
460static CanonicalForm
461balance_p ( const CanonicalForm & f, const CanonicalForm & q, const CanonicalForm & qh )
462{
463    Variable x = f.mvar();
464    CanonicalForm result = 0;
465    CanonicalForm c;
466    CFIterator i;
467    for ( i = f; i.hasTerms(); i++ )
468    {
469        c = i.coeff();
470        if ( c.inCoeffDomain())
471        {
472          if ( c > qh )
473            result += power( x, i.exp() ) * (c - q);
474          else
475            result += power( x, i.exp() ) * c;
476        }
477        else
478          result += power( x, i.exp() ) * balance_p(c,q,qh);
479    }
480    return result;
481}
482
483static CanonicalForm
484balance_p ( const CanonicalForm & f, const CanonicalForm & q )
485{
486    CanonicalForm qh = q / 2;
487    return balance_p (f, q, qh);
488}
489
490/*static CanonicalForm
491balance ( const CanonicalForm & f, const CanonicalForm & q )
492{
493    Variable x = f.mvar();
494    CanonicalForm result = 0, qh = q / 2;
495    CanonicalForm c;
496    CFIterator i;
497    for ( i = f; i.hasTerms(); i++ ) {
498        c = mod( i.coeff(), q );
499        if ( c > qh )
500            result += power( x, i.exp() ) * (c - q);
501        else
502            result += power( x, i.exp() ) * c;
503    }
504    return result;
505}*/
506//}}}
507
508static CanonicalForm gcd_poly_univar0( const CanonicalForm & F, const CanonicalForm & G, bool primitive )
509{
510  CanonicalForm f, g, c, cg, cl, BB, B, M, q, Dp, newD, D, newq;
511  int p, i;
512
513  if ( primitive )
514  {
515    f = F;
516    g = G;
517    c = 1;
518  }
519  else
520  {
521    CanonicalForm cF = content( F ), cG = content( G );
522    f = F / cF;
523    g = G / cG;
524    c = bgcd( cF, cG );
525  }
526  cg = gcd( f.lc(), g.lc() );
527  cl = ( f.lc() / cg ) * g.lc();
528//     B = 2 * cg * tmin(
529//         maxnorm(f)*power(CanonicalForm(2),f.degree())*isqrt(f.degree()+1),
530//         maxnorm(g)*power(CanonicalForm(2),g.degree())*isqrt(g.degree()+1)
531//         )+1;
532  M = tmin( maxNorm(f), maxNorm(g) );
533  BB = power(CanonicalForm(2),tmin(f.degree(),g.degree()))*M;
534  q = 0;
535  i = cf_getNumSmallPrimes() - 1;
536  while ( true )
537  {
538    B = BB;
539    while ( i >= 0 && q < B )
540    {
541      p = cf_getSmallPrime( i );
542      i--;
543      while ( i >= 0 && mod( cl, p ) == 0 )
544      {
545        p = cf_getSmallPrime( i );
546        i--;
547      }
548      setCharacteristic( p );
549      Dp = gcd( mapinto( f ), mapinto( g ) );
550      Dp = ( Dp / Dp.lc() ) * mapinto( cg );
551      setCharacteristic( 0 );
552      if ( Dp.degree() == 0 )
553        return c;
554      if ( q.isZero() )
555      {
556        D = mapinto( Dp );
557        q = p;
558        B = power(CanonicalForm(2),D.degree())*M+1;
559      }
560      else
561      {
562        if ( Dp.degree() == D.degree() )
563        {
564          chineseRemainder( D, q, mapinto( Dp ), p, newD, newq );
565          q = newq;
566          D = newD;
567        }
568        else if ( Dp.degree() < D.degree() )
569        {
570          // all previous p's are bad primes
571          q = p;
572          D = mapinto( Dp );
573          B = power(CanonicalForm(2),D.degree())*M+1;
574        }
575        // else p is a bad prime
576      }
577    }
578    if ( i >= 0 )
579    {
580      // now balance D mod q
581      D = pp( balance_p( D, q ) );
582      if ( fdivides( D, f ) && fdivides( D, g ) )
583        return D * c;
584      else
585        q = 0;
586    }
587    else
588      return gcd_poly( F, G );
589    DEBOUTLN( cerr, "another try ..." );
590  }
591}
592
593static CanonicalForm
594gcd_poly_p( const CanonicalForm & f, const CanonicalForm & g )
595{
596    if (f.inCoeffDomain() || g.inCoeffDomain()) //zero case should be caught by gcd
597      return 1;
598    CanonicalForm pi, pi1;
599    CanonicalForm C, Ci, Ci1, Hi, bi, pi2;
600    bool bpure, ezgcdon= isOn (SW_USE_EZGCD_P);
601    int delta = degree( f ) - degree( g );
602
603    if ( delta >= 0 )
604    {
605        pi = f; pi1 = g;
606    }
607    else
608    {
609        pi = g; pi1 = f; delta = -delta;
610    }
611    if (pi.isUnivariate())
612      Ci= 1;
613    else
614    {
615      if (!ezgcdon)
616        On (SW_USE_EZGCD_P);
617      Ci = content( pi );
618      if (!ezgcdon)
619        Off (SW_USE_EZGCD_P);
620      pi = pi / Ci;
621    }
622    if (pi1.isUnivariate())
623      Ci1= 1;
624    else
625    {
626      if (!ezgcdon)
627        On (SW_USE_EZGCD_P);
628      Ci1 = content( pi1 );
629      if (!ezgcdon)
630        Off (SW_USE_EZGCD_P);
631      pi1 = pi1 / Ci1;
632    }
633    C = gcd( Ci, Ci1 );
634    int d= 0;
635    if ( !( pi.isUnivariate() && pi1.isUnivariate() ) )
636    {
637        if ( gcd_test_one( pi1, pi, true, d ) )
638        {
639          C=abs(C);
640          //out_cf("GCD:",C,"\n");
641          return C;
642        }
643        bpure = false;
644    }
645    else
646    {
647        bpure = isPurePoly(pi) && isPurePoly(pi1);
648#ifdef HAVE_FLINT
649        if (bpure && (CFFactory::gettype() != GaloisFieldDomain))
650          return gcd_univar_flintp(pi,pi1)*C;
651#else
652#ifdef HAVE_NTL
653        if ( isOn(SW_USE_NTL_GCD_P) && bpure && (CFFactory::gettype() != GaloisFieldDomain))
654            return gcd_univar_ntlp(pi, pi1 ) * C;
655#endif
656#endif
657    }
658    Variable v = f.mvar();
659    Hi = power( LC( pi1, v ), delta );
660    int maxNumVars= tmax (getNumVars (pi), getNumVars (pi1));
661
662    if (!(pi.isUnivariate() && pi1.isUnivariate()))
663    {
664      if (size (Hi)*size (pi)/(maxNumVars*3) > 500) //maybe this needs more tuning
665      {
666        On (SW_USE_FF_MOD_GCD);
667        C *= gcd (pi, pi1);
668        Off (SW_USE_FF_MOD_GCD);
669        return C;
670      }
671    }
672
673    if ( (delta+1) % 2 )
674        bi = 1;
675    else
676        bi = -1;
677    CanonicalForm oldPi= pi, oldPi1= pi1, powHi;
678    while ( degree( pi1, v ) > 0 )
679    {
680        if (!(pi.isUnivariate() && pi1.isUnivariate()))
681        {
682          if (size (pi)/maxNumVars > 500 || size (pi1)/maxNumVars > 500)
683          {
684            On (SW_USE_FF_MOD_GCD);
685            C *= gcd (oldPi, oldPi1);
686            Off (SW_USE_FF_MOD_GCD);
687            return C;
688          }
689        }
690        pi2 = psr( pi, pi1, v );
691        pi2 = pi2 / bi;
692        pi = pi1; pi1 = pi2;
693        maxNumVars= tmax (getNumVars (pi), getNumVars (pi1));
694        if (!pi1.isUnivariate() && (size (pi1)/maxNumVars > 500))
695        {
696            On (SW_USE_FF_MOD_GCD);
697            C *= gcd (oldPi, oldPi1);
698            Off (SW_USE_FF_MOD_GCD);
699            return C;
700        }
701        if ( degree( pi1, v ) > 0 )
702        {
703            delta = degree( pi, v ) - degree( pi1, v );
704            powHi= power (Hi, delta-1);
705            if ( (delta+1) % 2 )
706                bi = LC( pi, v ) * powHi*Hi;
707            else
708                bi = -LC( pi, v ) * powHi*Hi;
709            Hi = power( LC( pi1, v ), delta ) / powHi;
710            if (!(pi.isUnivariate() && pi1.isUnivariate()))
711            {
712              if (size (Hi)*size (pi)/(maxNumVars*3) > 1500) //maybe this needs more tuning
713              {
714                On (SW_USE_FF_MOD_GCD);
715                C *= gcd (oldPi, oldPi1);
716                Off (SW_USE_FF_MOD_GCD);
717                return C;
718              }
719            }
720        }
721    }
722    if ( degree( pi1, v ) == 0 )
723    {
724      C=abs(C);
725      //out_cf("GCD:",C,"\n");
726      return C;
727    }
728    if (!pi.isUnivariate())
729    {
730      if (!ezgcdon)
731        On (SW_USE_EZGCD_P);
732      Ci= gcd (LC (oldPi,v), LC (oldPi1,v));
733      pi /= LC (pi,v)/Ci;
734      Ci= content (pi);
735      pi /= Ci;
736      if (!ezgcdon)
737        Off (SW_USE_EZGCD_P);
738    }
739    if ( bpure )
740        pi /= pi.lc();
741    C=abs(C*pi);
742    //out_cf("GCD:",C,"\n");
743    return C;
744}
745
746static CanonicalForm
747gcd_poly_0( const CanonicalForm & f, const CanonicalForm & g )
748{
749    CanonicalForm pi, pi1;
750    CanonicalForm C, Ci, Ci1, Hi, bi, pi2;
751    int delta = degree( f ) - degree( g );
752
753    if ( delta >= 0 )
754    {
755        pi = f; pi1 = g;
756    }
757    else
758    {
759        pi = g; pi1 = f; delta = -delta;
760    }
761    Ci = content( pi ); Ci1 = content( pi1 );
762    pi1 = pi1 / Ci1; pi = pi / Ci;
763    C = gcd( Ci, Ci1 );
764    int d= 0;
765    if ( pi.isUnivariate() && pi1.isUnivariate() )
766    {
767#ifdef HAVE_FLINT
768        if (isPurePoly(pi) && isPurePoly(pi1) )
769            return gcd_univar_flint0(pi, pi1 ) * C;
770#else
771#ifdef HAVE_NTL
772        if ( isOn(SW_USE_NTL_GCD_0) && isPurePoly(pi) && isPurePoly(pi1) )
773            return gcd_univar_ntl0(pi, pi1 ) * C;
774#endif
775#endif
776        return gcd_poly_univar0( pi, pi1, true ) * C;
777    }
778    else if ( gcd_test_one( pi1, pi, true, d ) )
779      return C;
780    Variable v = f.mvar();
781    Hi = power( LC( pi1, v ), delta );
782    if ( (delta+1) % 2 )
783        bi = 1;
784    else
785        bi = -1;
786    while ( degree( pi1, v ) > 0 )
787    {
788        pi2 = psr( pi, pi1, v );
789        pi2 = pi2 / bi;
790        pi = pi1; pi1 = pi2;
791        if ( degree( pi1, v ) > 0 )
792        {
793            delta = degree( pi, v ) - degree( pi1, v );
794            if ( (delta+1) % 2 )
795                bi = LC( pi, v ) * power( Hi, delta );
796            else
797                bi = -LC( pi, v ) * power( Hi, delta );
798            Hi = power( LC( pi1, v ), delta ) / power( Hi, delta-1 );
799        }
800    }
801    if ( degree( pi1, v ) == 0 )
802        return C;
803    else
804        return C * pp( pi );
805}
806
807//{{{ CanonicalForm gcd_poly ( const CanonicalForm & f, const CanonicalForm & g )
808//{{{ docu
809//
810// gcd_poly() - calculate polynomial gcd.
811//
812// This is the dispatcher for polynomial gcd calculation.  We call either
813// ezgcd(), sparsemod() or gcd_poly1() in dependecy on the current
814// characteristic and settings of SW_USE_EZGCD.
815//
816// Used by gcd() and gcd_poly_univar0().
817//
818//}}}
819#if 0
820int si_factor_reminder=1;
821#endif
822CanonicalForm gcd_poly ( const CanonicalForm & f, const CanonicalForm & g )
823{
824  CanonicalForm fc, gc, d1;
825  bool fc_isUnivariate=f.isUnivariate();
826  bool gc_isUnivariate=g.isUnivariate();
827  bool fc_and_gc_Univariate=fc_isUnivariate && gc_isUnivariate;
828  fc = f;
829  gc = g;
830  if ( getCharacteristic() != 0 )
831  {
832    #ifdef HAVE_NTL
833    if ((!fc_and_gc_Univariate) && (isOn( SW_USE_EZGCD_P )))
834    {
835      fc= EZGCD_P (fc, gc);
836    }
837    else if (isOn(SW_USE_FF_MOD_GCD) && !fc_and_gc_Univariate)
838    {
839      Variable a;
840      if (hasFirstAlgVar (fc, a) || hasFirstAlgVar (gc, a))
841        fc=GCD_Fp_extension (fc, gc, a);
842      else if (CFFactory::gettype() == GaloisFieldDomain)
843        fc=GCD_GF (fc, gc);
844      else
845        fc=GCD_small_p (fc, gc);
846    }
847    else
848    #endif
849    fc = gcd_poly_p( fc, gc );
850  }
851  else if (!fc_and_gc_Univariate)
852  {
853    if ( isOn( SW_USE_EZGCD ) )
854      fc= ezgcd (fc, gc);
855    else if (isOn(SW_USE_CHINREM_GCD))
856      fc = chinrem_gcd( fc, gc);
857    else
858    {
859       fc = gcd_poly_0( fc, gc );
860    }
861  }
862  else
863  {
864    fc = gcd_poly_0( fc, gc );
865  }
866  if ( d1.degree() > 0 )
867    fc *= d1;
868  return fc;
869}
870//}}}
871
872//{{{ static CanonicalForm cf_content ( const CanonicalForm & f, const CanonicalForm & g )
873//{{{ docu
874//
875// cf_content() - return gcd(g, content(f)).
876//
877// content(f) is calculated with respect to f's main variable.
878//
879// Used by gcd(), content(), content( CF, Variable ).
880//
881//}}}
882static CanonicalForm
883cf_content ( const CanonicalForm & f, const CanonicalForm & g )
884{
885    if ( f.inPolyDomain() || ( f.inExtension() && ! getReduce( f.mvar() ) ) )
886    {
887        CFIterator i = f;
888        CanonicalForm result = g;
889        while ( i.hasTerms() && ! result.isOne() )
890        {
891            result = gcd( i.coeff(), result );
892            i++;
893        }
894        return result;
895    }
896    else
897        return abs( f );
898}
899//}}}
900
901//{{{ CanonicalForm content ( const CanonicalForm & f )
902//{{{ docu
903//
904// content() - return content(f) with respect to main variable.
905//
906// Normalizes result.
907//
908//}}}
909CanonicalForm
910content ( const CanonicalForm & f )
911{
912    if ( f.inPolyDomain() || ( f.inExtension() && ! getReduce( f.mvar() ) ) )
913    {
914        CFIterator i = f;
915        CanonicalForm result = abs( i.coeff() );
916        i++;
917        while ( i.hasTerms() && ! result.isOne() )
918        {
919            result = gcd( i.coeff(), result );
920            i++;
921        }
922        return result;
923    }
924    else
925        return abs( f );
926}
927//}}}
928
929//{{{ CanonicalForm content ( const CanonicalForm & f, const Variable & x )
930//{{{ docu
931//
932// content() - return content(f) with respect to x.
933//
934// x should be a polynomial variable.
935//
936//}}}
937CanonicalForm
938content ( const CanonicalForm & f, const Variable & x )
939{
940    ASSERT( x.level() > 0, "cannot calculate content with respect to algebraic variable" );
941    Variable y = f.mvar();
942
943    if ( y == x )
944        return cf_content( f, 0 );
945    else  if ( y < x )
946        return f;
947    else
948        return swapvar( content( swapvar( f, y, x ), y ), y, x );
949}
950//}}}
951
952//{{{ CanonicalForm vcontent ( const CanonicalForm & f, const Variable & x )
953//{{{ docu
954//
955// vcontent() - return content of f with repect to variables >= x.
956//
957// The content is recursively calculated over all coefficients in
958// f having level less than x.  x should be a polynomial
959// variable.
960//
961//}}}
962CanonicalForm
963vcontent ( const CanonicalForm & f, const Variable & x )
964{
965    ASSERT( x.level() > 0, "cannot calculate vcontent with respect to algebraic variable" );
966
967    if ( f.mvar() <= x )
968        return content( f, x );
969    else {
970        CFIterator i;
971        CanonicalForm d = 0;
972        for ( i = f; i.hasTerms() && ! d.isOne(); i++ )
973            d = gcd( d, vcontent( i.coeff(), x ) );
974        return d;
975    }
976}
977//}}}
978
979//{{{ CanonicalForm pp ( const CanonicalForm & f )
980//{{{ docu
981//
982// pp() - return primitive part of f.
983//
984// Returns zero if f equals zero, otherwise f / content(f).
985//
986//}}}
987CanonicalForm
988pp ( const CanonicalForm & f )
989{
990    if ( f.isZero() )
991        return f;
992    else
993        return f / content( f );
994}
995//}}}
996
997CanonicalForm
998gcd ( const CanonicalForm & f, const CanonicalForm & g )
999{
1000    bool b = f.isZero();
1001    if ( b || g.isZero() )
1002    {
1003        if ( b )
1004            return abs( g );
1005        else
1006            return abs( f );
1007    }
1008    if ( f.inPolyDomain() || g.inPolyDomain() )
1009    {
1010        if ( f.mvar() != g.mvar() )
1011        {
1012            if ( f.mvar() > g.mvar() )
1013                return cf_content( f, g );
1014            else
1015                return cf_content( g, f );
1016        }
1017        if (isOn(SW_USE_QGCD))
1018        {
1019          Variable m;
1020          if (
1021          (getCharacteristic() == 0) &&
1022          (hasFirstAlgVar(f,m) || hasFirstAlgVar(g,m))
1023          )
1024          {
1025            bool on_rational = isOn(SW_RATIONAL);
1026            CanonicalForm r=QGCD(f,g);
1027            On(SW_RATIONAL);
1028            CanonicalForm cdF = bCommonDen( r );
1029            if (!on_rational) Off(SW_RATIONAL);
1030            return cdF*r;
1031          }
1032        }
1033
1034        if ( f.inExtension() && getReduce( f.mvar() ) )
1035            return CanonicalForm(1);
1036        else
1037        {
1038            if ( fdivides( f, g ) )
1039                return abs( f );
1040            else  if ( fdivides( g, f ) )
1041                return abs( g );
1042            if ( !( getCharacteristic() == 0 && isOn( SW_RATIONAL ) ) )
1043            {
1044                CanonicalForm d;
1045                d = gcd_poly( f, g );
1046                return abs( d );
1047            }
1048            else
1049            {
1050                //printf ("here\n");
1051                CanonicalForm cdF = bCommonDen( f );
1052                CanonicalForm cdG = bCommonDen( g );
1053                Off( SW_RATIONAL );
1054                CanonicalForm l = lcm( cdF, cdG );
1055                On( SW_RATIONAL );
1056                CanonicalForm F = f * l, G = g * l;
1057                Off( SW_RATIONAL );
1058                l = gcd_poly( F, G );
1059                On( SW_RATIONAL );
1060                return abs( l );
1061            }
1062        }
1063    }
1064    if ( f.inBaseDomain() && g.inBaseDomain() )
1065        return bgcd( f, g );
1066    else
1067        return 1;
1068}
1069
1070//{{{ CanonicalForm lcm ( const CanonicalForm & f, const CanonicalForm & g )
1071//{{{ docu
1072//
1073// lcm() - return least common multiple of f and g.
1074//
1075// The lcm is calculated using the formula lcm(f, g) = f * g / gcd(f, g).
1076//
1077// Returns zero if one of f or g equals zero.
1078//
1079//}}}
1080CanonicalForm
1081lcm ( const CanonicalForm & f, const CanonicalForm & g )
1082{
1083    if ( f.isZero() || g.isZero() )
1084        return 0;
1085    else
1086        return ( f / gcd( f, g ) ) * g;
1087}
1088//}}}
1089
1090#ifdef HAVE_NTL
1091#ifndef HAVE_FLINT
1092static CanonicalForm
1093gcd_univar_ntl0( const CanonicalForm & F, const CanonicalForm & G )
1094{
1095    ZZX F1=convertFacCF2NTLZZX(F);
1096    ZZX G1=convertFacCF2NTLZZX(G);
1097    ZZX R=GCD(F1,G1);
1098    return convertNTLZZX2CF(R,F.mvar());
1099}
1100
1101static CanonicalForm
1102gcd_univar_ntlp( const CanonicalForm & F, const CanonicalForm & G )
1103{
1104  if (fac_NTL_char!=getCharacteristic())
1105  {
1106    fac_NTL_char=getCharacteristic();
1107    zz_p::init(getCharacteristic());
1108  }
1109  zz_pX F1=convertFacCF2NTLzzpX(F);
1110  zz_pX G1=convertFacCF2NTLzzpX(G);
1111  zz_pX R=GCD(F1,G1);
1112  return  convertNTLzzpX2CF(R,F.mvar());
1113}
1114#endif
1115#endif
1116
1117#ifdef HAVE_FLINT
1118static CanonicalForm
1119gcd_univar_flintp (const CanonicalForm& F, const CanonicalForm& G)
1120{
1121  nmod_poly_t F1, G1;
1122  convertFacCF2nmod_poly_t (F1, F);
1123  convertFacCF2nmod_poly_t (G1, G);
1124  nmod_poly_gcd (F1, F1, G1);
1125  CanonicalForm result= convertnmod_poly_t2FacCF (F1, F.mvar());
1126  nmod_poly_clear (F1);
1127  nmod_poly_clear (G1);
1128  return result;
1129}
1130
1131static CanonicalForm
1132gcd_univar_flint0( const CanonicalForm & F, const CanonicalForm & G )
1133{
1134  fmpz_poly_t F1, G1;
1135  convertFacCF2Fmpz_poly_t(F1, F);
1136  convertFacCF2Fmpz_poly_t(G1, G);
1137  fmpz_poly_gcd (F1, F1, G1);
1138  CanonicalForm result= convertFmpz_poly_t2FacCF (F1, F.mvar());
1139  fmpz_poly_clear (F1);
1140  fmpz_poly_clear (G1);
1141  return result;
1142}
1143#endif
1144
1145
1146/*
1147*  compute positions p1 and pe of optimal variables:
1148*    pe is used in "ezgcd" and
1149*    p1 in "gcd_poly1"
1150*/
1151/*static
1152void optvalues ( const int * df, const int * dg, const int n, int & p1, int &pe )
1153{
1154    int i, o1, oe;
1155    if ( df[n] > dg[n] )
1156    {
1157        o1 = df[n]; oe = dg[n];
1158    }
1159    else
1160    {
1161        o1 = dg[n]; oe = df[n];
1162    }
1163    i = n-1;
1164    while ( i > 0 )
1165    {
1166        if ( df[i] != 0 )
1167        {
1168            if ( df[i] > dg[i] )
1169            {
1170                if ( o1 > df[i]) { o1 = df[i]; p1 = i; }
1171                if ( oe <= dg[i]) { oe = dg[i]; pe = i; }
1172            }
1173            else
1174            {
1175                if ( o1 > dg[i]) { o1 = dg[i]; p1 = i; }
1176                if ( oe <= df[i]) { oe = df[i]; pe = i; }
1177            }
1178        }
1179        i--;
1180    }
1181}*/
1182
1183/*
1184*  make some changes of variables, see optvalues
1185*/
1186/*static void
1187cf_prepgcd( const CanonicalForm & f, const CanonicalForm & g, int & cc, int & p1, int &pe )
1188{
1189    int i, k, n;
1190    n = f.level();
1191    cc = 0;
1192    p1 = pe = n;
1193    if ( n == 1 )
1194        return;
1195    int * degsf = new int[n+1];
1196    int * degsg = new int[n+1];
1197    for ( i = n; i > 0; i-- )
1198    {
1199        degsf[i] = degsg[i] = 0;
1200    }
1201    degsf = degrees( f, degsf );
1202    degsg = degrees( g, degsg );
1203
1204    k = 0;
1205    for ( i = n-1; i > 0; i-- )
1206    {
1207        if ( degsf[i] == 0 )
1208        {
1209            if ( degsg[i] != 0 )
1210            {
1211                cc = -i;
1212                break;
1213            }
1214        }
1215        else
1216        {
1217            if ( degsg[i] == 0 )
1218            {
1219                cc = i;
1220                break;
1221            }
1222            else k++;
1223        }
1224    }
1225
1226    if ( ( cc == 0 ) && ( k != 0 ) )
1227        optvalues( degsf, degsg, n, p1, pe );
1228    if ( ( pe != 1 ) && ( degsf[1] != 0 ) )
1229        pe = -pe;
1230
1231    delete [] degsf;
1232    delete [] degsg;
1233}*/
1234
1235TIMING_DEFINE_PRINT(chinrem_termination)
1236TIMING_DEFINE_PRINT(chinrem_recursion)
1237
1238CanonicalForm chinrem_gcd ( const CanonicalForm & FF, const CanonicalForm & GG )
1239{
1240  CanonicalForm f, g, cl, q(0), Dp, newD, D, newq, newqh;
1241  int p, i, dp_deg, d_deg=-1;
1242
1243  CanonicalForm cd ( bCommonDen( FF ));
1244  f=cd*FF;
1245  Variable x= Variable (1);
1246  CanonicalForm cf, cg;
1247  cf= icontent (f);
1248  f /= cf;
1249  //cd = bCommonDen( f ); f *=cd;
1250  //f /=vcontent(f,Variable(1));
1251
1252  cd = bCommonDen( GG );
1253  g=cd*GG;
1254  cg= icontent (g);
1255  g /= cg;
1256  //cd = bCommonDen( g ); g *=cd;
1257  //g /=vcontent(g,Variable(1));
1258
1259  CanonicalForm Dn, test= 0;
1260  CanonicalForm lcf, lcg;
1261  lcf= f.lc();
1262  lcg= g.lc();
1263  cl =  gcd (f.lc(),g.lc());
1264  CanonicalForm gcdcfcg= gcd (cf, cg);
1265  CanonicalForm fp, gp;
1266  CanonicalForm b= 1;
1267  int minCommonDeg= 0;
1268  for (i= tmax (f.level(), g.level()); i > 0; i--)
1269  {
1270    if (degree (f, i) <= 0 || degree (g, i) <= 0)
1271      continue;
1272    else
1273    {
1274      minCommonDeg= tmin (degree (g, i), degree (f, i));
1275      break;
1276    }
1277  }
1278  if (i == 0)
1279    return gcdcfcg;
1280  for (; i > 0; i--)
1281  {
1282    if (degree (f, i) <= 0 || degree (g, i) <= 0)
1283      continue;
1284    else
1285      minCommonDeg= tmin (minCommonDeg, tmin (degree (g, i), degree (f, i)));
1286  }
1287  b= 2*tmin (maxNorm (f), maxNorm (g))*abs (cl)*
1288     power (CanonicalForm (2), minCommonDeg);
1289  bool equal= false;
1290  i = cf_getNumBigPrimes() - 1;
1291
1292  CanonicalForm cof, cog, cofp, cogp, newCof, newCog, cofn, cogn, cDn;
1293  int maxNumVars= tmax (getNumVars (f), getNumVars (g));
1294  //Off (SW_RATIONAL);
1295  while ( true )
1296  {
1297    p = cf_getBigPrime( i );
1298    i--;
1299    while ( i >= 0 && mod( cl*(lc(f)/cl)*(lc(g)/cl), p ) == 0 )
1300    {
1301      p = cf_getBigPrime( i );
1302      i--;
1303    }
1304    //printf("try p=%d\n",p);
1305    setCharacteristic( p );
1306    fp= mapinto (f);
1307    gp= mapinto (g);
1308    TIMING_START (chinrem_recursion)
1309#ifdef HAVE_NTL
1310    if (size (fp)/maxNumVars > 500 && size (gp)/maxNumVars > 500)
1311      Dp = GCD_small_p (fp, gp, cofp, cogp);
1312    else
1313    {
1314      Dp= gcd_poly (fp, gp);
1315      cofp= fp/Dp;
1316      cogp= gp/Dp;
1317    }
1318#else
1319    Dp= gcd_poly (fp, gp);
1320    cofp= fp/Dp;
1321    cogp= gp/Dp;
1322#endif
1323    TIMING_END_AND_PRINT (chinrem_recursion,
1324                          "time for gcd mod p in modular gcd: ");
1325    Dp /=Dp.lc();
1326    Dp *= mapinto (cl);
1327    cofp /= lc (cofp);
1328    cofp *= mapinto (lcf);
1329    cogp /= lc (cogp);
1330    cogp *= mapinto (lcg);
1331    setCharacteristic( 0 );
1332    dp_deg=totaldegree(Dp);
1333    if ( dp_deg == 0 )
1334    {
1335      //printf(" -> 1\n");
1336      return CanonicalForm(gcdcfcg);
1337    }
1338    if ( q.isZero() )
1339    {
1340      D = mapinto( Dp );
1341      cof= mapinto (cofp);
1342      cog= mapinto (cogp);
1343      d_deg=dp_deg;
1344      q = p;
1345      Dn= balance_p (D, p);
1346      cofn= balance_p (cof, p);
1347      cogn= balance_p (cog, p);
1348    }
1349    else
1350    {
1351      if ( dp_deg == d_deg )
1352      {
1353        chineseRemainder( D, q, mapinto( Dp ), p, newD, newq );
1354        chineseRemainder( cof, q, mapinto (cofp), p, newCof, newq);
1355        chineseRemainder( cog, q, mapinto (cogp), p, newCog, newq);
1356        cof= newCof;
1357        cog= newCog;
1358        newqh= newq/2;
1359        Dn= balance_p (newD, newq, newqh);
1360        cofn= balance_p (newCof, newq, newqh);
1361        cogn= balance_p (newCog, newq, newqh);
1362        if (test != Dn) //balance_p (newD, newq))
1363          test= balance_p (newD, newq);
1364        else
1365          equal= true;
1366        q = newq;
1367        D = newD;
1368      }
1369      else if ( dp_deg < d_deg )
1370      {
1371        //printf(" were all bad, try more\n");
1372        // all previous p's are bad primes
1373        q = p;
1374        D = mapinto( Dp );
1375        cof= mapinto (cof);
1376        cog= mapinto (cog);
1377        d_deg=dp_deg;
1378        test= 0;
1379        equal= false;
1380        Dn= balance_p (D, p);
1381        cofn= balance_p (cof, p);
1382        cogn= balance_p (cog, p);
1383      }
1384      else
1385      {
1386        //printf(" was bad, try more\n");
1387      }
1388      //else dp_deg > d_deg: bad prime
1389    }
1390    if ( i >= 0 )
1391    {
1392      cDn= icontent (Dn);
1393      Dn /= cDn;
1394      cofn /= cl/cDn;
1395      //cofn /= icontent (cofn);
1396      cogn /= cl/cDn;
1397      //cogn /= icontent (cogn);
1398      TIMING_START (chinrem_termination);
1399      if ((terminationTest (f,g, cofn, cogn, Dn)) ||
1400          ((equal || q > b) && fdivides (Dn, f) && fdivides (Dn, g)))
1401      {
1402        TIMING_END_AND_PRINT (chinrem_termination,
1403                            "time for successful termination in modular gcd: ");
1404        //printf(" -> success\n");
1405        return Dn*gcdcfcg;
1406      }
1407      TIMING_END_AND_PRINT (chinrem_termination,
1408                          "time for unsuccessful termination in modular gcd: ");
1409      equal= false;
1410      //else: try more primes
1411    }
1412    else
1413    { // try other method
1414      //printf("try other gcd\n");
1415      Off(SW_USE_CHINREM_GCD);
1416      D=gcd_poly( f, g );
1417      On(SW_USE_CHINREM_GCD);
1418      return D*gcdcfcg;
1419    }
1420  }
1421}
1422
1423
Note: See TracBrowser for help on using the repository browser.