source: git/factory/cf_gcd.cc @ 19d0392

spielwiese
Last change on this file since 19d0392 was 19d0392, checked in by Martin Lee <martinlee84@…>, 10 years ago
chg: disable gcd_poly_univar0 if NTL is around
  • Property mode set to 100644
File size: 35.1 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      if(!rr.isZero())
395      {
396        a=convertNTLZZX2CF(A,f.mvar())*fc/rr;
397        b=convertNTLZZX2CF(B,f.mvar())*gc/rr;
398        return CanonicalForm(1);
399      }
400      else
401      {
402        Off(SW_USE_NTL_GCD_0);
403        r=extgcd(f,g,a,b);
404        if (isOn(SW_RATIONAL))
405        {
406          a/=r.lc();
407          b/=r.lc();
408          r/=r.lc();
409        }
410        On(SW_USE_NTL_GCD_0);
411      }
412    }
413    else
414    {
415      XGCD(RR,A,B,F1,G1,1);
416      CanonicalForm rr=convertZZ2CF(RR);
417      if (!rr.isZero())
418      {
419        a=convertNTLZZX2CF(A,f.mvar())*fc;
420        b=convertNTLZZX2CF(B,f.mvar())*gc;
421      }
422      else
423      {
424        Off(SW_USE_NTL_GCD_0);
425        r=extgcd(f,g,a,b);
426        if (isOn(SW_RATIONAL))
427        {
428          a/=r.lc();
429          b/=r.lc();
430          r/=r.lc();
431        }
432        On(SW_USE_NTL_GCD_0);
433      }
434      return r;
435    }
436  }
437#endif
438#endif
439  // may contain bug in the co-factors, see track 107
440  CanonicalForm contf = content( f );
441  CanonicalForm contg = content( g );
442
443  CanonicalForm p0 = f / contf, p1 = g / contg;
444  CanonicalForm f0 = 1, f1 = 0, g0 = 0, g1 = 1, q, r;
445
446  while ( ! p1.isZero() )
447  {
448      divrem( p0, p1, q, r );
449      p0 = p1; p1 = r;
450      r = g0 - g1 * q;
451      g0 = g1; g1 = r;
452      r = f0 - f1 * q;
453      f0 = f1; f1 = r;
454  }
455  CanonicalForm contp0 = content( p0 );
456  a = f0 / ( contf * contp0 );
457  b = g0 / ( contg * contp0 );
458  p0 /= contp0;
459  if ( p0.sign() < 0 )
460  {
461      p0 = -p0;
462      a = -a;
463      b = -b;
464  }
465  return p0;
466}
467//}}}
468
469//{{{ static CanonicalForm balance_p ( const CanonicalForm & f, const CanonicalForm & q )
470//{{{ docu
471//
472// balance_p() - map f from positive to symmetric representation
473//   mod q.
474//
475// This makes sense for univariate polynomials over Z only.
476// q should be an integer.
477//
478// Used by gcd_poly_univar0().
479//
480//}}}
481
482static CanonicalForm
483balance_p ( const CanonicalForm & f, const CanonicalForm & q, const CanonicalForm & qh )
484{
485    Variable x = f.mvar();
486    CanonicalForm result = 0;
487    CanonicalForm c;
488    CFIterator i;
489    for ( i = f; i.hasTerms(); i++ )
490    {
491        c = i.coeff();
492        if ( c.inCoeffDomain())
493        {
494          if ( c > qh )
495            result += power( x, i.exp() ) * (c - q);
496          else
497            result += power( x, i.exp() ) * c;
498        }
499        else
500          result += power( x, i.exp() ) * balance_p(c,q,qh);
501    }
502    return result;
503}
504
505static CanonicalForm
506balance_p ( const CanonicalForm & f, const CanonicalForm & q )
507{
508    CanonicalForm qh = q / 2;
509    return balance_p (f, q, qh);
510}
511
512/*static CanonicalForm
513balance ( const CanonicalForm & f, const CanonicalForm & q )
514{
515    Variable x = f.mvar();
516    CanonicalForm result = 0, qh = q / 2;
517    CanonicalForm c;
518    CFIterator i;
519    for ( i = f; i.hasTerms(); i++ ) {
520        c = mod( i.coeff(), q );
521        if ( c > qh )
522            result += power( x, i.exp() ) * (c - q);
523        else
524            result += power( x, i.exp() ) * c;
525    }
526    return result;
527}*/
528//}}}
529
530#ifndef HAVE_NTL
531static CanonicalForm gcd_poly_univar0( const CanonicalForm & F, const CanonicalForm & G, bool primitive )
532{
533  CanonicalForm f, g, c, cg, cl, BB, B, M, q, Dp, newD, D, newq;
534  int p, i;
535
536  if ( primitive )
537  {
538    f = F;
539    g = G;
540    c = 1;
541  }
542  else
543  {
544    CanonicalForm cF = content( F ), cG = content( G );
545    f = F / cF;
546    g = G / cG;
547    c = bgcd( cF, cG );
548  }
549  cg = gcd( f.lc(), g.lc() );
550  cl = ( f.lc() / cg ) * g.lc();
551//     B = 2 * cg * tmin(
552//         maxnorm(f)*power(CanonicalForm(2),f.degree())*isqrt(f.degree()+1),
553//         maxnorm(g)*power(CanonicalForm(2),g.degree())*isqrt(g.degree()+1)
554//         )+1;
555  M = tmin( maxNorm(f), maxNorm(g) );
556  BB = power(CanonicalForm(2),tmin(f.degree(),g.degree()))*M;
557  q = 0;
558  i = cf_getNumSmallPrimes() - 1;
559  while ( true )
560  {
561    B = BB;
562    while ( i >= 0 && q < B )
563    {
564      p = cf_getSmallPrime( i );
565      i--;
566      while ( i >= 0 && mod( cl, p ) == 0 )
567      {
568        p = cf_getSmallPrime( i );
569        i--;
570      }
571      setCharacteristic( p );
572      Dp = gcd( mapinto( f ), mapinto( g ) );
573      Dp = ( Dp / Dp.lc() ) * mapinto( cg );
574      setCharacteristic( 0 );
575      if ( Dp.degree() == 0 )
576        return c;
577      if ( q.isZero() )
578      {
579        D = mapinto( Dp );
580        q = p;
581        B = power(CanonicalForm(2),D.degree())*M+1;
582      }
583      else
584      {
585        if ( Dp.degree() == D.degree() )
586        {
587          chineseRemainder( D, q, mapinto( Dp ), p, newD, newq );
588          q = newq;
589          D = newD;
590        }
591        else if ( Dp.degree() < D.degree() )
592        {
593          // all previous p's are bad primes
594          q = p;
595          D = mapinto( Dp );
596          B = power(CanonicalForm(2),D.degree())*M+1;
597        }
598        // else p is a bad prime
599      }
600    }
601    if ( i >= 0 )
602    {
603      // now balance D mod q
604      D = pp( balance_p( D, q ) );
605      if ( fdivides( D, f ) && fdivides( D, g ) )
606        return D * c;
607      else
608        q = 0;
609    }
610    else
611      return gcd_poly( F, G );
612    DEBOUTLN( cerr, "another try ..." );
613  }
614}
615#endif
616
617static CanonicalForm
618gcd_poly_p( const CanonicalForm & f, const CanonicalForm & g )
619{
620    if (f.inCoeffDomain() || g.inCoeffDomain()) //zero case should be caught by gcd
621      return 1;
622    CanonicalForm pi, pi1;
623    CanonicalForm C, Ci, Ci1, Hi, bi, pi2;
624    bool bpure, ezgcdon= isOn (SW_USE_EZGCD_P);
625    int delta = degree( f ) - degree( g );
626
627    if ( delta >= 0 )
628    {
629        pi = f; pi1 = g;
630    }
631    else
632    {
633        pi = g; pi1 = f; delta = -delta;
634    }
635    if (pi.isUnivariate())
636      Ci= 1;
637    else
638    {
639      if (!ezgcdon)
640        On (SW_USE_EZGCD_P);
641      Ci = content( pi );
642      if (!ezgcdon)
643        Off (SW_USE_EZGCD_P);
644      pi = pi / Ci;
645    }
646    if (pi1.isUnivariate())
647      Ci1= 1;
648    else
649    {
650      if (!ezgcdon)
651        On (SW_USE_EZGCD_P);
652      Ci1 = content( pi1 );
653      if (!ezgcdon)
654        Off (SW_USE_EZGCD_P);
655      pi1 = pi1 / Ci1;
656    }
657    C = gcd( Ci, Ci1 );
658    int d= 0;
659    if ( !( pi.isUnivariate() && pi1.isUnivariate() ) )
660    {
661        if ( gcd_test_one( pi1, pi, true, d ) )
662        {
663          C=abs(C);
664          //out_cf("GCD:",C,"\n");
665          return C;
666        }
667        bpure = false;
668    }
669    else
670    {
671        bpure = isPurePoly(pi) && isPurePoly(pi1);
672#ifdef HAVE_FLINT
673        if (bpure && (CFFactory::gettype() != GaloisFieldDomain))
674          return gcd_univar_flintp(pi,pi1)*C;
675#else
676#ifdef HAVE_NTL
677        if ( isOn(SW_USE_NTL_GCD_P) && bpure && (CFFactory::gettype() != GaloisFieldDomain))
678            return gcd_univar_ntlp(pi, pi1 ) * C;
679#endif
680#endif
681    }
682    Variable v = f.mvar();
683    Hi = power( LC( pi1, v ), delta );
684    int maxNumVars= tmax (getNumVars (pi), getNumVars (pi1));
685
686    if (!(pi.isUnivariate() && pi1.isUnivariate()))
687    {
688      if (size (Hi)*size (pi)/(maxNumVars*3) > 500) //maybe this needs more tuning
689      {
690        On (SW_USE_FF_MOD_GCD);
691        C *= gcd (pi, pi1);
692        Off (SW_USE_FF_MOD_GCD);
693        return C;
694      }
695    }
696
697    if ( (delta+1) % 2 )
698        bi = 1;
699    else
700        bi = -1;
701    CanonicalForm oldPi= pi, oldPi1= pi1, powHi;
702    while ( degree( pi1, v ) > 0 )
703    {
704        if (!(pi.isUnivariate() && pi1.isUnivariate()))
705        {
706          if (size (pi)/maxNumVars > 500 || size (pi1)/maxNumVars > 500)
707          {
708            On (SW_USE_FF_MOD_GCD);
709            C *= gcd (oldPi, oldPi1);
710            Off (SW_USE_FF_MOD_GCD);
711            return C;
712          }
713        }
714        pi2 = psr( pi, pi1, v );
715        pi2 = pi2 / bi;
716        pi = pi1; pi1 = pi2;
717        maxNumVars= tmax (getNumVars (pi), getNumVars (pi1));
718        if (!pi1.isUnivariate() && (size (pi1)/maxNumVars > 500))
719        {
720            On (SW_USE_FF_MOD_GCD);
721            C *= gcd (oldPi, oldPi1);
722            Off (SW_USE_FF_MOD_GCD);
723            return C;
724        }
725        if ( degree( pi1, v ) > 0 )
726        {
727            delta = degree( pi, v ) - degree( pi1, v );
728            powHi= power (Hi, delta-1);
729            if ( (delta+1) % 2 )
730                bi = LC( pi, v ) * powHi*Hi;
731            else
732                bi = -LC( pi, v ) * powHi*Hi;
733            Hi = power( LC( pi1, v ), delta ) / powHi;
734            if (!(pi.isUnivariate() && pi1.isUnivariate()))
735            {
736              if (size (Hi)*size (pi)/(maxNumVars*3) > 1500) //maybe this needs more tuning
737              {
738                On (SW_USE_FF_MOD_GCD);
739                C *= gcd (oldPi, oldPi1);
740                Off (SW_USE_FF_MOD_GCD);
741                return C;
742              }
743            }
744        }
745    }
746    if ( degree( pi1, v ) == 0 )
747    {
748      C=abs(C);
749      //out_cf("GCD:",C,"\n");
750      return C;
751    }
752    if (!pi.isUnivariate())
753    {
754      if (!ezgcdon)
755        On (SW_USE_EZGCD_P);
756      Ci= gcd (LC (oldPi,v), LC (oldPi1,v));
757      pi /= LC (pi,v)/Ci;
758      Ci= content (pi);
759      pi /= Ci;
760      if (!ezgcdon)
761        Off (SW_USE_EZGCD_P);
762    }
763    if ( bpure )
764        pi /= pi.lc();
765    C=abs(C*pi);
766    //out_cf("GCD:",C,"\n");
767    return C;
768}
769
770static CanonicalForm
771gcd_poly_0( const CanonicalForm & f, const CanonicalForm & g )
772{
773    CanonicalForm pi, pi1;
774    CanonicalForm C, Ci, Ci1, Hi, bi, pi2;
775    int delta = degree( f ) - degree( g );
776
777    if ( delta >= 0 )
778    {
779        pi = f; pi1 = g;
780    }
781    else
782    {
783        pi = g; pi1 = f; delta = -delta;
784    }
785    Ci = content( pi ); Ci1 = content( pi1 );
786    pi1 = pi1 / Ci1; pi = pi / Ci;
787    C = gcd( Ci, Ci1 );
788    int d= 0;
789    if ( pi.isUnivariate() && pi1.isUnivariate() )
790    {
791#ifdef HAVE_FLINT
792        if (isPurePoly(pi) && isPurePoly(pi1) )
793            return gcd_univar_flint0(pi, pi1 ) * C;
794#else
795#ifdef HAVE_NTL
796        if ( isOn(SW_USE_NTL_GCD_0) && isPurePoly(pi) && isPurePoly(pi1) )
797            return gcd_univar_ntl0(pi, pi1 ) * C;
798#endif
799#endif
800#ifndef HAVE_NTL
801        return gcd_poly_univar0( pi, pi1, true ) * C;
802#endif
803    }
804    else if ( gcd_test_one( pi1, pi, true, d ) )
805      return C;
806    Variable v = f.mvar();
807    Hi = power( LC( pi1, v ), delta );
808    if ( (delta+1) % 2 )
809        bi = 1;
810    else
811        bi = -1;
812    while ( degree( pi1, v ) > 0 )
813    {
814        pi2 = psr( pi, pi1, v );
815        pi2 = pi2 / bi;
816        pi = pi1; pi1 = pi2;
817        if ( degree( pi1, v ) > 0 )
818        {
819            delta = degree( pi, v ) - degree( pi1, v );
820            if ( (delta+1) % 2 )
821                bi = LC( pi, v ) * power( Hi, delta );
822            else
823                bi = -LC( pi, v ) * power( Hi, delta );
824            Hi = power( LC( pi1, v ), delta ) / power( Hi, delta-1 );
825        }
826    }
827    if ( degree( pi1, v ) == 0 )
828        return C;
829    else
830        return C * pp( pi );
831}
832
833//{{{ CanonicalForm gcd_poly ( const CanonicalForm & f, const CanonicalForm & g )
834//{{{ docu
835//
836// gcd_poly() - calculate polynomial gcd.
837//
838// This is the dispatcher for polynomial gcd calculation.  We call either
839// ezgcd(), sparsemod() or gcd_poly1() in dependecy on the current
840// characteristic and settings of SW_USE_EZGCD.
841//
842// Used by gcd() and gcd_poly_univar0().
843//
844//}}}
845#if 0
846int si_factor_reminder=1;
847#endif
848CanonicalForm gcd_poly ( const CanonicalForm & f, const CanonicalForm & g )
849{
850  CanonicalForm fc, gc, d1;
851  bool fc_isUnivariate=f.isUnivariate();
852  bool gc_isUnivariate=g.isUnivariate();
853  bool fc_and_gc_Univariate=fc_isUnivariate && gc_isUnivariate;
854  fc = f;
855  gc = g;
856  if ( getCharacteristic() != 0 )
857  {
858    #ifdef HAVE_NTL
859    if ((!fc_and_gc_Univariate) && (isOn( SW_USE_EZGCD_P )))
860    {
861      fc= EZGCD_P (fc, gc);
862    }
863    else if (isOn(SW_USE_FF_MOD_GCD) && !fc_and_gc_Univariate)
864    {
865      Variable a;
866      if (hasFirstAlgVar (fc, a) || hasFirstAlgVar (gc, a))
867        fc=GCD_Fp_extension (fc, gc, a);
868      else if (CFFactory::gettype() == GaloisFieldDomain)
869        fc=GCD_GF (fc, gc);
870      else
871        fc=GCD_small_p (fc, gc);
872    }
873    else
874    #endif
875    fc = gcd_poly_p( fc, gc );
876  }
877  else if (!fc_and_gc_Univariate)
878  {
879    if ( isOn( SW_USE_EZGCD ) )
880      fc= ezgcd (fc, gc);
881    else if (isOn(SW_USE_CHINREM_GCD))
882      fc = chinrem_gcd( fc, gc);
883    else
884    {
885       fc = gcd_poly_0( fc, gc );
886    }
887  }
888  else
889  {
890    fc = gcd_poly_0( fc, gc );
891  }
892  if ( d1.degree() > 0 )
893    fc *= d1;
894  return fc;
895}
896//}}}
897
898//{{{ static CanonicalForm cf_content ( const CanonicalForm & f, const CanonicalForm & g )
899//{{{ docu
900//
901// cf_content() - return gcd(g, content(f)).
902//
903// content(f) is calculated with respect to f's main variable.
904//
905// Used by gcd(), content(), content( CF, Variable ).
906//
907//}}}
908static CanonicalForm
909cf_content ( const CanonicalForm & f, const CanonicalForm & g )
910{
911    if ( f.inPolyDomain() || ( f.inExtension() && ! getReduce( f.mvar() ) ) )
912    {
913        CFIterator i = f;
914        CanonicalForm result = g;
915        while ( i.hasTerms() && ! result.isOne() )
916        {
917            result = gcd( i.coeff(), result );
918            i++;
919        }
920        return result;
921    }
922    else
923        return abs( f );
924}
925//}}}
926
927//{{{ CanonicalForm content ( const CanonicalForm & f )
928//{{{ docu
929//
930// content() - return content(f) with respect to main variable.
931//
932// Normalizes result.
933//
934//}}}
935CanonicalForm
936content ( const CanonicalForm & f )
937{
938    if ( f.inPolyDomain() || ( f.inExtension() && ! getReduce( f.mvar() ) ) )
939    {
940        CFIterator i = f;
941        CanonicalForm result = abs( i.coeff() );
942        i++;
943        while ( i.hasTerms() && ! result.isOne() )
944        {
945            result = gcd( i.coeff(), result );
946            i++;
947        }
948        return result;
949    }
950    else
951        return abs( f );
952}
953//}}}
954
955//{{{ CanonicalForm content ( const CanonicalForm & f, const Variable & x )
956//{{{ docu
957//
958// content() - return content(f) with respect to x.
959//
960// x should be a polynomial variable.
961//
962//}}}
963CanonicalForm
964content ( const CanonicalForm & f, const Variable & x )
965{
966    ASSERT( x.level() > 0, "cannot calculate content with respect to algebraic variable" );
967    Variable y = f.mvar();
968
969    if ( y == x )
970        return cf_content( f, 0 );
971    else  if ( y < x )
972        return f;
973    else
974        return swapvar( content( swapvar( f, y, x ), y ), y, x );
975}
976//}}}
977
978//{{{ CanonicalForm vcontent ( const CanonicalForm & f, const Variable & x )
979//{{{ docu
980//
981// vcontent() - return content of f with repect to variables >= x.
982//
983// The content is recursively calculated over all coefficients in
984// f having level less than x.  x should be a polynomial
985// variable.
986//
987//}}}
988CanonicalForm
989vcontent ( const CanonicalForm & f, const Variable & x )
990{
991    ASSERT( x.level() > 0, "cannot calculate vcontent with respect to algebraic variable" );
992
993    if ( f.mvar() <= x )
994        return content( f, x );
995    else {
996        CFIterator i;
997        CanonicalForm d = 0;
998        for ( i = f; i.hasTerms() && ! d.isOne(); i++ )
999            d = gcd( d, vcontent( i.coeff(), x ) );
1000        return d;
1001    }
1002}
1003//}}}
1004
1005//{{{ CanonicalForm pp ( const CanonicalForm & f )
1006//{{{ docu
1007//
1008// pp() - return primitive part of f.
1009//
1010// Returns zero if f equals zero, otherwise f / content(f).
1011//
1012//}}}
1013CanonicalForm
1014pp ( const CanonicalForm & f )
1015{
1016    if ( f.isZero() )
1017        return f;
1018    else
1019        return f / content( f );
1020}
1021//}}}
1022
1023CanonicalForm
1024gcd ( const CanonicalForm & f, const CanonicalForm & g )
1025{
1026    bool b = f.isZero();
1027    if ( b || g.isZero() )
1028    {
1029        if ( b )
1030            return abs( g );
1031        else
1032            return abs( f );
1033    }
1034    if ( f.inPolyDomain() || g.inPolyDomain() )
1035    {
1036        if ( f.mvar() != g.mvar() )
1037        {
1038            if ( f.mvar() > g.mvar() )
1039                return cf_content( f, g );
1040            else
1041                return cf_content( g, f );
1042        }
1043        if (isOn(SW_USE_QGCD))
1044        {
1045          Variable m;
1046          if (
1047          (getCharacteristic() == 0) &&
1048          (hasFirstAlgVar(f,m) || hasFirstAlgVar(g,m))
1049          )
1050          {
1051            bool on_rational = isOn(SW_RATIONAL);
1052            CanonicalForm r=QGCD(f,g);
1053            On(SW_RATIONAL);
1054            CanonicalForm cdF = bCommonDen( r );
1055            if (!on_rational) Off(SW_RATIONAL);
1056            return cdF*r;
1057          }
1058        }
1059
1060        if ( f.inExtension() && getReduce( f.mvar() ) )
1061            return CanonicalForm(1);
1062        else
1063        {
1064            if ( fdivides( f, g ) )
1065                return abs( f );
1066            else  if ( fdivides( g, f ) )
1067                return abs( g );
1068            if ( !( getCharacteristic() == 0 && isOn( SW_RATIONAL ) ) )
1069            {
1070                CanonicalForm d;
1071                d = gcd_poly( f, g );
1072                return abs( d );
1073            }
1074            else
1075            {
1076                //printf ("here\n");
1077                CanonicalForm cdF = bCommonDen( f );
1078                CanonicalForm cdG = bCommonDen( g );
1079                Off( SW_RATIONAL );
1080                CanonicalForm l = lcm( cdF, cdG );
1081                On( SW_RATIONAL );
1082                CanonicalForm F = f * l, G = g * l;
1083                Off( SW_RATIONAL );
1084                l = gcd_poly( F, G );
1085                On( SW_RATIONAL );
1086                return abs( l );
1087            }
1088        }
1089    }
1090    if ( f.inBaseDomain() && g.inBaseDomain() )
1091        return bgcd( f, g );
1092    else
1093        return 1;
1094}
1095
1096//{{{ CanonicalForm lcm ( const CanonicalForm & f, const CanonicalForm & g )
1097//{{{ docu
1098//
1099// lcm() - return least common multiple of f and g.
1100//
1101// The lcm is calculated using the formula lcm(f, g) = f * g / gcd(f, g).
1102//
1103// Returns zero if one of f or g equals zero.
1104//
1105//}}}
1106CanonicalForm
1107lcm ( const CanonicalForm & f, const CanonicalForm & g )
1108{
1109    if ( f.isZero() || g.isZero() )
1110        return 0;
1111    else
1112        return ( f / gcd( f, g ) ) * g;
1113}
1114//}}}
1115
1116#ifdef HAVE_NTL
1117#ifndef HAVE_FLINT
1118static CanonicalForm
1119gcd_univar_ntl0( const CanonicalForm & F, const CanonicalForm & G )
1120{
1121    ZZX F1=convertFacCF2NTLZZX(F);
1122    ZZX G1=convertFacCF2NTLZZX(G);
1123    ZZX R=GCD(F1,G1);
1124    return convertNTLZZX2CF(R,F.mvar());
1125}
1126
1127static CanonicalForm
1128gcd_univar_ntlp( const CanonicalForm & F, const CanonicalForm & G )
1129{
1130  if (fac_NTL_char!=getCharacteristic())
1131  {
1132    fac_NTL_char=getCharacteristic();
1133    zz_p::init(getCharacteristic());
1134  }
1135  zz_pX F1=convertFacCF2NTLzzpX(F);
1136  zz_pX G1=convertFacCF2NTLzzpX(G);
1137  zz_pX R=GCD(F1,G1);
1138  return  convertNTLzzpX2CF(R,F.mvar());
1139}
1140#endif
1141#endif
1142
1143#ifdef HAVE_FLINT
1144static CanonicalForm
1145gcd_univar_flintp (const CanonicalForm& F, const CanonicalForm& G)
1146{
1147  nmod_poly_t F1, G1;
1148  convertFacCF2nmod_poly_t (F1, F);
1149  convertFacCF2nmod_poly_t (G1, G);
1150  nmod_poly_gcd (F1, F1, G1);
1151  CanonicalForm result= convertnmod_poly_t2FacCF (F1, F.mvar());
1152  nmod_poly_clear (F1);
1153  nmod_poly_clear (G1);
1154  return result;
1155}
1156
1157static CanonicalForm
1158gcd_univar_flint0( const CanonicalForm & F, const CanonicalForm & G )
1159{
1160  fmpz_poly_t F1, G1;
1161  convertFacCF2Fmpz_poly_t(F1, F);
1162  convertFacCF2Fmpz_poly_t(G1, G);
1163  fmpz_poly_gcd (F1, F1, G1);
1164  CanonicalForm result= convertFmpz_poly_t2FacCF (F1, F.mvar());
1165  fmpz_poly_clear (F1);
1166  fmpz_poly_clear (G1);
1167  return result;
1168}
1169#endif
1170
1171
1172/*
1173*  compute positions p1 and pe of optimal variables:
1174*    pe is used in "ezgcd" and
1175*    p1 in "gcd_poly1"
1176*/
1177/*static
1178void optvalues ( const int * df, const int * dg, const int n, int & p1, int &pe )
1179{
1180    int i, o1, oe;
1181    if ( df[n] > dg[n] )
1182    {
1183        o1 = df[n]; oe = dg[n];
1184    }
1185    else
1186    {
1187        o1 = dg[n]; oe = df[n];
1188    }
1189    i = n-1;
1190    while ( i > 0 )
1191    {
1192        if ( df[i] != 0 )
1193        {
1194            if ( df[i] > dg[i] )
1195            {
1196                if ( o1 > df[i]) { o1 = df[i]; p1 = i; }
1197                if ( oe <= dg[i]) { oe = dg[i]; pe = i; }
1198            }
1199            else
1200            {
1201                if ( o1 > dg[i]) { o1 = dg[i]; p1 = i; }
1202                if ( oe <= df[i]) { oe = df[i]; pe = i; }
1203            }
1204        }
1205        i--;
1206    }
1207}*/
1208
1209/*
1210*  make some changes of variables, see optvalues
1211*/
1212/*static void
1213cf_prepgcd( const CanonicalForm & f, const CanonicalForm & g, int & cc, int & p1, int &pe )
1214{
1215    int i, k, n;
1216    n = f.level();
1217    cc = 0;
1218    p1 = pe = n;
1219    if ( n == 1 )
1220        return;
1221    int * degsf = new int[n+1];
1222    int * degsg = new int[n+1];
1223    for ( i = n; i > 0; i-- )
1224    {
1225        degsf[i] = degsg[i] = 0;
1226    }
1227    degsf = degrees( f, degsf );
1228    degsg = degrees( g, degsg );
1229
1230    k = 0;
1231    for ( i = n-1; i > 0; i-- )
1232    {
1233        if ( degsf[i] == 0 )
1234        {
1235            if ( degsg[i] != 0 )
1236            {
1237                cc = -i;
1238                break;
1239            }
1240        }
1241        else
1242        {
1243            if ( degsg[i] == 0 )
1244            {
1245                cc = i;
1246                break;
1247            }
1248            else k++;
1249        }
1250    }
1251
1252    if ( ( cc == 0 ) && ( k != 0 ) )
1253        optvalues( degsf, degsg, n, p1, pe );
1254    if ( ( pe != 1 ) && ( degsf[1] != 0 ) )
1255        pe = -pe;
1256
1257    delete [] degsf;
1258    delete [] degsg;
1259}*/
1260
1261TIMING_DEFINE_PRINT(chinrem_termination)
1262TIMING_DEFINE_PRINT(chinrem_recursion)
1263
1264CanonicalForm chinrem_gcd ( const CanonicalForm & FF, const CanonicalForm & GG )
1265{
1266  CanonicalForm f, g, cl, q(0), Dp, newD, D, newq, newqh;
1267  int p, i, dp_deg, d_deg=-1;
1268
1269  CanonicalForm cd ( bCommonDen( FF ));
1270  f=cd*FF;
1271  Variable x= Variable (1);
1272  CanonicalForm cf, cg;
1273  cf= icontent (f);
1274  f /= cf;
1275  //cd = bCommonDen( f ); f *=cd;
1276  //f /=vcontent(f,Variable(1));
1277
1278  cd = bCommonDen( GG );
1279  g=cd*GG;
1280  cg= icontent (g);
1281  g /= cg;
1282  //cd = bCommonDen( g ); g *=cd;
1283  //g /=vcontent(g,Variable(1));
1284
1285  CanonicalForm Dn, test= 0;
1286  CanonicalForm lcf, lcg;
1287  lcf= f.lc();
1288  lcg= g.lc();
1289  cl =  gcd (f.lc(),g.lc());
1290  CanonicalForm gcdcfcg= gcd (cf, cg);
1291  CanonicalForm fp, gp;
1292  CanonicalForm b= 1;
1293  int minCommonDeg= 0;
1294  for (i= tmax (f.level(), g.level()); i > 0; i--)
1295  {
1296    if (degree (f, i) <= 0 || degree (g, i) <= 0)
1297      continue;
1298    else
1299    {
1300      minCommonDeg= tmin (degree (g, i), degree (f, i));
1301      break;
1302    }
1303  }
1304  if (i == 0)
1305    return gcdcfcg;
1306  for (; i > 0; i--)
1307  {
1308    if (degree (f, i) <= 0 || degree (g, i) <= 0)
1309      continue;
1310    else
1311      minCommonDeg= tmin (minCommonDeg, tmin (degree (g, i), degree (f, i)));
1312  }
1313  b= 2*tmin (maxNorm (f), maxNorm (g))*abs (cl)*
1314     power (CanonicalForm (2), minCommonDeg);
1315  bool equal= false;
1316  i = cf_getNumBigPrimes() - 1;
1317
1318  CanonicalForm cof, cog, cofp, cogp, newCof, newCog, cofn, cogn, cDn;
1319  int maxNumVars= tmax (getNumVars (f), getNumVars (g));
1320  //Off (SW_RATIONAL);
1321  while ( true )
1322  {
1323    p = cf_getBigPrime( i );
1324    i--;
1325    while ( i >= 0 && mod( cl*(lc(f)/cl)*(lc(g)/cl), p ) == 0 )
1326    {
1327      p = cf_getBigPrime( i );
1328      i--;
1329    }
1330    //printf("try p=%d\n",p);
1331    setCharacteristic( p );
1332    fp= mapinto (f);
1333    gp= mapinto (g);
1334    TIMING_START (chinrem_recursion)
1335#ifdef HAVE_NTL
1336    if (size (fp)/maxNumVars > 500 && size (gp)/maxNumVars > 500)
1337      Dp = GCD_small_p (fp, gp, cofp, cogp);
1338    else
1339    {
1340      Dp= gcd_poly (fp, gp);
1341      cofp= fp/Dp;
1342      cogp= gp/Dp;
1343    }
1344#else
1345    Dp= gcd_poly (fp, gp);
1346    cofp= fp/Dp;
1347    cogp= gp/Dp;
1348#endif
1349    TIMING_END_AND_PRINT (chinrem_recursion,
1350                          "time for gcd mod p in modular gcd: ");
1351    Dp /=Dp.lc();
1352    Dp *= mapinto (cl);
1353    cofp /= lc (cofp);
1354    cofp *= mapinto (lcf);
1355    cogp /= lc (cogp);
1356    cogp *= mapinto (lcg);
1357    setCharacteristic( 0 );
1358    dp_deg=totaldegree(Dp);
1359    if ( dp_deg == 0 )
1360    {
1361      //printf(" -> 1\n");
1362      return CanonicalForm(gcdcfcg);
1363    }
1364    if ( q.isZero() )
1365    {
1366      D = mapinto( Dp );
1367      cof= mapinto (cofp);
1368      cog= mapinto (cogp);
1369      d_deg=dp_deg;
1370      q = p;
1371      Dn= balance_p (D, p);
1372      cofn= balance_p (cof, p);
1373      cogn= balance_p (cog, p);
1374    }
1375    else
1376    {
1377      if ( dp_deg == d_deg )
1378      {
1379        chineseRemainder( D, q, mapinto( Dp ), p, newD, newq );
1380        chineseRemainder( cof, q, mapinto (cofp), p, newCof, newq);
1381        chineseRemainder( cog, q, mapinto (cogp), p, newCog, newq);
1382        cof= newCof;
1383        cog= newCog;
1384        newqh= newq/2;
1385        Dn= balance_p (newD, newq, newqh);
1386        cofn= balance_p (newCof, newq, newqh);
1387        cogn= balance_p (newCog, newq, newqh);
1388        if (test != Dn) //balance_p (newD, newq))
1389          test= balance_p (newD, newq);
1390        else
1391          equal= true;
1392        q = newq;
1393        D = newD;
1394      }
1395      else if ( dp_deg < d_deg )
1396      {
1397        //printf(" were all bad, try more\n");
1398        // all previous p's are bad primes
1399        q = p;
1400        D = mapinto( Dp );
1401        cof= mapinto (cof);
1402        cog= mapinto (cog);
1403        d_deg=dp_deg;
1404        test= 0;
1405        equal= false;
1406        Dn= balance_p (D, p);
1407        cofn= balance_p (cof, p);
1408        cogn= balance_p (cog, p);
1409      }
1410      else
1411      {
1412        //printf(" was bad, try more\n");
1413      }
1414      //else dp_deg > d_deg: bad prime
1415    }
1416    if ( i >= 0 )
1417    {
1418      cDn= icontent (Dn);
1419      Dn /= cDn;
1420      cofn /= cl/cDn;
1421      //cofn /= icontent (cofn);
1422      cogn /= cl/cDn;
1423      //cogn /= icontent (cogn);
1424      TIMING_START (chinrem_termination);
1425      if ((terminationTest (f,g, cofn, cogn, Dn)) ||
1426          ((equal || q > b) && fdivides (Dn, f) && fdivides (Dn, g)))
1427      {
1428        TIMING_END_AND_PRINT (chinrem_termination,
1429                            "time for successful termination in modular gcd: ");
1430        //printf(" -> success\n");
1431        return Dn*gcdcfcg;
1432      }
1433      TIMING_END_AND_PRINT (chinrem_termination,
1434                          "time for unsuccessful termination in modular gcd: ");
1435      equal= false;
1436      //else: try more primes
1437    }
1438    else
1439    { // try other method
1440      //printf("try other gcd\n");
1441      Off(SW_USE_CHINREM_GCD);
1442      D=gcd_poly( f, g );
1443      On(SW_USE_CHINREM_GCD);
1444      return D*gcdcfcg;
1445    }
1446  }
1447}
1448
1449
Note: See TracBrowser for help on using the repository browser.