3 * Polynomial factorization (implementation).
5 * The interface function factor() at the end of this file is defined in the
6 * GiNaC namespace. All other utility functions and classes are defined in an
7 * additional anonymous namespace.
9 * Factorization starts by doing a square free factorization and making the
10 * coefficients integer. Then, depending on the number of free variables it
11 * proceeds either in dedicated univariate or multivariate factorization code.
13 * Univariate factorization does a modular factorization via Berlekamp's
14 * algorithm and distinct degree factorization. Hensel lifting is used at the
17 * Multivariate factorization uses the univariate factorization (applying a
18 * evaluation homomorphism first) and Hensel lifting raises the answer to the
19 * multivariate domain. The Hensel lifting code is completely distinct from the
20 * code used by the univariate factorization.
22 * Algorithms used can be found in
23 * [Wan] An Improved Multivariate Polynomial Factoring Algorithm,
25 * Mathematics of Computation, Vol. 32, No. 144 (1978) 1215--1231.
26 * [GCL] Algorithms for Computer Algebra,
27 * K.O.Geddes, S.R.Czapor, G.Labahn,
28 * Springer Verlag, 1992.
29 * [Mig] Some Useful Bounds,
31 * In "Computer Algebra, Symbolic and Algebraic Computation" (B.Buchberger et al., eds.),
32 * pp. 259-263, Springer-Verlag, New York, 1982.
36 * GiNaC Copyright (C) 1999-2008 Johannes Gutenberg University Mainz, Germany
38 * This program is free software; you can redistribute it and/or modify
39 * it under the terms of the GNU General Public License as published by
40 * the Free Software Foundation; either version 2 of the License, or
41 * (at your option) any later version.
43 * This program is distributed in the hope that it will be useful,
44 * but WITHOUT ANY WARRANTY; without even the implied warranty of
45 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
46 * GNU General Public License for more details.
48 * You should have received a copy of the GNU General Public License
49 * along with this program; if not, write to the Free Software
50 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
59 #include "operators.h"
62 #include "relational.h"
84 #define DCOUT(str) cout << #str << endl
85 #define DCOUTVAR(var) cout << #var << ": " << var << endl
86 #define DCOUT2(str,var) cout << #str << ": " << var << endl
87 ostream& operator<<(ostream& o, const vector<int>& v)
89 vector<int>::const_iterator i = v.begin(), end = v.end();
95 ostream& operator<<(ostream& o, const vector<cl_I>& v)
97 vector<cl_I>::const_iterator i = v.begin(), end = v.end();
99 o << *i << "[" << i-v.begin() << "]" << " ";
104 ostream& operator<<(ostream& o, const vector<cl_MI>& v)
106 vector<cl_MI>::const_iterator i = v.begin(), end = v.end();
108 o << *i << "[" << i-v.begin() << "]" << " ";
113 ostream& operator<<(ostream& o, const vector<numeric>& v)
115 for ( size_t i=0; i<v.size(); ++i ) {
120 ostream& operator<<(ostream& o, const vector< vector<cl_MI> >& v)
122 vector< vector<cl_MI> >::const_iterator i = v.begin(), end = v.end();
124 o << i-v.begin() << ": " << *i << endl;
131 #define DCOUTVAR(var)
132 #define DCOUT2(str,var)
133 #endif // def DEBUGFACTOR
135 // anonymous namespace to hide all utility functions
138 ////////////////////////////////////////////////////////////////////////////////
139 // modular univariate polynomial code
141 typedef std::vector<cln::cl_MI> umodpoly;
142 typedef std::vector<cln::cl_I> upoly;
143 typedef vector<umodpoly> upvec;
145 // COPY FROM UPOLY.HPP
147 // CHANGED size_t -> int !!!
148 template<typename T> static int degree(const T& p)
153 template<typename T> static typename T::value_type lcoeff(const T& p)
155 return p[p.size() - 1];
158 static bool normalize_in_field(umodpoly& a)
162 if ( lcoeff(a) == a[0].ring()->one() ) {
166 const cln::cl_MI lc_1 = recip(lcoeff(a));
167 for (std::size_t k = a.size(); k-- != 0; )
172 template<typename T> static void
173 canonicalize(T& p, const typename T::size_type hint = std::numeric_limits<typename T::size_type>::max())
178 std::size_t i = p.size() - 1;
179 // Be fast if the polynomial is already canonicalized
186 bool is_zero = false;
204 p.erase(p.begin() + i, p.end());
207 // END COPY FROM UPOLY.HPP
209 static void expt_pos(umodpoly& a, unsigned int q)
211 if ( a.empty() ) return;
212 cl_MI zero = a[0].ring()->zero();
214 a.resize(degree(a)*q+1, zero);
215 for ( int i=deg; i>0; --i ) {
222 static T operator+(const T& a, const T& b)
229 for ( ; i<sb; ++i ) {
232 for ( ; i<sa; ++i ) {
241 for ( ; i<sa; ++i ) {
244 for ( ; i<sb; ++i ) {
253 static T operator-(const T& a, const T& b)
260 for ( ; i<sb; ++i ) {
263 for ( ; i<sa; ++i ) {
272 for ( ; i<sa; ++i ) {
275 for ( ; i<sb; ++i ) {
283 static upoly operator*(const upoly& a, const upoly& b)
286 if ( a.empty() || b.empty() ) return c;
288 int n = degree(a) + degree(b);
290 for ( int i=0 ; i<=n; ++i ) {
291 for ( int j=0 ; j<=i; ++j ) {
292 if ( j > degree(a) || (i-j) > degree(b) ) continue;
293 c[i] = c[i] + a[j] * b[i-j];
300 static umodpoly operator*(const umodpoly& a, const umodpoly& b)
303 if ( a.empty() || b.empty() ) return c;
305 int n = degree(a) + degree(b);
306 c.resize(n+1, a[0].ring()->zero());
307 for ( int i=0 ; i<=n; ++i ) {
308 for ( int j=0 ; j<=i; ++j ) {
309 if ( j > degree(a) || (i-j) > degree(b) ) continue;
310 c[i] = c[i] + a[j] * b[i-j];
317 static upoly operator*(const upoly& a, const cl_I& x)
324 for ( size_t i=0; i<a.size(); ++i ) {
330 static upoly operator/(const upoly& a, const cl_I& x)
337 for ( size_t i=0; i<a.size(); ++i ) {
338 r[i] = exquo(a[i],x);
343 static umodpoly operator*(const umodpoly& a, const cl_MI& x)
345 umodpoly r(a.size());
346 for ( size_t i=0; i<a.size(); ++i ) {
353 static void upoly_from_ex(upoly& up, const ex& e, const ex& x)
355 // assert: e is in Z[x]
356 int deg = e.degree(x);
358 int ldeg = e.ldegree(x);
359 for ( ; deg>=ldeg; --deg ) {
360 up[deg] = the<cl_I>(ex_to<numeric>(e.coeff(x, deg)).to_cl_N());
362 for ( ; deg>=0; --deg ) {
368 static void umodpoly_from_upoly(umodpoly& ump, const upoly& e, const cl_modint_ring& R)
372 for ( ; deg>=0; --deg ) {
373 ump[deg] = R->canonhom(e[deg]);
378 static void umodpoly_from_ex(umodpoly& ump, const ex& e, const ex& x, const cl_modint_ring& R)
380 // assert: e is in Z[x]
381 int deg = e.degree(x);
383 int ldeg = e.ldegree(x);
384 for ( ; deg>=ldeg; --deg ) {
385 cl_I coeff = the<cl_I>(ex_to<numeric>(e.coeff(x, deg)).to_cl_N());
386 ump[deg] = R->canonhom(coeff);
388 for ( ; deg>=0; --deg ) {
389 ump[deg] = R->zero();
395 static void umodpoly_from_ex(umodpoly& ump, const ex& e, const ex& x, const cl_I& modulus)
397 umodpoly_from_ex(ump, e, x, find_modint_ring(modulus));
401 static ex upoly_to_ex(const upoly& a, const ex& x)
403 if ( a.empty() ) return 0;
405 for ( int i=degree(a); i>=0; --i ) {
406 e += numeric(a[i]) * pow(x, i);
411 static ex umodpoly_to_ex(const umodpoly& a, const ex& x)
413 if ( a.empty() ) return 0;
414 cl_modint_ring R = a[0].ring();
415 cl_I mod = R->modulus;
416 cl_I halfmod = (mod-1) >> 1;
418 for ( int i=degree(a); i>=0; --i ) {
419 cl_I n = R->retract(a[i]);
421 e += numeric(n-mod) * pow(x, i);
423 e += numeric(n) * pow(x, i);
429 static upoly umodpoly_to_upoly(const umodpoly& a)
432 if ( a.empty() ) return e;
433 cl_modint_ring R = a[0].ring();
434 cl_I mod = R->modulus;
435 cl_I halfmod = (mod-1) >> 1;
436 for ( int i=degree(a); i>=0; --i ) {
437 cl_I n = R->retract(a[i]);
447 static umodpoly umodpoly_to_umodpoly(const umodpoly& a, const cl_modint_ring& R, unsigned int m)
450 if ( a.empty() ) return e;
451 cl_modint_ring oldR = a[0].ring();
452 size_t sa = a.size();
453 e.resize(sa+m, R->zero());
454 for ( size_t i=0; i<sa; ++i ) {
455 e[i+m] = R->canonhom(oldR->retract(a[i]));
461 /** Divides all coefficients of the polynomial a by the integer x.
462 * All coefficients are supposed to be divisible by x. If they are not, the
463 * the<cl_I> cast will raise an exception.
465 * @param[in,out] a polynomial of which the coefficients will be reduced by x
466 * @param[in] x integer that divides the coefficients
468 static void reduce_coeff(umodpoly& a, const cl_I& x)
470 if ( a.empty() ) return;
472 cl_modint_ring R = a[0].ring();
473 umodpoly::iterator i = a.begin(), end = a.end();
474 for ( ; i!=end; ++i ) {
475 // cln cannot perform this division in the modular field
476 cl_I c = R->retract(*i);
477 *i = cl_MI(R, the<cl_I>(c / x));
481 /** Calculates remainder of a/b.
482 * Assertion: a and b not empty.
484 * @param[in] a polynomial dividend
485 * @param[in] b polynomial divisor
486 * @param[out] r polynomial remainder
488 static void rem(const umodpoly& a, const umodpoly& b, umodpoly& r)
497 cl_MI qk = div(r[n+k], b[n]);
499 for ( int i=0; i<n; ++i ) {
500 unsigned int j = n + k - 1 - i;
501 r[j] = r[j] - qk * b[j-k];
506 fill(r.begin()+n, r.end(), a[0].ring()->zero());
510 /** Calculates quotient of a/b.
511 * Assertion: a and b not empty.
513 * @param[in] a polynomial dividend
514 * @param[in] b polynomial divisor
515 * @param[out] q polynomial quotient
517 static void div(const umodpoly& a, const umodpoly& b, umodpoly& q)
526 q.resize(k+1, a[0].ring()->zero());
528 cl_MI qk = div(r[n+k], b[n]);
531 for ( int i=0; i<n; ++i ) {
532 unsigned int j = n + k - 1 - i;
533 r[j] = r[j] - qk * b[j-k];
541 /** Calculates quotient and remainder of a/b.
542 * Assertion: a and b not empty.
544 * @param[in] a polynomial dividend
545 * @param[in] b polynomial divisor
546 * @param[out] r polynomial remainder
547 * @param[out] q polynomial quotient
549 static void remdiv(const umodpoly& a, const umodpoly& b, umodpoly& r, umodpoly& q)
558 q.resize(k+1, a[0].ring()->zero());
560 cl_MI qk = div(r[n+k], b[n]);
563 for ( int i=0; i<n; ++i ) {
564 unsigned int j = n + k - 1 - i;
565 r[j] = r[j] - qk * b[j-k];
570 fill(r.begin()+n, r.end(), a[0].ring()->zero());
575 /** Calculates the GCD of polynomial a and b.
577 * @param[in] a polynomial
578 * @param[in] b polynomial
581 static void gcd(const umodpoly& a, const umodpoly& b, umodpoly& c)
583 if ( degree(a) < degree(b) ) return gcd(b, a, c);
586 normalize_in_field(c);
588 normalize_in_field(d);
590 while ( !d.empty() ) {
595 normalize_in_field(c);
598 /** Calculates the derivative of the polynomial a.
600 * @param[in] a polynomial of which to take the derivative
601 * @param[out] d result/derivative
603 static void deriv(const umodpoly& a, umodpoly& d)
606 if ( a.size() <= 1 ) return;
608 d.insert(d.begin(), a.begin()+1, a.end());
610 for ( int i=1; i<max; ++i ) {
616 static bool unequal_one(const umodpoly& a)
618 if ( a.empty() ) return true;
619 return ( a.size() != 1 || a[0] != a[0].ring()->one() );
622 static bool equal_one(const umodpoly& a)
624 return ( a.size() == 1 && a[0] == a[0].ring()->one() );
627 /** Returns true if polynomial a is square free.
629 * @param[in] a polynomial to check
630 * @return true if polynomial is square free, false otherwise
632 static bool squarefree(const umodpoly& a)
644 // END modular univariate polynomial code
645 ////////////////////////////////////////////////////////////////////////////////
647 ////////////////////////////////////////////////////////////////////////////////
650 typedef vector<cl_MI> mvec;
654 friend ostream& operator<<(ostream& o, const modular_matrix& m);
656 modular_matrix(size_t r_, size_t c_, const cl_MI& init) : r(r_), c(c_)
660 size_t rowsize() const { return r; }
661 size_t colsize() const { return c; }
662 cl_MI& operator()(size_t row, size_t col) { return m[row*c + col]; }
663 cl_MI operator()(size_t row, size_t col) const { return m[row*c + col]; }
664 void mul_col(size_t col, const cl_MI x)
666 mvec::iterator i = m.begin() + col;
667 for ( size_t rc=0; rc<r; ++rc ) {
672 void sub_col(size_t col1, size_t col2, const cl_MI fac)
674 mvec::iterator i1 = m.begin() + col1;
675 mvec::iterator i2 = m.begin() + col2;
676 for ( size_t rc=0; rc<r; ++rc ) {
677 *i1 = *i1 - *i2 * fac;
682 void switch_col(size_t col1, size_t col2)
685 mvec::iterator i1 = m.begin() + col1;
686 mvec::iterator i2 = m.begin() + col2;
687 for ( size_t rc=0; rc<r; ++rc ) {
688 buf = *i1; *i1 = *i2; *i2 = buf;
693 void mul_row(size_t row, const cl_MI x)
695 vector<cl_MI>::iterator i = m.begin() + row*c;
696 for ( size_t cc=0; cc<c; ++cc ) {
701 void sub_row(size_t row1, size_t row2, const cl_MI fac)
703 vector<cl_MI>::iterator i1 = m.begin() + row1*c;
704 vector<cl_MI>::iterator i2 = m.begin() + row2*c;
705 for ( size_t cc=0; cc<c; ++cc ) {
706 *i1 = *i1 - *i2 * fac;
711 void switch_row(size_t row1, size_t row2)
714 vector<cl_MI>::iterator i1 = m.begin() + row1*c;
715 vector<cl_MI>::iterator i2 = m.begin() + row2*c;
716 for ( size_t cc=0; cc<c; ++cc ) {
717 buf = *i1; *i1 = *i2; *i2 = buf;
722 bool is_col_zero(size_t col) const
724 mvec::const_iterator i = m.begin() + col;
725 for ( size_t rr=0; rr<r; ++rr ) {
733 bool is_row_zero(size_t row) const
735 mvec::const_iterator i = m.begin() + row*c;
736 for ( size_t cc=0; cc<c; ++cc ) {
744 void set_row(size_t row, const vector<cl_MI>& newrow)
746 mvec::iterator i1 = m.begin() + row*c;
747 mvec::const_iterator i2 = newrow.begin(), end = newrow.end();
748 for ( ; i2 != end; ++i1, ++i2 ) {
752 mvec::const_iterator row_begin(size_t row) const { return m.begin()+row*c; }
753 mvec::const_iterator row_end(size_t row) const { return m.begin()+row*c+r; }
760 modular_matrix operator*(const modular_matrix& m1, const modular_matrix& m2)
762 const unsigned int r = m1.rowsize();
763 const unsigned int c = m2.colsize();
764 modular_matrix o(r,c,m1(0,0));
766 for ( size_t i=0; i<r; ++i ) {
767 for ( size_t j=0; j<c; ++j ) {
769 buf = m1(i,0) * m2(0,j);
770 for ( size_t k=1; k<c; ++k ) {
771 buf = buf + m1(i,k)*m2(k,j);
779 ostream& operator<<(ostream& o, const modular_matrix& m)
781 cl_modint_ring R = m(0,0).ring();
783 for ( size_t i=0; i<m.rowsize(); ++i ) {
785 for ( size_t j=0; j<m.colsize()-1; ++j ) {
786 o << R->retract(m(i,j)) << ",";
788 o << R->retract(m(i,m.colsize()-1)) << "}";
789 if ( i != m.rowsize()-1 ) {
796 #endif // def DEBUGFACTOR
798 // END modular matrix
799 ////////////////////////////////////////////////////////////////////////////////
801 /** Calculates the Q matrix for a polynomial. Used by Berlekamp's algorithm.
803 * @param[in] a_ modular polynomial
804 * @param[out] Q Q matrix
806 static void q_matrix(const umodpoly& a_, modular_matrix& Q)
809 normalize_in_field(a);
812 unsigned int q = cl_I_to_uint(a[0].ring()->modulus);
813 umodpoly r(n, a[0].ring()->zero());
814 r[0] = a[0].ring()->one();
816 unsigned int max = (n-1) * q;
817 for ( size_t m=1; m<=max; ++m ) {
818 cl_MI rn_1 = r.back();
819 for ( size_t i=n-1; i>0; --i ) {
820 r[i] = r[i-1] - (rn_1 * a[i]);
823 if ( (m % q) == 0 ) {
829 /** Determine the nullspace of a matrix M-1.
831 * @param[in,out] M matrix, will be modified
832 * @param[out] basis calculated nullspace of M-1
834 static void nullspace(modular_matrix& M, vector<mvec>& basis)
836 const size_t n = M.rowsize();
837 const cl_MI one = M(0,0).ring()->one();
838 for ( size_t i=0; i<n; ++i ) {
839 M(i,i) = M(i,i) - one;
841 for ( size_t r=0; r<n; ++r ) {
843 for ( ; cc<n; ++cc ) {
844 if ( !zerop(M(r,cc)) ) {
846 if ( !zerop(M(cc,cc)) ) {
858 M.mul_col(r, recip(M(r,r)));
859 for ( cc=0; cc<n; ++cc ) {
861 M.sub_col(cc, r, M(r,cc));
867 for ( size_t i=0; i<n; ++i ) {
868 M(i,i) = M(i,i) - one;
870 for ( size_t i=0; i<n; ++i ) {
871 if ( !M.is_row_zero(i) ) {
872 mvec nu(M.row_begin(i), M.row_end(i));
878 /** Berlekamp's modular factorization.
880 * The implementation follows the algorithm in chapter 8 of [GCL].
882 * @param[in] a modular polynomial
883 * @param[out] upv vector containing modular factors. if upv was not empty the
884 * new elements are added at the end
886 static void berlekamp(const umodpoly& a, upvec& upv)
888 cl_modint_ring R = a[0].ring();
889 umodpoly one(1, R->one());
891 // find nullspace of Q matrix
892 modular_matrix Q(degree(a), degree(a), R->zero());
897 const unsigned int k = nu.size();
903 list<umodpoly> factors;
904 factors.push_back(a);
905 unsigned int size = 1;
907 unsigned int q = cl_I_to_uint(R->modulus);
909 list<umodpoly>::iterator u = factors.begin();
911 // calculate all gcd's
913 for ( unsigned int s=0; s<q; ++s ) {
914 umodpoly nur = nu[r];
915 nur[0] = nur[0] - cl_MI(R, s);
919 if ( unequal_one(g) && g != *u ) {
922 if ( equal_one(uo) ) {
923 throw logic_error("berlekamp: unexpected divisor.");
928 factors.push_back(g);
930 list<umodpoly>::const_iterator i = factors.begin(), end = factors.end();
932 if ( degree(*i) ) ++size;
936 list<umodpoly>::const_iterator i = factors.begin(), end = factors.end();
951 // modular square free factorization is not used at the moment so we deactivate
955 /** Calculates a^(1/prime).
957 * @param[in] a polynomial
958 * @param[in] prime prime number -> exponent 1/prime
959 * @param[in] ap resulting polynomial
961 static void expt_1_over_p(const umodpoly& a, unsigned int prime, umodpoly& ap)
963 size_t newdeg = degree(a)/prime;
966 for ( size_t i=1; i<=newdeg; ++i ) {
971 /** Modular square free factorization.
973 * @param[in] a polynomial
974 * @param[out] factors modular factors
975 * @param[out] mult corresponding multiplicities (exponents)
977 static void modsqrfree(const umodpoly& a, upvec& factors, vector<int>& mult)
979 const unsigned int prime = cl_I_to_uint(a[0].ring()->modulus);
988 while ( unequal_one(w) ) {
993 factors.push_back(z);
1001 if ( unequal_one(c) ) {
1003 expt_1_over_p(c, prime, cp);
1004 size_t previ = mult.size();
1005 modsqrfree(cp, factors, mult);
1006 for ( size_t i=previ; i<mult.size(); ++i ) {
1013 expt_1_over_p(a, prime, ap);
1014 size_t previ = mult.size();
1015 modsqrfree(ap, factors, mult);
1016 for ( size_t i=previ; i<mult.size(); ++i ) {
1022 #endif // deactivation of square free factorization
1024 /** Distinct degree factorization (DDF).
1026 * The implementation follows the algorithm in chapter 8 of [GCL].
1028 * @param[in] a_ modular polynomial
1029 * @param[out] degrees vector containing the degrees of the factors of the
1030 * corresponding polynomials in ddfactors.
1031 * @param[out] ddfactors vector containing polynomials which factors have the
1032 * degree given in degrees.
1034 static void distinct_degree_factor(const umodpoly& a_, vector<int>& degrees, upvec& ddfactors)
1038 cl_modint_ring R = a[0].ring();
1039 int q = cl_I_to_int(R->modulus);
1040 int nhalf = degree(a)/2;
1048 while ( i <= nhalf ) {
1053 umodpoly wx = w - x;
1055 if ( unequal_one(buf) ) {
1056 degrees.push_back(i);
1057 ddfactors.push_back(buf);
1059 if ( unequal_one(buf) ) {
1063 nhalf = degree(a)/2;
1069 if ( unequal_one(a) ) {
1070 degrees.push_back(degree(a));
1071 ddfactors.push_back(a);
1075 /** Modular same degree factorization.
1076 * Same degree factorization is a kind of misnomer. It performs distinct degree
1077 * factorization, but instead of using the Cantor-Zassenhaus algorithm it
1078 * (sub-optimally) uses Berlekamp's algorithm for the factors of the same
1081 * @param[in] a modular polynomial
1082 * @param[out] upv vector containing modular factors. if upv was not empty the
1083 * new elements are added at the end
1085 static void same_degree_factor(const umodpoly& a, upvec& upv)
1087 cl_modint_ring R = a[0].ring();
1089 vector<int> degrees;
1091 distinct_degree_factor(a, degrees, ddfactors);
1093 for ( size_t i=0; i<degrees.size(); ++i ) {
1094 if ( degrees[i] == degree(ddfactors[i]) ) {
1095 upv.push_back(ddfactors[i]);
1098 berlekamp(ddfactors[i], upv);
1103 // Yes, we can (choose).
1104 #define USE_SAME_DEGREE_FACTOR
1106 /** Modular univariate factorization.
1108 * In principle, we have two algorithms at our disposal: Berlekamp's algorithm
1109 * and same degree factorization (SDF). SDF seems to be slightly faster in
1110 * almost all cases so it is activated as default.
1112 * @param[in] p modular polynomial
1113 * @param[out] upv vector containing modular factors. if upv was not empty the
1114 * new elements are added at the end
1116 static void factor_modular(const umodpoly& p, upvec& upv)
1118 #ifdef USE_SAME_DEGREE_FACTOR
1119 same_degree_factor(p, upv);
1125 /** Calculates modular polynomials s and t such that a*s+b*t==1.
1126 * Assertion: a and b are relatively prime and not zero.
1128 * @param[in] a polynomial
1129 * @param[in] b polynomial
1130 * @param[out] s polynomial
1131 * @param[out] t polynomial
1133 static void exteuclid(const umodpoly& a, const umodpoly& b, umodpoly& s, umodpoly& t)
1135 if ( degree(a) < degree(b) ) {
1136 exteuclid(b, a, t, s);
1140 umodpoly one(1, a[0].ring()->one());
1141 umodpoly c = a; normalize_in_field(c);
1142 umodpoly d = b; normalize_in_field(d);
1150 umodpoly r = c - q * d;
1151 umodpoly r1 = s - q * d1;
1152 umodpoly r2 = t - q * d2;
1156 if ( r.empty() ) break;
1161 cl_MI fac = recip(lcoeff(a) * lcoeff(c));
1162 umodpoly::iterator i = s.begin(), end = s.end();
1163 for ( ; i!=end; ++i ) {
1167 fac = recip(lcoeff(b) * lcoeff(c));
1168 i = t.begin(), end = t.end();
1169 for ( ; i!=end; ++i ) {
1175 /** Replaces the leading coefficient in a polynomial by a given number.
1177 * @param[in] poly polynomial to change
1178 * @param[in] lc new leading coefficient
1179 * @return changed polynomial
1181 static upoly replace_lc(const upoly& poly, const cl_I& lc)
1183 if ( poly.empty() ) return poly;
1189 /** Calculates the bound for the modulus.
1192 static inline cl_I calc_bound(const ex& a, const ex& x, int maxdeg)
1196 for ( int i=a.degree(x); i>=a.ldegree(x); --i ) {
1197 cl_I aa = abs(the<cl_I>(ex_to<numeric>(a.coeff(x, i)).to_cl_N()));
1198 if ( aa > maxcoeff ) maxcoeff = aa;
1199 coeff = coeff + square(aa);
1201 cl_I coeffnorm = ceiling1(the<cl_R>(cln::sqrt(coeff)));
1202 cl_I B = coeffnorm * expt_pos(cl_I(2), cl_I(maxdeg));
1203 return ( B > maxcoeff ) ? B : maxcoeff;
1206 /** Calculates the bound for the modulus.
1209 static inline cl_I calc_bound(const upoly& a, int maxdeg)
1213 for ( int i=degree(a); i>=0; --i ) {
1214 cl_I aa = abs(a[i]);
1215 if ( aa > maxcoeff ) maxcoeff = aa;
1216 coeff = coeff + square(aa);
1218 cl_I coeffnorm = ceiling1(the<cl_R>(cln::sqrt(coeff)));
1219 cl_I B = coeffnorm * expt_pos(cl_I(2), cl_I(maxdeg));
1220 return ( B > maxcoeff ) ? B : maxcoeff;
1223 /** Hensel lifting as used by factor_univariate().
1225 * The implementation follows the algorithm in chapter 6 of [GCL].
1227 * @param[in] a_ primitive univariate polynomials
1228 * @param[in] p prime number that does not divide lcoeff(a)
1229 * @param[in] u1_ modular factor of a (mod p)
1230 * @param[in] w1_ modular factor of a (mod p), relatively prime to u1_,
1231 * fulfilling u1_*w1_ == a mod p
1232 * @param[out] u lifted factor
1233 * @param[out] w lifted factor, u*w = a
1235 static void hensel_univar(const upoly& a_, unsigned int p, const umodpoly& u1_, const umodpoly& w1_, upoly& u, upoly& w)
1238 const cl_modint_ring& R = u1_[0].ring();
1241 int maxdeg = (degree(u1_) > degree(w1_)) ? degree(u1_) : degree(w1_);
1242 cl_I maxmodulus = 2*calc_bound(a, maxdeg);
1245 cl_I alpha = lcoeff(a);
1248 normalize_in_field(nu1);
1250 normalize_in_field(nw1);
1252 phi = umodpoly_to_upoly(nu1) * alpha;
1254 umodpoly_from_upoly(u1, phi, R);
1255 phi = umodpoly_to_upoly(nw1) * alpha;
1257 umodpoly_from_upoly(w1, phi, R);
1262 exteuclid(u1, w1, s, t);
1265 u = replace_lc(umodpoly_to_upoly(u1), alpha);
1266 w = replace_lc(umodpoly_to_upoly(w1), alpha);
1267 upoly e = a - u * w;
1271 while ( !e.empty() && modulus < maxmodulus ) {
1272 upoly c = e / modulus;
1273 phi = umodpoly_to_upoly(s) * c;
1274 umodpoly sigmatilde;
1275 umodpoly_from_upoly(sigmatilde, phi, R);
1276 phi = umodpoly_to_upoly(t) * c;
1278 umodpoly_from_upoly(tautilde, phi, R);
1280 remdiv(sigmatilde, w1, r, q);
1282 phi = umodpoly_to_upoly(tautilde) + umodpoly_to_upoly(q) * umodpoly_to_upoly(u1);
1284 umodpoly_from_upoly(tau, phi, R);
1285 u = u + umodpoly_to_upoly(tau) * modulus;
1286 w = w + umodpoly_to_upoly(sigma) * modulus;
1288 modulus = modulus * p;
1294 for ( size_t i=1; i<u.size(); ++i ) {
1296 if ( g == 1 ) break;
1311 /** Returns a new prime number.
1313 * @param[in] p prime number
1314 * @return next prime number after p
1316 static unsigned int next_prime(unsigned int p)
1318 static vector<unsigned int> primes;
1319 if ( primes.size() == 0 ) {
1320 primes.push_back(3); primes.push_back(5); primes.push_back(7);
1322 vector<unsigned int>::const_iterator it = primes.begin();
1323 if ( p >= primes.back() ) {
1324 unsigned int candidate = primes.back() + 2;
1326 size_t n = primes.size()/2;
1327 for ( size_t i=0; i<n; ++i ) {
1328 if ( candidate % primes[i] ) continue;
1332 primes.push_back(candidate);
1333 if ( candidate > p ) break;
1337 vector<unsigned int>::const_iterator end = primes.end();
1338 for ( ; it!=end; ++it ) {
1343 throw logic_error("next_prime: should not reach this point!");
1346 /** Manages the splitting a vector of of modular factors into two partitions.
1348 class factor_partition
1351 /** Takes the vector of modular factors and initializes the first partition */
1352 factor_partition(const upvec& factors_) : factors(factors_)
1358 one.resize(1, factors.front()[0].ring()->one());
1363 int operator[](size_t i) const { return k[i]; }
1364 size_t size() const { return n; }
1365 size_t size_left() const { return n-len; }
1366 size_t size_right() const { return len; }
1367 /** Initializes the next partition.
1368 Returns true, if there is one, false otherwise. */
1371 if ( last == n-1 ) {
1381 while ( k[last] == 0 ) { --last; }
1382 if ( last == 0 && n == 2*len ) return false;
1384 for ( size_t i=0; i<=len-rem; ++i ) {
1388 fill(k.begin()+last, k.end(), 0);
1395 if ( len > n/2 ) return false;
1396 fill(k.begin(), k.begin()+len, 1);
1397 fill(k.begin()+len+1, k.end(), 0);
1406 /** Get first partition */
1407 umodpoly& left() { return lr[0]; }
1408 /** Get second partition */
1409 umodpoly& right() { return lr[1]; }
1418 while ( i < n && k[i] == group ) { ++d; ++i; }
1420 if ( cache[pos].size() >= d ) {
1421 lr[group] = lr[group] * cache[pos][d-1];
1424 if ( cache[pos].size() == 0 ) {
1425 cache[pos].push_back(factors[pos] * factors[pos+1]);
1427 size_t j = pos + cache[pos].size() + 1;
1428 d -= cache[pos].size();
1430 umodpoly buf = cache[pos].back() * factors[j];
1431 cache[pos].push_back(buf);
1435 lr[group] = lr[group] * cache[pos].back();
1439 lr[group] = lr[group] * factors[pos];
1451 for ( size_t i=0; i<n; ++i ) {
1452 lr[k[i]] = lr[k[i]] * factors[i];
1458 vector< vector<umodpoly> > cache;
1467 /** Contains a pair of univariate polynomial and its modular factors.
1468 * Used by factor_univariate().
1476 /** Univariate polynomial factorization.
1478 * Modular factorization is tried for several primes to minimize the number of
1479 * modular factors. Then, Hensel lifting is performed.
1481 * @param[in] poly expanded square free univariate polynomial
1482 * @param[in] x symbol
1483 * @param[in,out] prime prime number to start trying modular factorization with,
1484 * output value is the prime number actually used
1486 static ex factor_univariate(const ex& poly, const ex& x, unsigned int& prime)
1488 ex unit, cont, prim_ex;
1489 poly.unitcontprim(x, unit, cont, prim_ex);
1491 upoly_from_ex(prim, prim_ex, x);
1493 // determine proper prime and minimize number of modular factors
1495 unsigned int lastp = prime;
1497 unsigned int trials = 0;
1498 unsigned int minfactors = 0;
1499 cl_I lc = lcoeff(prim) * the<cl_I>(ex_to<numeric>(cont).to_cl_N());
1501 while ( trials < 2 ) {
1504 prime = next_prime(prime);
1505 if ( !zerop(rem(lc, prime)) ) {
1506 R = find_modint_ring(prime);
1507 umodpoly_from_upoly(modpoly, prim, R);
1508 if ( squarefree(modpoly) ) break;
1512 // do modular factorization
1514 factor_modular(modpoly, trialfactors);
1515 if ( trialfactors.size() <= 1 ) {
1516 // irreducible for sure
1520 if ( minfactors == 0 || trialfactors.size() < minfactors ) {
1521 factors = trialfactors;
1522 minfactors = trialfactors.size();
1531 R = find_modint_ring(prime);
1533 // lift all factor combinations
1534 stack<ModFactors> tocheck;
1537 mf.factors = factors;
1541 while ( tocheck.size() ) {
1542 const size_t n = tocheck.top().factors.size();
1543 factor_partition part(tocheck.top().factors);
1545 // call Hensel lifting
1546 hensel_univar(tocheck.top().poly, prime, part.left(), part.right(), f1, f2);
1547 if ( !f1.empty() ) {
1548 // successful, update the stack and the result
1549 if ( part.size_left() == 1 ) {
1550 if ( part.size_right() == 1 ) {
1551 result *= upoly_to_ex(f1, x) * upoly_to_ex(f2, x);
1555 result *= upoly_to_ex(f1, x);
1556 tocheck.top().poly = f2;
1557 for ( size_t i=0; i<n; ++i ) {
1558 if ( part[i] == 0 ) {
1559 tocheck.top().factors.erase(tocheck.top().factors.begin()+i);
1565 else if ( part.size_right() == 1 ) {
1566 if ( part.size_left() == 1 ) {
1567 result *= upoly_to_ex(f1, x) * upoly_to_ex(f2, x);
1571 result *= upoly_to_ex(f2, x);
1572 tocheck.top().poly = f1;
1573 for ( size_t i=0; i<n; ++i ) {
1574 if ( part[i] == 1 ) {
1575 tocheck.top().factors.erase(tocheck.top().factors.begin()+i);
1582 upvec newfactors1(part.size_left()), newfactors2(part.size_right());
1583 upvec::iterator i1 = newfactors1.begin(), i2 = newfactors2.begin();
1584 for ( size_t i=0; i<n; ++i ) {
1586 *i2++ = tocheck.top().factors[i];
1589 *i1++ = tocheck.top().factors[i];
1592 tocheck.top().factors = newfactors1;
1593 tocheck.top().poly = f1;
1595 mf.factors = newfactors2;
1603 if ( !part.next() ) {
1604 // if no more combinations left, return polynomial as
1606 result *= upoly_to_ex(tocheck.top().poly, x);
1614 return unit * cont * result;
1617 /** Second interface to factor_univariate() to be used if the information about
1618 * the prime is not needed.
1620 static inline ex factor_univariate(const ex& poly, const ex& x)
1623 return factor_univariate(poly, x, prime);
1626 /** Represents an evaluation point (<symbol>==<integer>).
1635 ostream& operator<<(ostream& o, const vector<EvalPoint>& v)
1637 for ( size_t i=0; i<v.size(); ++i ) {
1638 o << "(" << v[i].x << "==" << v[i].evalpoint << ") ";
1642 #endif // def DEBUGFACTOR
1644 // forward declaration
1645 static vector<ex> multivar_diophant(const vector<ex>& a_, const ex& x, const ex& c, const vector<EvalPoint>& I, unsigned int d, unsigned int p, unsigned int k);
1647 /** Utility function for multivariate Hensel lifting.
1649 * Solves the equation
1650 * s_1*b_1 + ... + s_r*b_r == 1 mod p^k
1651 * with deg(s_i) < deg(a_i)
1652 * and with given b_1 = a_1 * ... * a_{i-1} * a_{i+1} * ... * a_r
1654 * The implementation follows the algorithm in chapter 6 of [GCL].
1656 * @param[in] a vector of modular univariate polynomials
1657 * @param[in] x symbol
1658 * @param[in] p prime number
1659 * @param[in] k p^k is modulus
1660 * @return vector of polynomials (s_i)
1662 static upvec multiterm_eea_lift(const upvec& a, const ex& x, unsigned int p, unsigned int k)
1664 const size_t r = a.size();
1665 cl_modint_ring R = find_modint_ring(expt_pos(cl_I(p),k));
1668 for ( size_t j=r-2; j>=1; --j ) {
1669 q[j-1] = a[j] * q[j];
1671 umodpoly beta(1, R->one());
1673 for ( size_t j=1; j<r; ++j ) {
1674 vector<ex> mdarg(2);
1675 mdarg[0] = umodpoly_to_ex(q[j-1], x);
1676 mdarg[1] = umodpoly_to_ex(a[j-1], x);
1677 vector<EvalPoint> empty;
1678 vector<ex> exsigma = multivar_diophant(mdarg, x, umodpoly_to_ex(beta, x), empty, 0, p, k);
1680 umodpoly_from_ex(sigma1, exsigma[0], x, R);
1682 umodpoly_from_ex(sigma2, exsigma[1], x, R);
1684 s.push_back(sigma2);
1690 /** Changes the modulus of a modular polynomial. Used by eea_lift().
1692 * @param[in] R new modular ring
1693 * @param[in,out] a polynomial to change (in situ)
1695 static void change_modulus(const cl_modint_ring& R, umodpoly& a)
1697 if ( a.empty() ) return;
1698 cl_modint_ring oldR = a[0].ring();
1699 umodpoly::iterator i = a.begin(), end = a.end();
1700 for ( ; i!=end; ++i ) {
1701 *i = R->canonhom(oldR->retract(*i));
1706 /** Utility function for multivariate Hensel lifting.
1708 * Solves s*a + t*b == 1 mod p^k given a,b.
1710 * The implementation follows the algorithm in chapter 6 of [GCL].
1712 * @param[in] a polynomial
1713 * @param[in] b polynomial
1714 * @param[in] x symbol
1715 * @param[in] p prime number
1716 * @param[in] k p^k is modulus
1717 * @param[out] s_ output polynomial
1718 * @param[out] t_ output polynomial
1720 static void eea_lift(const umodpoly& a, const umodpoly& b, const ex& x, unsigned int p, unsigned int k, umodpoly& s_, umodpoly& t_)
1722 cl_modint_ring R = find_modint_ring(p);
1724 change_modulus(R, amod);
1726 change_modulus(R, bmod);
1730 exteuclid(amod, bmod, smod, tmod);
1732 cl_modint_ring Rpk = find_modint_ring(expt_pos(cl_I(p),k));
1734 change_modulus(Rpk, s);
1736 change_modulus(Rpk, t);
1739 umodpoly one(1, Rpk->one());
1740 for ( size_t j=1; j<k; ++j ) {
1741 umodpoly e = one - a * s - b * t;
1742 reduce_coeff(e, modulus);
1744 change_modulus(R, c);
1745 umodpoly sigmabar = smod * c;
1746 umodpoly taubar = tmod * c;
1748 remdiv(sigmabar, bmod, sigma, q);
1749 umodpoly tau = taubar + q * amod;
1750 umodpoly sadd = sigma;
1751 change_modulus(Rpk, sadd);
1752 cl_MI modmodulus(Rpk, modulus);
1753 s = s + sadd * modmodulus;
1754 umodpoly tadd = tau;
1755 change_modulus(Rpk, tadd);
1756 t = t + tadd * modmodulus;
1757 modulus = modulus * p;
1763 /** Utility function for multivariate Hensel lifting.
1765 * Solves the equation
1766 * s_1*b_1 + ... + s_r*b_r == x^m mod p^k
1767 * with given b_1 = a_1 * ... * a_{i-1} * a_{i+1} * ... * a_r
1769 * The implementation follows the algorithm in chapter 6 of [GCL].
1771 * @param a vector with univariate polynomials mod p^k
1773 * @param m exponent of x^m in the equation to solve
1774 * @param p prime number
1775 * @param k p^k is modulus
1776 * @return vector of polynomials (s_i)
1778 static upvec univar_diophant(const upvec& a, const ex& x, unsigned int m, unsigned int p, unsigned int k)
1780 cl_modint_ring R = find_modint_ring(expt_pos(cl_I(p),k));
1782 const size_t r = a.size();
1785 upvec s = multiterm_eea_lift(a, x, p, k);
1786 for ( size_t j=0; j<r; ++j ) {
1787 umodpoly bmod = umodpoly_to_umodpoly(s[j], R, m);
1789 rem(bmod, a[j], buf);
1790 result.push_back(buf);
1795 eea_lift(a[1], a[0], x, p, k, s, t);
1796 umodpoly bmod = umodpoly_to_umodpoly(s, R, m);
1798 remdiv(bmod, a[0], buf, q);
1799 result.push_back(buf);
1800 umodpoly t1mod = umodpoly_to_umodpoly(t, R, m);
1801 buf = t1mod + q * a[1];
1802 result.push_back(buf);
1808 /** Map used by function make_modular().
1809 * Finds every coefficient in a polynomial and replaces it by is value in the
1810 * given modular ring R (symmetric representation).
1812 struct make_modular_map : public map_function {
1814 make_modular_map(const cl_modint_ring& R_) : R(R_) { }
1815 ex operator()(const ex& e)
1817 if ( is_a<add>(e) || is_a<mul>(e) ) {
1818 return e.map(*this);
1820 else if ( is_a<numeric>(e) ) {
1821 numeric mod(R->modulus);
1822 numeric halfmod = (mod-1)/2;
1823 cl_MI emod = R->canonhom(the<cl_I>(ex_to<numeric>(e).to_cl_N()));
1824 numeric n(R->retract(emod));
1825 if ( n > halfmod ) {
1836 /** Helps mimicking modular multivariate polynomial arithmetic.
1838 * @param e expression of which to make the coefficients equal to their value
1839 * in the modular ring R (symmetric representation)
1840 * @param R modular ring
1841 * @return resulting expression
1843 static ex make_modular(const ex& e, const cl_modint_ring& R)
1845 make_modular_map map(R);
1846 return map(e.expand());
1849 /** Utility function for multivariate Hensel lifting.
1851 * Returns the polynomials s_i that fulfill
1852 * s_1*b_1 + ... + s_r*b_r == c mod <I^(d+1),p^k>
1853 * with given b_1 = a_1 * ... * a_{i-1} * a_{i+1} * ... * a_r
1855 * The implementation follows the algorithm in chapter 6 of [GCL].
1857 * @param a_ vector of multivariate factors mod p^k
1858 * @param x symbol (equiv. x_1 in [GCL])
1859 * @param c polynomial mod p^k
1860 * @param I vector of evaluation points
1861 * @param d maximum total degree of result
1862 * @param p prime number
1863 * @param k p^k is modulus
1864 * @return vector of polynomials (s_i)
1866 static vector<ex> multivar_diophant(const vector<ex>& a_, const ex& x, const ex& c, const vector<EvalPoint>& I,
1867 unsigned int d, unsigned int p, unsigned int k)
1871 const cl_modint_ring R = find_modint_ring(expt_pos(cl_I(p),k));
1872 const size_t r = a.size();
1873 const size_t nu = I.size() + 1;
1877 ex xnu = I.back().x;
1878 int alphanu = I.back().evalpoint;
1881 for ( size_t i=0; i<r; ++i ) {
1885 for ( size_t i=0; i<r; ++i ) {
1886 b[i] = normal(A / a[i]);
1889 vector<ex> anew = a;
1890 for ( size_t i=0; i<r; ++i ) {
1891 anew[i] = anew[i].subs(xnu == alphanu);
1893 ex cnew = c.subs(xnu == alphanu);
1894 vector<EvalPoint> Inew = I;
1896 sigma = multivar_diophant(anew, x, cnew, Inew, d, p, k);
1899 for ( size_t i=0; i<r; ++i ) {
1900 buf -= sigma[i] * b[i];
1902 ex e = make_modular(buf, R);
1905 for ( size_t m=1; !e.is_zero() && e.has(xnu) && m<=d; ++m ) {
1906 monomial *= (xnu - alphanu);
1907 monomial = expand(monomial);
1908 ex cm = e.diff(ex_to<symbol>(xnu), m).subs(xnu==alphanu) / factorial(m);
1909 cm = make_modular(cm, R);
1910 if ( !cm.is_zero() ) {
1911 vector<ex> delta_s = multivar_diophant(anew, x, cm, Inew, d, p, k);
1913 for ( size_t j=0; j<delta_s.size(); ++j ) {
1914 delta_s[j] *= monomial;
1915 sigma[j] += delta_s[j];
1916 buf -= delta_s[j] * b[j];
1918 e = make_modular(buf, R);
1924 for ( size_t i=0; i<a.size(); ++i ) {
1926 umodpoly_from_ex(up, a[i], x, R);
1930 sigma.insert(sigma.begin(), r, 0);
1933 if ( is_a<add>(c) ) {
1941 for ( size_t i=0; i<nterms; ++i ) {
1942 int m = z.degree(x);
1943 cl_I cm = the<cl_I>(ex_to<numeric>(z.lcoeff(x)).to_cl_N());
1944 upvec delta_s = univar_diophant(amod, x, m, p, k);
1947 while ( poscm < 0 ) {
1948 poscm = poscm + expt_pos(cl_I(p),k);
1950 modcm = cl_MI(R, poscm);
1951 for ( size_t j=0; j<delta_s.size(); ++j ) {
1952 delta_s[j] = delta_s[j] * modcm;
1953 sigma[j] = sigma[j] + umodpoly_to_ex(delta_s[j], x);
1961 for ( size_t i=0; i<sigma.size(); ++i ) {
1962 sigma[i] = make_modular(sigma[i], R);
1968 /** Multivariate Hensel lifting.
1969 * The implementation follows the algorithm in chapter 6 of [GCL].
1970 * Since we don't have a data type for modular multivariate polynomials, the
1971 * respective operations are done in a GiNaC::ex and the function
1972 * make_modular() is then called to make the coefficient modular p^l.
1974 * @param a multivariate polynomial primitive in x
1975 * @param x symbol (equiv. x_1 in [GCL])
1976 * @param I vector of evaluation points (x_2==a_2,x_3==a_3,...)
1977 * @param p prime number (should not divide lcoeff(a mod I))
1978 * @param l p^l is the modulus of the lifted univariate field
1979 * @param u vector of modular (mod p^l) factors of a mod I
1980 * @param lcU correct leading coefficient of the univariate factors of a mod I
1981 * @return list GiNaC::lst with lifted factors (multivariate factors of a),
1982 * empty if Hensel lifting did not succeed
1984 static ex hensel_multivar(const ex& a, const ex& x, const vector<EvalPoint>& I,
1985 unsigned int p, const cl_I& l, const upvec& u, const vector<ex>& lcU)
1987 const size_t nu = I.size() + 1;
1988 const cl_modint_ring R = find_modint_ring(expt_pos(cl_I(p),l));
1993 for ( size_t j=nu; j>=2; --j ) {
1995 int alpha = I[j-2].evalpoint;
1996 A[j-2] = A[j-1].subs(x==alpha);
1997 A[j-2] = make_modular(A[j-2], R);
2000 int maxdeg = a.degree(I.front().x);
2001 for ( size_t i=1; i<I.size(); ++i ) {
2002 int maxdeg2 = a.degree(I[i].x);
2003 if ( maxdeg2 > maxdeg ) maxdeg = maxdeg2;
2006 const size_t n = u.size();
2008 for ( size_t i=0; i<n; ++i ) {
2009 U[i] = umodpoly_to_ex(u[i], x);
2012 for ( size_t j=2; j<=nu; ++j ) {
2015 for ( size_t m=0; m<n; ++m) {
2016 if ( lcU[m] != 1 ) {
2018 for ( size_t i=j-1; i<nu-1; ++i ) {
2019 coef = coef.subs(I[i].x == I[i].evalpoint);
2021 coef = make_modular(coef, R);
2022 int deg = U[m].degree(x);
2023 U[m] = U[m] - U[m].lcoeff(x) * pow(x,deg) + coef * pow(x,deg);
2027 for ( size_t i=0; i<n; ++i ) {
2030 ex e = expand(A[j-1] - Uprod);
2032 vector<EvalPoint> newI;
2033 for ( size_t i=1; i<=j-2; ++i ) {
2034 newI.push_back(I[i-1]);
2038 int alphaj = I[j-2].evalpoint;
2039 size_t deg = A[j-1].degree(xj);
2040 for ( size_t k=1; k<=deg; ++k ) {
2041 if ( !e.is_zero() ) {
2042 monomial *= (xj - alphaj);
2043 monomial = expand(monomial);
2044 ex dif = e.diff(ex_to<symbol>(xj), k);
2045 ex c = dif.subs(xj==alphaj) / factorial(k);
2046 if ( !c.is_zero() ) {
2047 vector<ex> deltaU = multivar_diophant(U1, x, c, newI, maxdeg, p, cl_I_to_uint(l));
2048 for ( size_t i=0; i<n; ++i ) {
2049 deltaU[i] *= monomial;
2051 U[i] = make_modular(U[i], R);
2054 for ( size_t i=0; i<n; ++i ) {
2058 e = make_modular(e, R);
2065 for ( size_t i=0; i<U.size(); ++i ) {
2068 if ( expand(a-acand).is_zero() ) {
2070 for ( size_t i=0; i<U.size(); ++i ) {
2081 /** Takes a factorized expression and puts the factors in a lst. The exponents
2082 * of the factors are discarded, e.g. 7*x^2*(y+1)^4 --> {7,x,y+1}. The first
2083 * element of the list is always the numeric coefficient.
2085 static ex put_factors_into_lst(const ex& e)
2088 if ( is_a<numeric>(e) ) {
2092 if ( is_a<power>(e) ) {
2094 result.append(e.op(0));
2097 if ( is_a<symbol>(e) || is_a<add>(e) ) {
2102 if ( is_a<mul>(e) ) {
2104 for ( size_t i=0; i<e.nops(); ++i ) {
2106 if ( is_a<numeric>(op) ) {
2109 if ( is_a<power>(op) ) {
2110 result.append(op.op(0));
2112 if ( is_a<symbol>(op) || is_a<add>(op) ) {
2116 result.prepend(nfac);
2119 throw runtime_error("put_factors_into_lst: bad term.");
2122 /** Checks a set of numbers for whether each number has a unique prime factor.
2124 * @param[in] f list of numbers to check
2125 * @return true: if number set is bad, false: if set is okay (has unique
2128 static bool checkdivisors(const lst& f)
2130 const int k = f.nops();
2132 vector<numeric> d(k);
2133 d[0] = ex_to<numeric>(abs(f.op(0)));
2134 for ( int i=1; i<k; ++i ) {
2135 q = ex_to<numeric>(abs(f.op(i)));
2136 for ( int j=i-1; j>=0; --j ) {
2151 /** Generates a set of evaluation points for a multivariate polynomial.
2152 * The set fulfills the following conditions:
2153 * 1. lcoeff(evaluated_polynomial) does not vanish
2154 * 2. factors of lcoeff(evaluated_polynomial) have each a unique prime factor
2155 * 3. evaluated_polynomial is square free
2156 * See [Wan] for more details.
2158 * @param[in] u multivariate polynomial to be factored
2159 * @param[in] vn leading coefficient of u in x (x==first symbol in syms)
2160 * @param[in] syms set of symbols that appear in u
2161 * @param[in] f lst containing the factors of the leading coefficient vn
2162 * @param[in,out] modulus integer modulus for random number generation (i.e. |a_i| < modulus)
2163 * @param[out] u0 returns the evaluated (univariate) polynomial
2164 * @param[out] a returns the valid evaluation points. must have initial size equal
2165 * number of symbols-1 before calling generate_set
2167 static void generate_set(const ex& u, const ex& vn, const exset& syms, const lst& f,
2168 numeric& modulus, ex& u0, vector<numeric>& a)
2170 const ex& x = *syms.begin();
2173 // generate a set of integers ...
2177 exset::const_iterator s = syms.begin();
2179 for ( size_t i=0; i<a.size(); ++i ) {
2181 a[i] = mod(numeric(rand()), 2*modulus) - modulus;
2182 vnatry = vna.subs(*s == a[i]);
2183 // ... for which the leading coefficient doesn't vanish ...
2184 } while ( vnatry == 0 );
2186 u0 = u0.subs(*s == a[i]);
2189 // ... for which u0 is square free ...
2190 ex g = gcd(u0, u0.diff(ex_to<symbol>(x)));
2191 if ( !is_a<numeric>(g) ) {
2194 if ( !is_a<numeric>(vn) ) {
2195 // ... and for which the evaluated factors have each an unique prime factor
2197 fnum.let_op(0) = fnum.op(0) * u0.content(x);
2198 for ( size_t i=1; i<fnum.nops(); ++i ) {
2199 if ( !is_a<numeric>(fnum.op(i)) ) {
2202 for ( size_t j=0; j<a.size(); ++j, ++s ) {
2203 fnum.let_op(i) = fnum.op(i).subs(*s == a[j]);
2207 if ( checkdivisors(fnum) ) {
2211 // ok, we have a valid set now
2216 // forward declaration
2217 static ex factor_sqrfree(const ex& poly);
2219 /** Multivariate factorization.
2221 * The implementation is based on the algorithm described in [Wan].
2222 * An evaluation homomorphism (a set of integers) is determined that fulfills
2223 * certain criteria. The evaluated polynomial is univariate and is factorized
2224 * by factor_univariate(). The main work then is to find the correct leading
2225 * coefficients of the univariate factors. They have to correspond to the
2226 * factors of the (multivariate) leading coefficient of the input polynomial
2227 * (as defined for a specific variable x). After that the Hensel lifting can be
2230 * @param[in] poly expanded, square free polynomial
2231 * @param[in] syms contains the symbols in the polynomial
2232 * @return factorized polynomial
2234 static ex factor_multivariate(const ex& poly, const exset& syms)
2236 exset::const_iterator s;
2237 const ex& x = *syms.begin();
2239 // make polynomial primitive
2240 ex p = poly.collect(x);
2241 ex cont = p.lcoeff(x);
2242 for ( int i=p.degree(x)-1; i>=p.ldegree(x); --i ) {
2243 cont = gcd(cont, p.coeff(x,i));
2244 if ( cont == 1 ) break;
2246 ex pp = expand(normal(p / cont));
2247 if ( !is_a<numeric>(cont) ) {
2248 return factor_sqrfree(cont) * factor_sqrfree(pp);
2251 // factor leading coefficient
2252 ex vn = pp.collect(x).lcoeff(x);
2254 if ( is_a<numeric>(vn) ) {
2258 ex vnfactors = factor(vn);
2259 vnlst = put_factors_into_lst(vnfactors);
2262 const unsigned int maxtrials = 3;
2263 numeric modulus = (vnlst.nops() > 3) ? vnlst.nops() : 3;
2264 vector<numeric> a(syms.size()-1, 0);
2266 // try now to factorize until we are successful
2269 unsigned int trialcount = 0;
2271 int factor_count = 0;
2272 int min_factor_count = -1;
2276 // try several evaluation points to reduce the number of factors
2277 while ( trialcount < maxtrials ) {
2279 // generate a set of valid evaluation points
2280 generate_set(pp, vn, syms, ex_to<lst>(vnlst), modulus, u, a);
2282 ufac = factor_univariate(u, x, prime);
2283 ufaclst = put_factors_into_lst(ufac);
2284 factor_count = ufaclst.nops()-1;
2285 delta = ufaclst.op(0);
2287 if ( factor_count <= 1 ) {
2291 if ( min_factor_count < 0 ) {
2293 min_factor_count = factor_count;
2295 else if ( min_factor_count == factor_count ) {
2299 else if ( min_factor_count > factor_count ) {
2300 // new minimum, reset trial counter
2301 min_factor_count = factor_count;
2306 // determine true leading coefficients for the Hensel lifting
2307 vector<ex> C(factor_count);
2308 if ( is_a<numeric>(vn) ) {
2310 for ( size_t i=1; i<ufaclst.nops(); ++i ) {
2311 C[i-1] = ufaclst.op(i).lcoeff(x);
2316 // we use the property of the ftilde having a unique prime factor.
2317 // details can be found in [Wan].
2319 vector<numeric> ftilde(vnlst.nops()-1);
2320 for ( size_t i=0; i<ftilde.size(); ++i ) {
2321 ex ft = vnlst.op(i+1);
2324 for ( size_t j=0; j<a.size(); ++j ) {
2325 ft = ft.subs(*s == a[j]);
2328 ftilde[i] = ex_to<numeric>(ft);
2330 // calculate D and C
2331 vector<bool> used_flag(ftilde.size(), false);
2332 vector<ex> D(factor_count, 1);
2334 for ( int i=0; i<factor_count; ++i ) {
2335 numeric prefac = ex_to<numeric>(ufaclst.op(i+1).lcoeff(x));
2336 for ( int j=ftilde.size()-1; j>=0; --j ) {
2338 while ( irem(prefac, ftilde[j]) == 0 ) {
2339 prefac = iquo(prefac, ftilde[j]);
2343 used_flag[j] = true;
2344 D[i] = D[i] * pow(vnlst.op(j+1), count);
2347 C[i] = D[i] * prefac;
2351 for ( int i=0; i<factor_count; ++i ) {
2352 numeric prefac = ex_to<numeric>(ufaclst.op(i+1).lcoeff(x));
2353 for ( int j=ftilde.size()-1; j>=0; --j ) {
2355 while ( irem(prefac, ftilde[j]) == 0 ) {
2356 prefac = iquo(prefac, ftilde[j]);
2359 while ( irem(ex_to<numeric>(delta)*prefac, ftilde[j]) == 0 ) {
2360 numeric g = gcd(prefac, ex_to<numeric>(ftilde[j]));
2361 prefac = iquo(prefac, g);
2362 delta = delta / (ftilde[j]/g);
2363 ufaclst.let_op(i+1) = ufaclst.op(i+1) * (ftilde[j]/g);
2367 used_flag[j] = true;
2368 D[i] = D[i] * pow(vnlst.op(j+1), count);
2371 C[i] = D[i] * prefac;
2374 // check if something went wrong
2375 bool some_factor_unused = false;
2376 for ( size_t i=0; i<used_flag.size(); ++i ) {
2377 if ( !used_flag[i] ) {
2378 some_factor_unused = true;
2382 if ( some_factor_unused ) {
2387 // multiply the remaining content of the univariate polynomial into the
2390 C[0] = C[0] * delta;
2391 ufaclst.let_op(1) = ufaclst.op(1) * delta;
2394 // set up evaluation points
2396 vector<EvalPoint> epv;
2399 for ( size_t i=0; i<a.size(); ++i ) {
2401 ep.evalpoint = a[i].to_int();
2407 for ( int i=1; i<=factor_count; ++i ) {
2408 if ( ufaclst.op(i).degree(x) > maxdeg ) {
2409 maxdeg = ufaclst[i].degree(x);
2412 cl_I B = 2*calc_bound(u, x, maxdeg);
2420 // set up modular factors (mod p^l)
2421 cl_modint_ring R = find_modint_ring(expt_pos(cl_I(prime),l));
2422 upvec modfactors(ufaclst.nops()-1);
2423 for ( size_t i=1; i<ufaclst.nops(); ++i ) {
2424 umodpoly_from_ex(modfactors[i-1], ufaclst.op(i), x, R);
2427 // try Hensel lifting
2428 ex res = hensel_multivar(pp, x, epv, prime, l, modfactors, C);
2429 if ( res != lst() ) {
2431 for ( size_t i=0; i<res.nops(); ++i ) {
2432 result *= res.op(i).content(x) * res.op(i).unit(x);
2433 result *= res.op(i).primpart(x);
2440 /** Finds all symbols in an expression. Used by factor_sqrfree() and factor().
2442 struct find_symbols_map : public map_function {
2444 ex operator()(const ex& e)
2446 if ( is_a<symbol>(e) ) {
2450 return e.map(*this);
2454 /** Factorizes a polynomial that is square free. It calls either the univariate
2455 * or the multivariate factorization functions.
2457 static ex factor_sqrfree(const ex& poly)
2459 // determine all symbols in poly
2460 find_symbols_map findsymbols;
2462 if ( findsymbols.syms.size() == 0 ) {
2466 if ( findsymbols.syms.size() == 1 ) {
2468 const ex& x = *(findsymbols.syms.begin());
2469 if ( poly.ldegree(x) > 0 ) {
2470 // pull out direct factors
2471 int ld = poly.ldegree(x);
2472 ex res = factor_univariate(expand(poly/pow(x, ld)), x);
2473 return res * pow(x,ld);
2476 ex res = factor_univariate(poly, x);
2481 // multivariate case
2482 ex res = factor_multivariate(poly, findsymbols.syms);
2486 /** Map used by factor() when factor_options::all is given to access all
2487 * subexpressions and to call factor() on them.
2489 struct apply_factor_map : public map_function {
2491 apply_factor_map(unsigned options_) : options(options_) { }
2492 ex operator()(const ex& e)
2494 if ( e.info(info_flags::polynomial) ) {
2495 return factor(e, options);
2497 if ( is_a<add>(e) ) {
2499 for ( size_t i=0; i<e.nops(); ++i ) {
2500 if ( e.op(i).info(info_flags::polynomial) ) {
2509 return factor(s1, options) + s2.map(*this);
2511 return e.map(*this);
2515 } // anonymous namespace
2517 /** Interface function to the outside world. It checks the arguments, tries a
2518 * square free factorization, and then calls factor_sqrfree to do the hard
2521 ex factor(const ex& poly, unsigned options)
2524 if ( !poly.info(info_flags::polynomial) ) {
2525 if ( options & factor_options::all ) {
2526 options &= ~factor_options::all;
2527 apply_factor_map factor_map(options);
2528 return factor_map(poly);
2533 // determine all symbols in poly
2534 find_symbols_map findsymbols;
2536 if ( findsymbols.syms.size() == 0 ) {
2540 exset::const_iterator i=findsymbols.syms.begin(), end=findsymbols.syms.end();
2541 for ( ; i!=end; ++i ) {
2545 // make poly square free
2546 ex sfpoly = sqrfree(poly.expand(), syms);
2548 // factorize the square free components
2549 if ( is_a<power>(sfpoly) ) {
2550 // case: (polynomial)^exponent
2551 const ex& base = sfpoly.op(0);
2552 if ( !is_a<add>(base) ) {
2553 // simple case: (monomial)^exponent
2556 ex f = factor_sqrfree(base);
2557 return pow(f, sfpoly.op(1));
2559 if ( is_a<mul>(sfpoly) ) {
2560 // case: multiple factors
2562 for ( size_t i=0; i<sfpoly.nops(); ++i ) {
2563 const ex& t = sfpoly.op(i);
2564 if ( is_a<power>(t) ) {
2565 const ex& base = t.op(0);
2566 if ( !is_a<add>(base) ) {
2570 ex f = factor_sqrfree(base);
2571 res *= pow(f, t.op(1));
2574 else if ( is_a<add>(t) ) {
2575 ex f = factor_sqrfree(t);
2584 if ( is_a<symbol>(sfpoly) ) {
2587 // case: (polynomial)
2588 ex f = factor_sqrfree(sfpoly);
2592 } // namespace GiNaC