source: git/factory/algext.cc @ a64b0e

spielwiese
Last change on this file since a64b0e was a64b0e, checked in by Martin Lee <martinlee84@…>, 11 years ago
chg: deleted unused tryDivide
  • Property mode set to 100644
File size: 30.0 KB
Line 
1#include "config.h"
2
3#ifndef NOSTREAMIO
4#ifdef HAVE_CSTDIO
5#include <cstdio>
6#else
7#include <stdio.h>
8#endif
9#ifdef HAVE_IOSTREAM_H
10#include <iostream.h>
11#elif defined(HAVE_IOSTREAM)
12#include <iostream>
13#endif
14#endif
15
16#include "cf_assert.h"
17#include "timing.h"
18
19#include "templates/ftmpl_functions.h"
20#include "cf_defs.h"
21#include "canonicalform.h"
22#include "cf_iter.h"
23#include "cf_primes.h"
24#include "cf_algorithm.h"
25#include "algext.h"
26#include "cf_map.h"
27#include "cf_generator.h"
28
29#ifdef HAVE_NTL
30#include "NTLconvert.h"
31#endif
32
33#ifdef HAVE_FLINT
34#include "FLINTconvert.h"
35#endif
36
37TIMING_DEFINE_PRINT(alg_content_p)
38TIMING_DEFINE_PRINT(alg_content)
39TIMING_DEFINE_PRINT(alg_compress)
40TIMING_DEFINE_PRINT(alg_termination)
41TIMING_DEFINE_PRINT(alg_termination_p)
42TIMING_DEFINE_PRINT(alg_reconstruction)
43TIMING_DEFINE_PRINT(alg_newton_p)
44TIMING_DEFINE_PRINT(alg_recursion_p)
45TIMING_DEFINE_PRINT(alg_gcd_p)
46TIMING_DEFINE_PRINT(alg_euclid_p)
47
48/// compressing two polynomials F and G, M is used for compressing,
49/// N to reverse the compression
50static
51int myCompress (const CanonicalForm& F, const CanonicalForm& G, CFMap & M,
52                CFMap & N, bool topLevel)
53{
54  int n= tmax (F.level(), G.level());
55  int * degsf= new int [n + 1];
56  int * degsg= new int [n + 1];
57
58  for (int i = 0; i <= n; i++)
59    degsf[i]= degsg[i]= 0;
60
61  degsf= degrees (F, degsf);
62  degsg= degrees (G, degsg);
63
64  int both_non_zero= 0;
65  int f_zero= 0;
66  int g_zero= 0;
67  int both_zero= 0;
68
69  if (topLevel)
70  {
71    for (int i= 1; i <= n; i++)
72    {
73      if (degsf[i] != 0 && degsg[i] != 0)
74      {
75        both_non_zero++;
76        continue;
77      }
78      if (degsf[i] == 0 && degsg[i] != 0 && i <= G.level())
79      {
80        f_zero++;
81        continue;
82      }
83      if (degsg[i] == 0 && degsf[i] && i <= F.level())
84      {
85        g_zero++;
86        continue;
87      }
88    }
89
90    if (both_non_zero == 0)
91    {
92      delete [] degsf;
93      delete [] degsg;
94      return 0;
95    }
96
97    // map Variables which do not occur in both polynomials to higher levels
98    int k= 1;
99    int l= 1;
100    for (int i= 1; i <= n; i++)
101    {
102      if (degsf[i] != 0 && degsg[i] == 0 && i <= F.level())
103      {
104        if (k + both_non_zero != i)
105        {
106          M.newpair (Variable (i), Variable (k + both_non_zero));
107          N.newpair (Variable (k + both_non_zero), Variable (i));
108        }
109        k++;
110      }
111      if (degsf[i] == 0 && degsg[i] != 0 && i <= G.level())
112      {
113        if (l + g_zero + both_non_zero != i)
114        {
115          M.newpair (Variable (i), Variable (l + g_zero + both_non_zero));
116          N.newpair (Variable (l + g_zero + both_non_zero), Variable (i));
117        }
118        l++;
119      }
120    }
121
122    // sort Variables x_{i} in increasing order of
123    // min(deg_{x_{i}}(f),deg_{x_{i}}(g))
124    int m= tmax (F.level(), G.level());
125    int min_max_deg;
126    k= both_non_zero;
127    l= 0;
128    int i= 1;
129    while (k > 0)
130    {
131      if (degsf [i] != 0 && degsg [i] != 0)
132        min_max_deg= tmax (degsf[i], degsg[i]);
133      else
134        min_max_deg= 0;
135      while (min_max_deg == 0)
136      {
137        i++;
138        min_max_deg= tmax (degsf[i], degsg[i]);
139        if (degsf [i] != 0 && degsg [i] != 0)
140          min_max_deg= tmax (degsf[i], degsg[i]);
141        else
142          min_max_deg= 0;
143      }
144      for (int j= i + 1; j <=  m; j++)
145      {
146        if (tmax (degsf[j],degsg[j]) <= min_max_deg && degsf[j] != 0 && degsg [j] != 0)
147        {
148          min_max_deg= tmax (degsf[j], degsg[j]);
149          l= j;
150        }
151      }
152      if (l != 0)
153      {
154        if (l != k)
155        {
156          M.newpair (Variable (l), Variable(k));
157          N.newpair (Variable (k), Variable(l));
158          degsf[l]= 0;
159          degsg[l]= 0;
160          l= 0;
161        }
162        else
163        {
164          degsf[l]= 0;
165          degsg[l]= 0;
166          l= 0;
167        }
168      }
169      else if (l == 0)
170      {
171        if (i != k)
172        {
173          M.newpair (Variable (i), Variable (k));
174          N.newpair (Variable (k), Variable (i));
175          degsf[i]= 0;
176          degsg[i]= 0;
177        }
178        else
179        {
180          degsf[i]= 0;
181          degsg[i]= 0;
182        }
183        i++;
184      }
185      k--;
186    }
187  }
188  else
189  {
190    //arrange Variables such that no gaps occur
191    for (int i= 1; i <= n; i++)
192    {
193      if (degsf[i] == 0 && degsg[i] == 0)
194      {
195        both_zero++;
196        continue;
197      }
198      else
199      {
200        if (both_zero != 0)
201        {
202          M.newpair (Variable (i), Variable (i - both_zero));
203          N.newpair (Variable (i - both_zero), Variable (i));
204        }
205      }
206    }
207  }
208
209  delete [] degsf;
210  delete [] degsg;
211
212  return 1;
213}
214
215void tryInvert( const CanonicalForm & F, const CanonicalForm & M, CanonicalForm & inv, bool & fail )
216{ // F, M are required to be "univariate" polynomials in an algebraic variable
217  // we try to invert F modulo M
218  if(F.inBaseDomain())
219  {
220    if(F.isZero())
221    {
222      fail = true;
223      return;
224    }
225    inv = 1/F;
226    return;
227  }
228  CanonicalForm b;
229  Variable a = M.mvar();
230  Variable x = Variable(1);
231  if(!extgcd( replacevar( F, a, x ), replacevar( M, a, x ), inv, b ).isOne())
232    fail = true;
233  else
234    inv = replacevar( inv, x, a ); // change back to alg var
235}
236
237void tryDivrem (const CanonicalForm& F, const CanonicalForm& G, CanonicalForm& Q,
238                CanonicalForm& R, CanonicalForm& inv, const CanonicalForm& mipo,
239                bool& fail)
240{
241  if (F.inCoeffDomain())
242  {
243    Q= 0;
244    R= F;
245    return;
246  }
247
248  CanonicalForm A, B;
249  Variable x= F.mvar();
250  A= F;
251  B= G;
252  int degA= degree (A, x);
253  int degB= degree (B, x);
254
255  if (degA < degB)
256  {
257    R= A;
258    Q= 0;
259    return;
260  }
261
262  tryInvert (Lc (B), mipo, inv, fail);
263  if (fail)
264    return;
265
266  R= A;
267  Q= 0;
268  CanonicalForm Qi;
269  for (int i= degA -degB; i >= 0; i--)
270  {
271    if (degree (R, x) == i + degB)
272    {
273      Qi= Lc (R)*inv*power (x, i);
274      Qi= reduce (Qi, mipo);
275      R -= Qi*B;
276      R= reduce (R, mipo);
277      Q += Qi;
278    }
279  }
280}
281
282void tryEuclid( const CanonicalForm & A, const CanonicalForm & B, const CanonicalForm & M, CanonicalForm & result, bool & fail )
283{
284  CanonicalForm P;
285  if(A.inCoeffDomain())
286  {
287    tryInvert( A, M, P, fail );
288    if(fail)
289      return;
290    result = 1;
291    return;
292  }
293  if(B.inCoeffDomain())
294  {
295    tryInvert( B, M, P, fail );
296    if(fail)
297      return;
298    result = 1;
299    return;
300  }
301  // here: both not inCoeffDomain
302  if( A.degree() > B.degree() )
303  {
304    P = A; result = B;
305  }
306  else
307  {
308    P = B; result = A;
309  }
310  CanonicalForm inv;
311  if( result.isZero() )
312  {
313    tryInvert( Lc(P), M, inv, fail );
314    if(fail)
315      return;
316    result = inv*P; // monify result (not reduced, yet)
317    result= reduce (result, M);
318    return;
319  }
320  Variable x = P.mvar();
321  CanonicalForm rem, Q;
322  // here: degree(P) >= degree(result)
323  while(true)
324  {
325    tryDivrem (P, result, Q, rem, inv, M, fail);
326    if (fail)
327      return;
328    if( rem.isZero() )
329    {
330      result *= inv;
331      result= reduce (result, M);
332      return;
333    }
334    if(result.degree(x) >= rem.degree(x))
335    {
336      P = result;
337      result = rem;
338    }
339    else
340      P = rem;
341  }
342}
343
344bool hasFirstAlgVar( const CanonicalForm & f, Variable & a )
345{
346  if( f.inBaseDomain() ) // f has NO alg. variable
347    return false;
348  if( f.level()<0 ) // f has only alg. vars, so take the first one
349  {
350    a = f.mvar();
351    return true;
352  }
353  for(CFIterator i=f; i.hasTerms(); i++)
354    if( hasFirstAlgVar( i.coeff(), a ))
355      return true; // 'a' is already set
356  return false;
357}
358
359CanonicalForm QGCD( const CanonicalForm & F, const CanonicalForm & G );
360int * leadDeg(const CanonicalForm & f, int *degs);
361bool isLess(int *a, int *b, int lower, int upper);
362bool isEqual(int *a, int *b, int lower, int upper);
363CanonicalForm firstLC(const CanonicalForm & f);
364static CanonicalForm trycontent ( const CanonicalForm & f, const Variable & x, const CanonicalForm & M, bool & fail );
365static CanonicalForm tryvcontent ( const CanonicalForm & f, const Variable & x, const CanonicalForm & M, bool & fail );
366static CanonicalForm trycf_content ( const CanonicalForm & f, const CanonicalForm & g, const CanonicalForm & M, bool & fail );
367
368static inline CanonicalForm
369tryNewtonInterp (const CanonicalForm alpha, const CanonicalForm u,
370              const CanonicalForm newtonPoly, const CanonicalForm oldInterPoly,
371              const Variable & x, const CanonicalForm& M, bool& fail)
372{
373  CanonicalForm interPoly;
374
375  CanonicalForm inv;
376  tryInvert (newtonPoly (alpha, x), M, inv, fail);
377  if (fail)
378    return 0;
379
380  interPoly= oldInterPoly+reduce ((u - oldInterPoly (alpha, x))*inv*newtonPoly, M);
381  return interPoly;
382}
383
384void tryBrownGCD( const CanonicalForm & F, const CanonicalForm & G, const CanonicalForm & M, CanonicalForm & result, bool & fail, bool topLevel )
385{ // assume F,G are multivariate polys over Z/p(a) for big prime p, M "univariate" polynomial in an algebraic variable
386  // M is assumed to be monic
387  if(F.isZero())
388  {
389    if(G.isZero())
390    {
391      result = G; // G is zero
392      return;
393    }
394    if(G.inCoeffDomain())
395    {
396      tryInvert(G,M,result,fail);
397      if(fail)
398        return;
399      result = 1;
400      return;
401    }
402    // try to make G monic modulo M
403    CanonicalForm inv;
404    tryInvert(Lc(G),M,inv,fail);
405    if(fail)
406      return;
407    result = inv*G;
408    result= reduce (result, M);
409    return;
410  }
411  if(G.isZero()) // F is non-zero
412  {
413    if(F.inCoeffDomain())
414    {
415      tryInvert(F,M,result,fail);
416      if(fail)
417        return;
418      result = 1;
419      return;
420    }
421    // try to make F monic modulo M
422    CanonicalForm inv;
423    tryInvert(Lc(F),M,inv,fail);
424    if(fail)
425      return;
426    result = inv*F;
427    result= reduce (result, M);
428    return;
429  }
430  // here: F,G both nonzero
431  if(F.inCoeffDomain())
432  {
433    tryInvert(F,M,result,fail);
434    if(fail)
435      return;
436    result = 1;
437    return;
438  }
439  if(G.inCoeffDomain())
440  {
441    tryInvert(G,M,result,fail);
442    if(fail)
443      return;
444    result = 1;
445    return;
446  }
447  TIMING_START (alg_compress)
448  CFMap MM,NN;
449  int lev= myCompress (F, G, MM, NN, topLevel);
450  if (lev == 0)
451  {
452    result= 1;
453    return;
454  }
455  CanonicalForm f=MM(F);
456  CanonicalForm g=MM(G);
457  TIMING_END_AND_PRINT (alg_compress, "time to compress in alg gcd: ")
458  // here: f,g are compressed
459  // compute largest variable in f or g (least one is Variable(1))
460  int mv = f.level();
461  if(g.level() > mv)
462    mv = g.level();
463  // here: mv is level of the largest variable in f, g
464  if(mv == 1) // f,g univariate
465  {
466    TIMING_START (alg_euclid_p)
467    tryEuclid(f,g,M,result,fail);
468    TIMING_END_AND_PRINT (alg_euclid_p, "time for euclidean alg mod p: ")
469    if(fail)
470      return;
471    result= NN (reduce (result, M)); // do not forget to map back
472    return;
473  }
474  TIMING_START (alg_content_p)
475  // here: mv > 1
476  CanonicalForm cf = tryvcontent(f, Variable(2), M, fail); // cf is univariate poly in var(1)
477  if(fail)
478    return;
479  CanonicalForm cg = tryvcontent(g, Variable(2), M, fail);
480  if(fail)
481    return;
482  CanonicalForm c;
483  tryEuclid(cf,cg,M,c,fail);
484  if(fail)
485    return;
486  // f /= cf
487  f.tryDiv (cf, M, fail);
488  if(fail)
489    return;
490  // g /= cg
491  g.tryDiv (cg, M, fail);
492  if(fail)
493    return;
494  TIMING_END_AND_PRINT (alg_content_p, "time for content in alg gcd mod p: ")
495  if(f.inCoeffDomain())
496  {
497    tryInvert(f,M,result,fail);
498    if(fail)
499      return;
500    result = NN(c);
501    return;
502  }
503  if(g.inCoeffDomain())
504  {
505    tryInvert(g,M,result,fail);
506    if(fail)
507      return;
508    result = NN(c);
509    return;
510  }
511  int *L = new int[mv+1]; // L is addressed by i from 2 to mv
512  int *N = new int[mv+1];
513  for(int i=2; i<=mv; i++)
514    L[i] = N[i] = 0;
515  L = leadDeg(f, L);
516  N = leadDeg(g, N);
517  CanonicalForm gamma;
518  TIMING_START (alg_euclid_p)
519  tryEuclid( firstLC(f), firstLC(g), M, gamma, fail );
520  TIMING_END_AND_PRINT (alg_euclid_p, "time for gcd of lcs in alg mod p: ")
521  if(fail)
522    return;
523  for(int i=2; i<=mv; i++) // entries at i=0,1 not visited
524    if(N[i] < L[i])
525      L[i] = N[i];
526  // L is now upper bound for degrees of gcd
527  int *dg_im = new int[mv+1]; // for the degree vector of the image we don't need any entry at i=1
528  for(int i=2; i<=mv; i++)
529    dg_im[i] = 0; // initialize
530  CanonicalForm gamma_image, m=1;
531  CanonicalForm gm=0;
532  CanonicalForm g_image, alpha, gnew;
533  FFGenerator gen = FFGenerator();
534  Variable x= Variable (1);
535  bool divides= true;
536  for(FFGenerator gen = FFGenerator(); gen.hasItems(); gen.next())
537  {
538    alpha = gen.item();
539    gamma_image = reduce(gamma(alpha, x),M); // plug in alpha for var(1)
540    if(gamma_image.isZero()) // skip lc-bad points var(1)-alpha
541      continue;
542    TIMING_START (alg_recursion_p)
543    tryBrownGCD( f(alpha, x), g(alpha, x), M, g_image, fail, false ); // recursive call with one var less
544    TIMING_END_AND_PRINT (alg_recursion_p,
545                         "time for recursive calls in alg gcd mod p: ")
546    if(fail)
547      return;
548    g_image = reduce(g_image, M);
549    if(g_image.inCoeffDomain()) // early termination
550    {
551      tryInvert(g_image,M,result,fail);
552      if(fail)
553        return;
554      result = NN(c);
555      return;
556    }
557    for(int i=2; i<=mv; i++)
558      dg_im[i] = 0; // reset (this is necessary, because some entries may not be updated by call to leadDeg)
559    dg_im = leadDeg(g_image, dg_im); // dg_im cannot be NIL-pointer
560    if(isEqual(dg_im, L, 2, mv))
561    {
562      CanonicalForm inv;
563      tryInvert (firstLC (g_image), M, inv, fail);
564      if (fail)
565        return;
566      g_image *= inv;
567      g_image *= gamma_image; // multiply by multiple of image lc(gcd)
568      g_image= reduce (g_image, M);
569      TIMING_START (alg_newton_p)
570      gnew= tryNewtonInterp (alpha, g_image, m, gm, x, M, fail);
571      TIMING_END_AND_PRINT (alg_newton_p,
572                            "time for Newton interpolation in alg gcd mod p: ")
573      // gnew = gm mod m
574      // gnew = g_image mod var(1)-alpha
575      // mnew = m * (var(1)-alpha)
576      if(fail)
577        return;
578      m *= (x - alpha);
579      if((firstLC(gnew) == gamma) || (gnew == gm)) // gnew did not change
580      {
581        TIMING_START (alg_termination_p)
582        cf = tryvcontent(gnew, Variable(2), M, fail);
583        if(fail)
584          return;
585        divides = true;
586        g_image= gnew;
587        g_image.tryDiv (cf, M, fail);
588        if(fail)
589          return;
590        divides= tryFdivides (g_image,f, M, fail); // trial division (f)
591        if(fail)
592          return;
593        if(divides)
594        {
595          bool divides2= tryFdivides (g_image,g, M, fail); // trial division (g)
596          if(fail)
597            return;
598          if(divides2)
599          {
600            result = NN(reduce (c*g_image, M));
601            TIMING_END_AND_PRINT (alg_termination_p,
602                      "time for successful termination test in alg gcd mod p: ")
603            return;
604          }
605        }
606        TIMING_END_AND_PRINT (alg_termination_p,
607                    "time for unsuccessful termination test in alg gcd mod p: ")
608      }
609      gm = gnew;
610      continue;
611    }
612
613    if(isLess(L, dg_im, 2, mv)) // dg_im > L --> current point unlucky
614      continue;
615
616    // here: isLess(dg_im, L, 2, mv) --> all previous points were unlucky
617    m = CanonicalForm(1); // reset
618    gm = 0; // reset
619    for(int i=2; i<=mv; i++) // tighten bound
620      L[i] = dg_im[i];
621  }
622  // we are out of evaluation points
623  fail = true;
624}
625
626static CanonicalForm
627myicontent ( const CanonicalForm & f, const CanonicalForm & c )
628{
629#ifdef HAVE_NTL
630    if (f.isOne() || c.isOne())
631      return 1;
632    if ( f.inBaseDomain() && c.inBaseDomain())
633    {
634      if (c.isZero()) return abs(f);
635      return bgcd( f, c );
636    }
637    else if ( (f.inCoeffDomain() && c.inCoeffDomain()) ||
638              (f.inCoeffDomain() && c.inBaseDomain()) ||
639              (f.inBaseDomain() && c.inCoeffDomain()))
640    {
641      if (c.isZero()) return abs (f);
642#ifdef HAVE_FLINT
643      fmpz_poly_t FLINTf, FLINTc;
644      convertFacCF2Fmpz_poly_t (FLINTf, f);
645      convertFacCF2Fmpz_poly_t (FLINTc, c);
646      fmpz_poly_gcd (FLINTc, FLINTc, FLINTf);
647      CanonicalForm result;
648      if (f.inCoeffDomain())
649        result= convertFmpz_poly_t2FacCF (FLINTc, f.mvar());
650      else
651        result= convertFmpz_poly_t2FacCF (FLINTc, c.mvar());
652      fmpz_poly_clear (FLINTc);
653      fmpz_poly_clear (FLINTf);
654      return result;
655#else
656      ZZX NTLf= convertFacCF2NTLZZX (f);
657      ZZX NTLc= convertFacCF2NTLZZX (c);
658      NTLc= GCD (NTLc, NTLf);
659      if (f.inCoeffDomain())
660        return convertNTLZZX2CF(NTLc,f.mvar());
661      else
662        return convertNTLZZX2CF(NTLc,c.mvar());
663#endif
664    }
665    else
666    {
667        CanonicalForm g = c;
668        for ( CFIterator i = f; i.hasTerms() && ! g.isOne(); i++ )
669            g = myicontent( i.coeff(), g );
670        return g;
671    }
672#else
673    return 1;
674#endif
675}
676
677CanonicalForm
678myicontent ( const CanonicalForm & f )
679{
680#ifdef HAVE_NTL
681    return myicontent( f, 0 );
682#else
683    return 1;
684#endif
685}
686
687CanonicalForm QGCD( const CanonicalForm & F, const CanonicalForm & G )
688{ // f,g in Q(a)[x1,...,xn]
689  if(F.isZero())
690  {
691    if(G.isZero())
692      return G; // G is zero
693    if(G.inCoeffDomain())
694      return CanonicalForm(1);
695    CanonicalForm lcinv= 1/Lc (G);
696    return G*lcinv; // return monic G
697  }
698  if(G.isZero()) // F is non-zero
699  {
700    if(F.inCoeffDomain())
701      return CanonicalForm(1);
702    CanonicalForm lcinv= 1/Lc (F);
703    return F*lcinv; // return monic F
704  }
705  if(F.inCoeffDomain() || G.inCoeffDomain())
706    return CanonicalForm(1);
707  // here: both NOT inCoeffDomain
708  CanonicalForm f, g, tmp, M, q, D, Dp, cl, newq, mipo;
709  int p, i;
710  int *bound, *other; // degree vectors
711  bool fail;
712  bool off_rational=!isOn(SW_RATIONAL);
713  On( SW_RATIONAL ); // needed by bCommonDen
714  f = F * bCommonDen(F);
715  g = G * bCommonDen(G);
716  TIMING_START (alg_content)
717  CanonicalForm contf= myicontent (f);
718  CanonicalForm contg= myicontent (g);
719  f /= contf;
720  g /= contg;
721  CanonicalForm gcdcfcg= myicontent (contf, contg);
722  TIMING_END_AND_PRINT (alg_content, "time for content in alg gcd: ")
723  Variable a, b;
724  if(hasFirstAlgVar(f,a))
725  {
726    if(hasFirstAlgVar(g,b))
727    {
728      if(b.level() > a.level())
729        a = b;
730    }
731  }
732  else
733  {
734    if(!hasFirstAlgVar(g,a))// both not in extension
735    {
736      Off( SW_RATIONAL );
737      Off( SW_USE_QGCD );
738      tmp = gcdcfcg*gcd( f, g );
739      On( SW_USE_QGCD );
740      if (off_rational) Off(SW_RATIONAL);
741      return tmp;
742    }
743  }
744  // here: a is the biggest alg. var in f and g AND some of f,g is in extension
745  setReduce(a,false); // do not reduce expressions modulo mipo
746  tmp = getMipo(a);
747  M = tmp * bCommonDen(tmp);
748  // here: f, g in Z[a][x1,...,xn], M in Z[a] not necessarily monic
749  Off( SW_RATIONAL ); // needed by mod
750  // calculate upper bound for degree vector of gcd
751  int mv = f.level(); i = g.level();
752  if(i > mv)
753    mv = i;
754  // here: mv is level of the largest variable in f, g
755  bound = new int[mv+1]; // 'bound' could be indexed from 0 to mv, but we will only use from 1 to mv
756  other = new int[mv+1];
757  for(int i=1; i<=mv; i++) // initialize 'bound', 'other' with zeros
758    bound[i] = other[i] = 0;
759  bound = leadDeg(f,bound); // 'bound' is set the leading degree vector of f
760  other = leadDeg(g,other);
761  for(int i=1; i<=mv; i++) // entry at i=0 not visited
762    if(other[i] < bound[i])
763      bound[i] = other[i];
764  // now 'bound' is the smaller vector
765  cl = lc(M) * lc(f) * lc(g);
766  q = 1;
767  D = 0;
768  CanonicalForm test= 0;
769  bool equal= false;
770  for( i=cf_getNumBigPrimes()-1; i>-1; i-- )
771  {
772    p = cf_getBigPrime(i);
773    if( mod( cl, p ).isZero() ) // skip lc-bad primes
774      continue;
775    fail = false;
776    setCharacteristic(p);
777    mipo = mapinto(M);
778    mipo /= mipo.lc();
779    // here: mipo is monic
780    TIMING_START (alg_gcd_p)
781    tryBrownGCD( mapinto(f), mapinto(g), mipo, Dp, fail );
782    TIMING_END_AND_PRINT (alg_gcd_p, "time for alg gcd mod p: ")
783    if( fail ) // mipo splits in char p
784      continue;
785    if( Dp.inCoeffDomain() ) // early termination
786    {
787      tryInvert(Dp,mipo,tmp,fail); // check if zero divisor
788      if(fail)
789        continue;
790      setReduce(a,true);
791      if (off_rational) Off(SW_RATIONAL); else On(SW_RATIONAL);
792      setCharacteristic(0);
793      return gcdcfcg;
794    }
795    setCharacteristic(0);
796    // here: Dp NOT inCoeffDomain
797    for(int i=1; i<=mv; i++)
798      other[i] = 0; // reset (this is necessary, because some entries may not be updated by call to leadDeg)
799    other = leadDeg(Dp,other);
800
801    if(isEqual(bound, other, 1, mv)) // equal
802    {
803      chineseRemainder( D, q, mapinto(Dp), p, tmp, newq );
804      // tmp = Dp mod p
805      // tmp = D mod q
806      // newq = p*q
807      q = newq;
808      if( D != tmp )
809        D = tmp;
810      On( SW_RATIONAL );
811      TIMING_START (alg_reconstruction)
812      tmp = Farey( D, q ); // Farey
813      tmp *= bCommonDen (tmp);
814      TIMING_END_AND_PRINT (alg_reconstruction,
815                            "time for rational reconstruction in alg gcd: ")
816      setReduce(a,true); // reduce expressions modulo mipo
817      On( SW_RATIONAL ); // needed by fdivides
818      if (test != tmp)
819        test= tmp;
820      else
821        equal= true; // modular image did not add any new information
822      TIMING_START (alg_termination)
823      if(equal && fdivides( tmp, f ) && fdivides( tmp, g )) // trial division
824      {
825        Off( SW_RATIONAL );
826        setReduce(a,true);
827        if (off_rational) Off(SW_RATIONAL); else On(SW_RATIONAL);
828        TIMING_END_AND_PRINT (alg_termination,
829                            "time for successful termination test in alg gcd: ")
830        return tmp*gcdcfcg;
831      }
832      TIMING_END_AND_PRINT (alg_termination,
833                          "time for unsuccessful termination test in alg gcd: ")
834      Off( SW_RATIONAL );
835      setReduce(a,false); // do not reduce expressions modulo mipo
836      continue;
837    }
838    if( isLess(bound, other, 1, mv) ) // current prime unlucky
839      continue;
840    // here: isLess(other, bound, 1, mv) ) ==> all previous primes unlucky
841    q = p;
842    D = mapinto(Dp); // shortcut CRA // shortcut CRA
843    for(int i=1; i<=mv; i++) // tighten bound
844      bound[i] = other[i];
845  }
846  // hopefully, we never reach this point
847  setReduce(a,true);
848  Off( SW_USE_QGCD );
849  D = gcdcfcg*gcd( f, g );
850  On( SW_USE_QGCD );
851  if (off_rational) Off(SW_RATIONAL); else On(SW_RATIONAL);
852  return D;
853}
854
855
856int * leadDeg(const CanonicalForm & f, int *degs)
857{ // leading degree vector w.r.t. lex. monomial order x(i+1) > x(i)
858  // if f is in a coeff domain, the zero pointer is returned
859  // 'a' should point to an array of sufficient size level(f)+1
860  if(f.inCoeffDomain())
861    return 0;
862  CanonicalForm tmp = f;
863  do
864  {
865    degs[tmp.level()] = tmp.degree();
866    tmp = LC(tmp);
867  }
868  while(!tmp.inCoeffDomain());
869  return degs;
870}
871
872
873bool isLess(int *a, int *b, int lower, int upper)
874{ // compares the degree vectors a,b on the specified part. Note: x(i+1) > x(i)
875  for(int i=upper; i>=lower; i--)
876    if(a[i] == b[i])
877      continue;
878    else
879      return a[i] < b[i];
880  return true;
881}
882
883
884bool isEqual(int *a, int *b, int lower, int upper)
885{ // compares the degree vectors a,b on the specified part. Note: x(i+1) > x(i)
886  for(int i=lower; i<=upper; i++)
887    if(a[i] != b[i])
888      return false;
889  return true;
890}
891
892
893CanonicalForm firstLC(const CanonicalForm & f)
894{ // returns the leading coefficient (LC) of level <= 1
895  CanonicalForm ret = f;
896  while(ret.level() > 1)
897    ret = LC(ret);
898  return ret;
899}
900
901void tryExtgcd( const CanonicalForm & F, const CanonicalForm & G, const CanonicalForm & M, CanonicalForm & result, CanonicalForm & s, CanonicalForm & t, bool & fail )
902{ // F, G are univariate polynomials (i.e. they have exactly one polynomial variable)
903  // F and G must have the same level AND level > 0
904  // we try to calculate gcd(F,G) = s*F + t*G
905  // if a zero divisor is encontered, 'fail' is set to one
906  // M is assumed to be monic
907  CanonicalForm P;
908  if(F.inCoeffDomain())
909  {
910    tryInvert( F, M, P, fail );
911    if(fail)
912      return;
913    result = 1;
914    s = P; t = 0;
915    return;
916  }
917  if(G.inCoeffDomain())
918  {
919    tryInvert( G, M, P, fail );
920    if(fail)
921      return;
922    result = 1;
923    s = 0; t = P;
924    return;
925  }
926  // here: both not inCoeffDomain
927  CanonicalForm inv, rem, tmp, u, v, q, sum=0;
928  if( F.degree() > G.degree() )
929  {
930    P = F; result = G;  s=v=0; t=u=1;
931  }
932  else
933  {
934    P = G; result = F; s=v=1; t=u=0;
935  }
936  Variable x = P.mvar();
937  // here: degree(P) >= degree(result)
938  while(true)
939  {
940    tryDivrem (P, result, q, rem, inv, M, fail);
941    if(fail)
942      return;
943    if( rem.isZero() )
944    {
945      s*=inv;
946      s= reduce (s, M);
947      t*=inv;
948      t= reduce (t, M);
949      result *= inv; // monify result
950      result= reduce (result, M);
951      return;
952    }
953    sum += q;
954    if(result.degree(x) >= rem.degree(x))
955    {
956      P=result;
957      result=rem;
958      tmp=u-sum*s;
959      u=s;
960      s=tmp;
961      tmp=v-sum*t;
962      v=t;
963      t=tmp;
964      sum = 0; // reset
965    }
966    else
967      P = rem;
968  }
969}
970
971
972static CanonicalForm trycontent ( const CanonicalForm & f, const Variable & x, const CanonicalForm & M, bool & fail )
973{ // as 'content', but takes care of zero divisors
974  ASSERT( x.level() > 0, "cannot calculate content with respect to algebraic variable" );
975  Variable y = f.mvar();
976  if ( y == x )
977    return trycf_content( f, 0, M, fail );
978  if ( y < x )
979     return f;
980  return swapvar( trycontent( swapvar( f, y, x ), y, M, fail ), y, x );
981}
982
983
984static CanonicalForm tryvcontent ( const CanonicalForm & f, const Variable & x, const CanonicalForm & M, bool & fail )
985{ // as vcontent, but takes care of zero divisors
986  ASSERT( x.level() > 0, "cannot calculate vcontent with respect to algebraic variable" );
987  if ( f.mvar() <= x )
988    return trycontent( f, x, M, fail );
989  CFIterator i;
990  CanonicalForm d = 0, e, ret;
991  for ( i = f; i.hasTerms() && ! d.isOne() && ! fail; i++ )
992  {
993    e = tryvcontent( i.coeff(), x, M, fail );
994    if(fail)
995      break;
996    tryBrownGCD( d, e, M, ret, fail );
997    d = ret;
998  }
999  return d;
1000}
1001
1002
1003static CanonicalForm trycf_content ( const CanonicalForm & f, const CanonicalForm & g, const CanonicalForm & M, bool & fail )
1004{ // as cf_content, but takes care of zero divisors
1005  if ( f.inPolyDomain() || ( f.inExtension() && ! getReduce( f.mvar() ) ) )
1006  {
1007    CFIterator i = f;
1008    CanonicalForm tmp = g, result;
1009    while ( i.hasTerms() && ! tmp.isOne() && ! fail )
1010    {
1011      tryBrownGCD( i.coeff(), tmp, M, result, fail );
1012      tmp = result;
1013      i++;
1014    }
1015    return result;
1016  }
1017  return abs( f );
1018}
1019
1020void tryExtgcd( const CanonicalForm & F, const CanonicalForm & G, CanonicalForm & result, CanonicalForm & s, CanonicalForm & t, bool & fail )
1021{
1022  // F, G are univariate polynomials (i.e. they have exactly one polynomial variable)
1023  // F and G must have the same level AND level > 0
1024  // we try to calculate gcd(f,g) = s*F + t*G
1025  // if a zero divisor is encontered, 'fail' is set to one
1026  Variable a, b;
1027  if( !hasFirstAlgVar(F,a) && !hasFirstAlgVar(G,b) ) // note lazy evaluation
1028  {
1029    result = extgcd( F, G, s, t ); // no zero divisors possible
1030    return;
1031  }
1032  if( b.level() > a.level() )
1033    a = b;
1034  // here: a is the biggest alg. var in F and G
1035  CanonicalForm M = getMipo(a);
1036  CanonicalForm P;
1037  if( degree(F) > degree(G) )
1038  {
1039    P=F; result=G; s=0; t=1;
1040  }
1041  else
1042  {
1043    P=G; result=F; s=1; t=0;
1044  }
1045  CanonicalForm inv, rem, q, u, v;
1046  // here: degree(P) >= degree(result)
1047  while(true)
1048  {
1049    tryInvert( Lc(result), M, inv, fail );
1050    if(fail)
1051      return;
1052    // here: Lc(result) is invertible modulo M
1053    q = Lc(P)*inv * power( P.mvar(), degree(P)-degree(result) );
1054    rem = P - q*result;
1055    // here: s*F + t*G = result
1056    if( rem.isZero() )
1057    {
1058      s*=inv;
1059      t*=inv;
1060      result *= inv; // monify result
1061      return;
1062    }
1063    P=result;
1064    result=rem;
1065    rem=u-q*s;
1066    u=s;
1067    s=rem;
1068    rem=v-q*t;
1069    v=t;
1070    t=rem;
1071  }
1072}
1073
1074void tryCRA( const CanonicalForm & x1, const CanonicalForm & q1, const CanonicalForm & x2, const CanonicalForm & q2, CanonicalForm & xnew, CanonicalForm & qnew, bool & fail )
1075{ // polys of level <= 1 are considered coefficients. q1,q2 are assumed to be coprime
1076  // xnew = x1 mod q1 (coefficientwise in the above sense)
1077  // xnew = x2 mod q2
1078  // qnew = q1*q2
1079  CanonicalForm tmp;
1080  if(x1.level() <= 1 && x2.level() <= 1) // base case
1081  {
1082    tryExtgcd(q1,q2,tmp,xnew,qnew,fail);
1083    if(fail)
1084      return;
1085    xnew = x1 + (x2-x1) * xnew * q1;
1086    qnew = q1*q2;
1087    xnew = mod(xnew,qnew);
1088    return;
1089  }
1090  CanonicalForm tmp2;
1091  xnew = 0;
1092  qnew = q1 * q2;
1093  // here: x1.level() > 1 || x2.level() > 1
1094  if(x1.level() > x2.level())
1095  {
1096    for(CFIterator i=x1; i.hasTerms(); i++)
1097    {
1098      if(i.exp() == 0) // const. term
1099      {
1100        tryCRA(i.coeff(),q1,x2,q2,tmp,tmp2,fail);
1101        if(fail)
1102          return;
1103        xnew += tmp;
1104      }
1105      else
1106      {
1107        tryCRA(i.coeff(),q1,0,q2,tmp,tmp2,fail);
1108        if(fail)
1109          return;
1110        xnew += tmp * power(x1.mvar(),i.exp());
1111      }
1112    }
1113    return;
1114  }
1115  // here: x1.level() <= x2.level() && ( x1.level() > 1 || x2.level() > 1 )
1116  if(x2.level() > x1.level())
1117  {
1118    for(CFIterator j=x2; j.hasTerms(); j++)
1119    {
1120      if(j.exp() == 0) // const. term
1121      {
1122        tryCRA(x1,q1,j.coeff(),q2,tmp,tmp2,fail);
1123        if(fail)
1124          return;
1125        xnew += tmp;
1126      }
1127      else
1128      {
1129        tryCRA(0,q1,j.coeff(),q2,tmp,tmp2,fail);
1130        if(fail)
1131          return;
1132        xnew += tmp * power(x2.mvar(),j.exp());
1133      }
1134    }
1135    return;
1136  }
1137  // here: x1.level() == x2.level() && x1.level() > 1 && x2.level() > 1
1138  CFIterator i = x1;
1139  CFIterator j = x2;
1140  while(i.hasTerms() || j.hasTerms())
1141  {
1142    if(i.hasTerms())
1143    {
1144      if(j.hasTerms())
1145      {
1146        if(i.exp() == j.exp())
1147        {
1148          tryCRA(i.coeff(),q1,j.coeff(),q2,tmp,tmp2,fail);
1149          if(fail)
1150            return;
1151          xnew += tmp * power(x1.mvar(),i.exp());
1152          i++; j++;
1153        }
1154        else
1155        {
1156          if(i.exp() < j.exp())
1157          {
1158            tryCRA(i.coeff(),q1,0,q2,tmp,tmp2,fail);
1159            if(fail)
1160              return;
1161            xnew += tmp * power(x1.mvar(),i.exp());
1162            i++;
1163          }
1164          else // i.exp() > j.exp()
1165          {
1166            tryCRA(0,q1,j.coeff(),q2,tmp,tmp2,fail);
1167            if(fail)
1168              return;
1169            xnew += tmp * power(x1.mvar(),j.exp());
1170            j++;
1171          }
1172        }
1173      }
1174      else // j is out of terms
1175      {
1176        tryCRA(i.coeff(),q1,0,q2,tmp,tmp2,fail);
1177        if(fail)
1178          return;
1179        xnew += tmp * power(x1.mvar(),i.exp());
1180        i++;
1181      }
1182    }
1183    else // i is out of terms
1184    {
1185      tryCRA(0,q1,j.coeff(),q2,tmp,tmp2,fail);
1186      if(fail)
1187        return;
1188      xnew += tmp * power(x1.mvar(),j.exp());
1189      j++;
1190    }
1191  }
1192}
1193
Note: See TracBrowser for help on using the repository browser.