]> www.ginac.de Git - ginac.git/blob - ginac/factor.cpp
Update copyright notice.
[ginac.git] / ginac / factor.cpp
1 /** @file factor.cpp
2  *
3  *  Polynomial factorization (implementation).
4  *
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.
8  *
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.
12  *
13  *  Univariate factorization does a modular factorization via Berlekamp's
14  *  algorithm and distinct degree factorization. Hensel lifting is used at the
15  *  end.
16  *  
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.
21  *
22  *  Algorithms used can be found in
23  *    [Wan] An Improved Multivariate Polynomial Factoring Algorithm,
24  *          P.S.Wang,
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,
30  *          M.Mignotte, 
31  *          In "Computer Algebra, Symbolic and Algebraic Computation" (B.Buchberger et al., eds.),
32  *          pp. 259-263, Springer-Verlag, New York, 1982.
33  */
34
35 /*
36  *  GiNaC Copyright (C) 1999-2010 Johannes Gutenberg University Mainz, Germany
37  *
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.
42  *
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.
47  *
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
51  */
52
53 //#define DEBUGFACTOR
54
55 #include "factor.h"
56
57 #include "ex.h"
58 #include "numeric.h"
59 #include "operators.h"
60 #include "inifcns.h"
61 #include "symbol.h"
62 #include "relational.h"
63 #include "power.h"
64 #include "mul.h"
65 #include "normal.h"
66 #include "add.h"
67
68 #include <algorithm>
69 #include <cmath>
70 #include <limits>
71 #include <list>
72 #include <vector>
73 #ifdef DEBUGFACTOR
74 #include <ostream>
75 #endif
76 using namespace std;
77
78 #include <cln/cln.h>
79 using namespace cln;
80
81 namespace GiNaC {
82
83 #ifdef DEBUGFACTOR
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)
88 {
89         vector<int>::const_iterator i = v.begin(), end = v.end();
90         while ( i != end ) {
91                 o << *i++ << " ";
92         }
93         return o;
94 }
95 static ostream& operator<<(ostream& o, const vector<cl_I>& v)
96 {
97         vector<cl_I>::const_iterator i = v.begin(), end = v.end();
98         while ( i != end ) {
99                 o << *i << "[" << i-v.begin() << "]" << " ";
100                 ++i;
101         }
102         return o;
103 }
104 static ostream& operator<<(ostream& o, const vector<cl_MI>& v)
105 {
106         vector<cl_MI>::const_iterator i = v.begin(), end = v.end();
107         while ( i != end ) {
108                 o << *i << "[" << i-v.begin() << "]" << " ";
109                 ++i;
110         }
111         return o;
112 }
113 ostream& operator<<(ostream& o, const vector<numeric>& v)
114 {
115         for ( size_t i=0; i<v.size(); ++i ) {
116                 o << v[i] << " ";
117         }
118         return o;
119 }
120 ostream& operator<<(ostream& o, const vector< vector<cl_MI> >& v)
121 {
122         vector< vector<cl_MI> >::const_iterator i = v.begin(), end = v.end();
123         while ( i != end ) {
124                 o << i-v.begin() << ": " << *i << endl;
125                 ++i;
126         }
127         return o;
128 }
129 #else
130 #define DCOUT(str)
131 #define DCOUTVAR(var)
132 #define DCOUT2(str,var)
133 #endif // def DEBUGFACTOR
134
135 // anonymous namespace to hide all utility functions
136 namespace {
137
138 ////////////////////////////////////////////////////////////////////////////////
139 // modular univariate polynomial code
140
141 typedef std::vector<cln::cl_MI> umodpoly;
142 typedef std::vector<cln::cl_I> upoly;
143 typedef vector<umodpoly> upvec;
144
145 // COPY FROM UPOLY.HPP
146
147 // CHANGED size_t -> int !!!
148 template<typename T> static int degree(const T& p)
149 {
150         return p.size() - 1;
151 }
152
153 template<typename T> static typename T::value_type lcoeff(const T& p)
154 {
155         return p[p.size() - 1];
156 }
157
158 static bool normalize_in_field(umodpoly& a)
159 {
160         if (a.size() == 0)
161                 return true;
162         if ( lcoeff(a) == a[0].ring()->one() ) {
163                 return true;
164         }
165
166         const cln::cl_MI lc_1 = recip(lcoeff(a));
167         for (std::size_t k = a.size(); k-- != 0; )
168                 a[k] = a[k]*lc_1;
169         return false;
170 }
171
172 template<typename T> static void
173 canonicalize(T& p, const typename T::size_type hint = std::numeric_limits<typename T::size_type>::max())
174 {
175         if (p.empty())
176                 return;
177
178         std::size_t i = p.size() - 1;
179         // Be fast if the polynomial is already canonicalized
180         if (!zerop(p[i]))
181                 return;
182
183         if (hint < p.size())
184                 i = hint;
185
186         bool is_zero = false;
187         do {
188                 if (!zerop(p[i])) {
189                         ++i;
190                         break;
191                 }
192                 if (i == 0) {
193                         is_zero = true;
194                         break;
195                 }
196                 --i;
197         } while (true);
198
199         if (is_zero) {
200                 p.clear();
201                 return;
202         }
203
204         p.erase(p.begin() + i, p.end());
205 }
206
207 // END COPY FROM UPOLY.HPP
208
209 static void expt_pos(umodpoly& a, unsigned int q)
210 {
211         if ( a.empty() ) return;
212         cl_MI zero = a[0].ring()->zero(); 
213         int deg = degree(a);
214         a.resize(degree(a)*q+1, zero);
215         for ( int i=deg; i>0; --i ) {
216                 a[i*q] = a[i];
217                 a[i] = zero;
218         }
219 }
220
221 template<bool COND, typename T = void> struct enable_if
222 {
223         typedef T type;
224 };
225
226 template<typename T> struct enable_if<false, T> { /* empty */ };
227
228 template<typename T> struct uvar_poly_p
229 {
230         static const bool value = false;
231 };
232
233 template<> struct uvar_poly_p<upoly>
234 {
235         static const bool value = true;
236 };
237
238 template<> struct uvar_poly_p<umodpoly>
239 {
240         static const bool value = true;
241 };
242
243 template<typename T>
244 // Don't define this for anything but univariate polynomials.
245 static typename enable_if<uvar_poly_p<T>::value, T>::type
246 operator+(const T& a, const T& b)
247 {
248         int sa = a.size();
249         int sb = b.size();
250         if ( sa >= sb ) {
251                 T r(sa);
252                 int i = 0;
253                 for ( ; i<sb; ++i ) {
254                         r[i] = a[i] + b[i];
255                 }
256                 for ( ; i<sa; ++i ) {
257                         r[i] = a[i];
258                 }
259                 canonicalize(r);
260                 return r;
261         }
262         else {
263                 T r(sb);
264                 int i = 0;
265                 for ( ; i<sa; ++i ) {
266                         r[i] = a[i] + b[i];
267                 }
268                 for ( ; i<sb; ++i ) {
269                         r[i] = b[i];
270                 }
271                 canonicalize(r);
272                 return r;
273         }
274 }
275
276 template<typename T>
277 // Don't define this for anything but univariate polynomials. Otherwise
278 // overload resolution might fail (this actually happens when compiling
279 // GiNaC with g++ 3.4).
280 static typename enable_if<uvar_poly_p<T>::value, T>::type
281 operator-(const T& a, const T& b)
282 {
283         int sa = a.size();
284         int sb = b.size();
285         if ( sa >= sb ) {
286                 T r(sa);
287                 int i = 0;
288                 for ( ; i<sb; ++i ) {
289                         r[i] = a[i] - b[i];
290                 }
291                 for ( ; i<sa; ++i ) {
292                         r[i] = a[i];
293                 }
294                 canonicalize(r);
295                 return r;
296         }
297         else {
298                 T r(sb);
299                 int i = 0;
300                 for ( ; i<sa; ++i ) {
301                         r[i] = a[i] - b[i];
302                 }
303                 for ( ; i<sb; ++i ) {
304                         r[i] = -b[i];
305                 }
306                 canonicalize(r);
307                 return r;
308         }
309 }
310
311 static upoly operator*(const upoly& a, const upoly& b)
312 {
313         upoly c;
314         if ( a.empty() || b.empty() ) return c;
315
316         int n = degree(a) + degree(b);
317         c.resize(n+1, 0);
318         for ( int i=0 ; i<=n; ++i ) {
319                 for ( int j=0 ; j<=i; ++j ) {
320                         if ( j > degree(a) || (i-j) > degree(b) ) continue;
321                         c[i] = c[i] + a[j] * b[i-j];
322                 }
323         }
324         canonicalize(c);
325         return c;
326 }
327
328 static umodpoly operator*(const umodpoly& a, const umodpoly& b)
329 {
330         umodpoly c;
331         if ( a.empty() || b.empty() ) return c;
332
333         int n = degree(a) + degree(b);
334         c.resize(n+1, a[0].ring()->zero());
335         for ( int i=0 ; i<=n; ++i ) {
336                 for ( int j=0 ; j<=i; ++j ) {
337                         if ( j > degree(a) || (i-j) > degree(b) ) continue;
338                         c[i] = c[i] + a[j] * b[i-j];
339                 }
340         }
341         canonicalize(c);
342         return c;
343 }
344
345 static upoly operator*(const upoly& a, const cl_I& x)
346 {
347         if ( zerop(x) ) {
348                 upoly r;
349                 return r;
350         }
351         upoly r(a.size());
352         for ( size_t i=0; i<a.size(); ++i ) {
353                 r[i] = a[i] * x;
354         }
355         return r;
356 }
357
358 static upoly operator/(const upoly& a, const cl_I& x)
359 {
360         if ( zerop(x) ) {
361                 upoly r;
362                 return r;
363         }
364         upoly r(a.size());
365         for ( size_t i=0; i<a.size(); ++i ) {
366                 r[i] = exquo(a[i],x);
367         }
368         return r;
369 }
370
371 static umodpoly operator*(const umodpoly& a, const cl_MI& x)
372 {
373         umodpoly r(a.size());
374         for ( size_t i=0; i<a.size(); ++i ) {
375                 r[i] = a[i] * x;
376         }
377         canonicalize(r);
378         return r;
379 }
380
381 static void upoly_from_ex(upoly& up, const ex& e, const ex& x)
382 {
383         // assert: e is in Z[x]
384         int deg = e.degree(x);
385         up.resize(deg+1);
386         int ldeg = e.ldegree(x);
387         for ( ; deg>=ldeg; --deg ) {
388                 up[deg] = the<cl_I>(ex_to<numeric>(e.coeff(x, deg)).to_cl_N());
389         }
390         for ( ; deg>=0; --deg ) {
391                 up[deg] = 0;
392         }
393         canonicalize(up);
394 }
395
396 static void umodpoly_from_upoly(umodpoly& ump, const upoly& e, const cl_modint_ring& R)
397 {
398         int deg = degree(e);
399         ump.resize(deg+1);
400         for ( ; deg>=0; --deg ) {
401                 ump[deg] = R->canonhom(e[deg]);
402         }
403         canonicalize(ump);
404 }
405
406 static void umodpoly_from_ex(umodpoly& ump, const ex& e, const ex& x, const cl_modint_ring& R)
407 {
408         // assert: e is in Z[x]
409         int deg = e.degree(x);
410         ump.resize(deg+1);
411         int ldeg = e.ldegree(x);
412         for ( ; deg>=ldeg; --deg ) {
413                 cl_I coeff = the<cl_I>(ex_to<numeric>(e.coeff(x, deg)).to_cl_N());
414                 ump[deg] = R->canonhom(coeff);
415         }
416         for ( ; deg>=0; --deg ) {
417                 ump[deg] = R->zero();
418         }
419         canonicalize(ump);
420 }
421
422 #ifdef DEBUGFACTOR
423 static void umodpoly_from_ex(umodpoly& ump, const ex& e, const ex& x, const cl_I& modulus)
424 {
425         umodpoly_from_ex(ump, e, x, find_modint_ring(modulus));
426 }
427 #endif
428
429 static ex upoly_to_ex(const upoly& a, const ex& x)
430 {
431         if ( a.empty() ) return 0;
432         ex e;
433         for ( int i=degree(a); i>=0; --i ) {
434                 e += numeric(a[i]) * pow(x, i);
435         }
436         return e;
437 }
438
439 static ex umodpoly_to_ex(const umodpoly& a, const ex& x)
440 {
441         if ( a.empty() ) return 0;
442         cl_modint_ring R = a[0].ring();
443         cl_I mod = R->modulus;
444         cl_I halfmod = (mod-1) >> 1;
445         ex e;
446         for ( int i=degree(a); i>=0; --i ) {
447                 cl_I n = R->retract(a[i]);
448                 if ( n > halfmod ) {
449                         e += numeric(n-mod) * pow(x, i);
450                 } else {
451                         e += numeric(n) * pow(x, i);
452                 }
453         }
454         return e;
455 }
456
457 static upoly umodpoly_to_upoly(const umodpoly& a)
458 {
459         upoly e(a.size());
460         if ( a.empty() ) return e;
461         cl_modint_ring R = a[0].ring();
462         cl_I mod = R->modulus;
463         cl_I halfmod = (mod-1) >> 1;
464         for ( int i=degree(a); i>=0; --i ) {
465                 cl_I n = R->retract(a[i]);
466                 if ( n > halfmod ) {
467                         e[i] = n-mod;
468                 } else {
469                         e[i] = n;
470                 }
471         }
472         return e;
473 }
474
475 static umodpoly umodpoly_to_umodpoly(const umodpoly& a, const cl_modint_ring& R, unsigned int m)
476 {
477         umodpoly e;
478         if ( a.empty() ) return e;
479         cl_modint_ring oldR = a[0].ring();
480         size_t sa = a.size();
481         e.resize(sa+m, R->zero());
482         for ( size_t i=0; i<sa; ++i ) {
483                 e[i+m] = R->canonhom(oldR->retract(a[i]));
484         }
485         canonicalize(e);
486         return e;
487 }
488
489 /** Divides all coefficients of the polynomial a by the integer x.
490  *  All coefficients are supposed to be divisible by x. If they are not, the
491  *  the<cl_I> cast will raise an exception.
492  *
493  *  @param[in,out] a  polynomial of which the coefficients will be reduced by x
494  *  @param[in]     x  integer that divides the coefficients
495  */
496 static void reduce_coeff(umodpoly& a, const cl_I& x)
497 {
498         if ( a.empty() ) return;
499
500         cl_modint_ring R = a[0].ring();
501         umodpoly::iterator i = a.begin(), end = a.end();
502         for ( ; i!=end; ++i ) {
503                 // cln cannot perform this division in the modular field
504                 cl_I c = R->retract(*i);
505                 *i = cl_MI(R, the<cl_I>(c / x));
506         }
507 }
508
509 /** Calculates remainder of a/b.
510  *  Assertion: a and b not empty.
511  *
512  *  @param[in]  a  polynomial dividend
513  *  @param[in]  b  polynomial divisor
514  *  @param[out] r  polynomial remainder
515  */
516 static void rem(const umodpoly& a, const umodpoly& b, umodpoly& r)
517 {
518         int k, n;
519         n = degree(b);
520         k = degree(a) - n;
521         r = a;
522         if ( k < 0 ) return;
523
524         do {
525                 cl_MI qk = div(r[n+k], b[n]);
526                 if ( !zerop(qk) ) {
527                         for ( int i=0; i<n; ++i ) {
528                                 unsigned int j = n + k - 1 - i;
529                                 r[j] = r[j] - qk * b[j-k];
530                         }
531                 }
532         } while ( k-- );
533
534         fill(r.begin()+n, r.end(), a[0].ring()->zero());
535         canonicalize(r);
536 }
537
538 /** Calculates quotient of a/b.
539  *  Assertion: a and b not empty.
540  *
541  *  @param[in]  a  polynomial dividend
542  *  @param[in]  b  polynomial divisor
543  *  @param[out] q  polynomial quotient
544  */
545 static void div(const umodpoly& a, const umodpoly& b, umodpoly& q)
546 {
547         int k, n;
548         n = degree(b);
549         k = degree(a) - n;
550         q.clear();
551         if ( k < 0 ) return;
552
553         umodpoly r = a;
554         q.resize(k+1, a[0].ring()->zero());
555         do {
556                 cl_MI qk = div(r[n+k], b[n]);
557                 if ( !zerop(qk) ) {
558                         q[k] = qk;
559                         for ( int i=0; i<n; ++i ) {
560                                 unsigned int j = n + k - 1 - i;
561                                 r[j] = r[j] - qk * b[j-k];
562                         }
563                 }
564         } while ( k-- );
565
566         canonicalize(q);
567 }
568
569 /** Calculates quotient and remainder of a/b.
570  *  Assertion: a and b not empty.
571  *
572  *  @param[in]  a  polynomial dividend
573  *  @param[in]  b  polynomial divisor
574  *  @param[out] r  polynomial remainder
575  *  @param[out] q  polynomial quotient
576  */
577 static void remdiv(const umodpoly& a, const umodpoly& b, umodpoly& r, umodpoly& q)
578 {
579         int k, n;
580         n = degree(b);
581         k = degree(a) - n;
582         q.clear();
583         r = a;
584         if ( k < 0 ) return;
585
586         q.resize(k+1, a[0].ring()->zero());
587         do {
588                 cl_MI qk = div(r[n+k], b[n]);
589                 if ( !zerop(qk) ) {
590                         q[k] = qk;
591                         for ( int i=0; i<n; ++i ) {
592                                 unsigned int j = n + k - 1 - i;
593                                 r[j] = r[j] - qk * b[j-k];
594                         }
595                 }
596         } while ( k-- );
597
598         fill(r.begin()+n, r.end(), a[0].ring()->zero());
599         canonicalize(r);
600         canonicalize(q);
601 }
602
603 /** Calculates the GCD of polynomial a and b.
604  *
605  *  @param[in]  a  polynomial
606  *  @param[in]  b  polynomial
607  *  @param[out] c  GCD
608  */
609 static void gcd(const umodpoly& a, const umodpoly& b, umodpoly& c)
610 {
611         if ( degree(a) < degree(b) ) return gcd(b, a, c);
612
613         c = a;
614         normalize_in_field(c);
615         umodpoly d = b;
616         normalize_in_field(d);
617         umodpoly r;
618         while ( !d.empty() ) {
619                 rem(c, d, r);
620                 c = d;
621                 d = r;
622         }
623         normalize_in_field(c);
624 }
625
626 /** Calculates the derivative of the polynomial a.
627  *  
628  *  @param[in]  a  polynomial of which to take the derivative
629  *  @param[out] d  result/derivative
630  */
631 static void deriv(const umodpoly& a, umodpoly& d)
632 {
633         d.clear();
634         if ( a.size() <= 1 ) return;
635
636         d.insert(d.begin(), a.begin()+1, a.end());
637         int max = d.size();
638         for ( int i=1; i<max; ++i ) {
639                 d[i] = d[i] * (i+1);
640         }
641         canonicalize(d);
642 }
643
644 static bool unequal_one(const umodpoly& a)
645 {
646         if ( a.empty() ) return true;
647         return ( a.size() != 1 || a[0] != a[0].ring()->one() );
648 }
649
650 static bool equal_one(const umodpoly& a)
651 {
652         return ( a.size() == 1 && a[0] == a[0].ring()->one() );
653 }
654
655 /** Returns true if polynomial a is square free.
656  *
657  *  @param[in] a  polynomial to check
658  *  @return       true if polynomial is square free, false otherwise
659  */
660 static bool squarefree(const umodpoly& a)
661 {
662         umodpoly b;
663         deriv(a, b);
664         if ( b.empty() ) {
665                 return false;
666         }
667         umodpoly c;
668         gcd(a, b, c);
669         return equal_one(c);
670 }
671
672 // END modular univariate polynomial code
673 ////////////////////////////////////////////////////////////////////////////////
674
675 ////////////////////////////////////////////////////////////////////////////////
676 // modular matrix
677
678 typedef vector<cl_MI> mvec;
679
680 class modular_matrix
681 {
682         friend ostream& operator<<(ostream& o, const modular_matrix& m);
683 public:
684         modular_matrix(size_t r_, size_t c_, const cl_MI& init) : r(r_), c(c_)
685         {
686                 m.resize(c*r, init);
687         }
688         size_t rowsize() const { return r; }
689         size_t colsize() const { return c; }
690         cl_MI& operator()(size_t row, size_t col) { return m[row*c + col]; }
691         cl_MI operator()(size_t row, size_t col) const { return m[row*c + col]; }
692         void mul_col(size_t col, const cl_MI x)
693         {
694                 for ( size_t rc=0; rc<r; ++rc ) {
695                         std::size_t i = c*rc + col;
696                         m[i] = m[i] * x;
697                 }
698         }
699         void sub_col(size_t col1, size_t col2, const cl_MI fac)
700         {
701                 for ( size_t rc=0; rc<r; ++rc ) {
702                         std::size_t i1 = col1 + c*rc;
703                         std::size_t i2 = col2 + c*rc;
704                         m[i1] = m[i1] - m[i2]*fac;
705                 }
706         }
707         void switch_col(size_t col1, size_t col2)
708         {
709                 for ( size_t rc=0; rc<r; ++rc ) {
710                         std::size_t i1 = col1 + rc*c;
711                         std::size_t i2 = col2 + rc*c;
712                         std::swap(m[i1], m[i2]);
713                 }
714         }
715         void mul_row(size_t row, const cl_MI x)
716         {
717                 for ( size_t cc=0; cc<c; ++cc ) {
718                         std::size_t i = row*c + cc; 
719                         m[i] = m[i] * x;
720                 }
721         }
722         void sub_row(size_t row1, size_t row2, const cl_MI fac)
723         {
724                 for ( size_t cc=0; cc<c; ++cc ) {
725                         std::size_t i1 = row1*c + cc;
726                         std::size_t i2 = row2*c + cc;
727                         m[i1] = m[i1] - m[i2]*fac;
728                 }
729         }
730         void switch_row(size_t row1, size_t row2)
731         {
732                 for ( size_t cc=0; cc<c; ++cc ) {
733                         std::size_t i1 = row1*c + cc;
734                         std::size_t i2 = row2*c + cc;
735                         std::swap(m[i1], m[i2]);
736                 }
737         }
738         bool is_col_zero(size_t col) const
739         {
740                 mvec::const_iterator i = m.begin() + col;
741                 for ( size_t rr=0; rr<r; ++rr ) {
742                         std::size_t i = col + rr*c;
743                         if ( !zerop(m[i]) ) {
744                                 return false;
745                         }
746                 }
747                 return true;
748         }
749         bool is_row_zero(size_t row) const
750         {
751                 for ( size_t cc=0; cc<c; ++cc ) {
752                         std::size_t i = row*c + cc;
753                         if ( !zerop(m[i]) ) {
754                                 return false;
755                         }
756                 }
757                 return true;
758         }
759         void set_row(size_t row, const vector<cl_MI>& newrow)
760         {
761                 for (std::size_t i2 = 0; i2 < newrow.size(); ++i2) {
762                         std::size_t i1 = row*c + i2;
763                         m[i1] = newrow[i2];
764                 }
765         }
766         mvec::const_iterator row_begin(size_t row) const { return m.begin()+row*c; }
767         mvec::const_iterator row_end(size_t row) const { return m.begin()+row*c+r; }
768 private:
769         size_t r, c;
770         mvec m;
771 };
772
773 #ifdef DEBUGFACTOR
774 modular_matrix operator*(const modular_matrix& m1, const modular_matrix& m2)
775 {
776         const unsigned int r = m1.rowsize();
777         const unsigned int c = m2.colsize();
778         modular_matrix o(r,c,m1(0,0));
779
780         for ( size_t i=0; i<r; ++i ) {
781                 for ( size_t j=0; j<c; ++j ) {
782                         cl_MI buf;
783                         buf = m1(i,0) * m2(0,j);
784                         for ( size_t k=1; k<c; ++k ) {
785                                 buf = buf + m1(i,k)*m2(k,j);
786                         }
787                         o(i,j) = buf;
788                 }
789         }
790         return o;
791 }
792
793 ostream& operator<<(ostream& o, const modular_matrix& m)
794 {
795         cl_modint_ring R = m(0,0).ring();
796         o << "{";
797         for ( size_t i=0; i<m.rowsize(); ++i ) {
798                 o << "{";
799                 for ( size_t j=0; j<m.colsize()-1; ++j ) {
800                         o << R->retract(m(i,j)) << ",";
801                 }
802                 o << R->retract(m(i,m.colsize()-1)) << "}";
803                 if ( i != m.rowsize()-1 ) {
804                         o << ",";
805                 }
806         }
807         o << "}";
808         return o;
809 }
810 #endif // def DEBUGFACTOR
811
812 // END modular matrix
813 ////////////////////////////////////////////////////////////////////////////////
814
815 /** Calculates the Q matrix for a polynomial. Used by Berlekamp's algorithm.
816  *
817  *  @param[in]  a_  modular polynomial
818  *  @param[out] Q   Q matrix
819  */
820 static void q_matrix(const umodpoly& a_, modular_matrix& Q)
821 {
822         umodpoly a = a_;
823         normalize_in_field(a);
824
825         int n = degree(a);
826         unsigned int q = cl_I_to_uint(a[0].ring()->modulus);
827         umodpoly r(n, a[0].ring()->zero());
828         r[0] = a[0].ring()->one();
829         Q.set_row(0, r);
830         unsigned int max = (n-1) * q;
831         for ( size_t m=1; m<=max; ++m ) {
832                 cl_MI rn_1 = r.back();
833                 for ( size_t i=n-1; i>0; --i ) {
834                         r[i] = r[i-1] - (rn_1 * a[i]);
835                 }
836                 r[0] = -rn_1 * a[0];
837                 if ( (m % q) == 0 ) {
838                         Q.set_row(m/q, r);
839                 }
840         }
841 }
842
843 /** Determine the nullspace of a matrix M-1.
844  *
845  *  @param[in,out] M      matrix, will be modified
846  *  @param[out]    basis  calculated nullspace of M-1
847  */
848 static void nullspace(modular_matrix& M, vector<mvec>& basis)
849 {
850         const size_t n = M.rowsize();
851         const cl_MI one = M(0,0).ring()->one();
852         for ( size_t i=0; i<n; ++i ) {
853                 M(i,i) = M(i,i) - one;
854         }
855         for ( size_t r=0; r<n; ++r ) {
856                 size_t cc = 0;
857                 for ( ; cc<n; ++cc ) {
858                         if ( !zerop(M(r,cc)) ) {
859                                 if ( cc < r ) {
860                                         if ( !zerop(M(cc,cc)) ) {
861                                                 continue;
862                                         }
863                                         M.switch_col(cc, r);
864                                 }
865                                 else if ( cc > r ) {
866                                         M.switch_col(cc, r);
867                                 }
868                                 break;
869                         }
870                 }
871                 if ( cc < n ) {
872                         M.mul_col(r, recip(M(r,r)));
873                         for ( cc=0; cc<n; ++cc ) {
874                                 if ( cc != r ) {
875                                         M.sub_col(cc, r, M(r,cc));
876                                 }
877                         }
878                 }
879         }
880
881         for ( size_t i=0; i<n; ++i ) {
882                 M(i,i) = M(i,i) - one;
883         }
884         for ( size_t i=0; i<n; ++i ) {
885                 if ( !M.is_row_zero(i) ) {
886                         mvec nu(M.row_begin(i), M.row_end(i));
887                         basis.push_back(nu);
888                 }
889         }
890 }
891
892 /** Berlekamp's modular factorization.
893  *  
894  *  The implementation follows the algorithm in chapter 8 of [GCL].
895  *
896  *  @param[in]  a    modular polynomial
897  *  @param[out] upv  vector containing modular factors. if upv was not empty the
898  *                   new elements are added at the end
899  */
900 static void berlekamp(const umodpoly& a, upvec& upv)
901 {
902         cl_modint_ring R = a[0].ring();
903         umodpoly one(1, R->one());
904
905         // find nullspace of Q matrix
906         modular_matrix Q(degree(a), degree(a), R->zero());
907         q_matrix(a, Q);
908         vector<mvec> nu;
909         nullspace(Q, nu);
910
911         const unsigned int k = nu.size();
912         if ( k == 1 ) {
913                 // irreducible
914                 return;
915         }
916
917         list<umodpoly> factors;
918         factors.push_back(a);
919         unsigned int size = 1;
920         unsigned int r = 1;
921         unsigned int q = cl_I_to_uint(R->modulus);
922
923         list<umodpoly>::iterator u = factors.begin();
924
925         // calculate all gcd's
926         while ( true ) {
927                 for ( unsigned int s=0; s<q; ++s ) {
928                         umodpoly nur = nu[r];
929                         nur[0] = nur[0] - cl_MI(R, s);
930                         canonicalize(nur);
931                         umodpoly g;
932                         gcd(nur, *u, g);
933                         if ( unequal_one(g) && g != *u ) {
934                                 umodpoly uo;
935                                 div(*u, g, uo);
936                                 if ( equal_one(uo) ) {
937                                         throw logic_error("berlekamp: unexpected divisor.");
938                                 }
939                                 else {
940                                         *u = uo;
941                                 }
942                                 factors.push_back(g);
943                                 size = 0;
944                                 list<umodpoly>::const_iterator i = factors.begin(), end = factors.end();
945                                 while ( i != end ) {
946                                         if ( degree(*i) ) ++size; 
947                                         ++i;
948                                 }
949                                 if ( size == k ) {
950                                         list<umodpoly>::const_iterator i = factors.begin(), end = factors.end();
951                                         while ( i != end ) {
952                                                 upv.push_back(*i++);
953                                         }
954                                         return;
955                                 }
956                         }
957                 }
958                 if ( ++r == k ) {
959                         r = 1;
960                         ++u;
961                 }
962         }
963 }
964
965 // modular square free factorization is not used at the moment so we deactivate
966 // the code
967 #if 0
968
969 /** Calculates a^(1/prime).
970  *  
971  *  @param[in] a      polynomial
972  *  @param[in] prime  prime number -> exponent 1/prime
973  *  @param[in] ap     resulting polynomial
974  */
975 static void expt_1_over_p(const umodpoly& a, unsigned int prime, umodpoly& ap)
976 {
977         size_t newdeg = degree(a)/prime;
978         ap.resize(newdeg+1);
979         ap[0] = a[0];
980         for ( size_t i=1; i<=newdeg; ++i ) {
981                 ap[i] = a[i*prime];
982         }
983 }
984
985 /** Modular square free factorization.
986  *
987  *  @param[in]  a        polynomial
988  *  @param[out] factors  modular factors
989  *  @param[out] mult     corresponding multiplicities (exponents)
990  */
991 static void modsqrfree(const umodpoly& a, upvec& factors, vector<int>& mult)
992 {
993         const unsigned int prime = cl_I_to_uint(a[0].ring()->modulus);
994         int i = 1;
995         umodpoly b;
996         deriv(a, b);
997         if ( b.size() ) {
998                 umodpoly c;
999                 gcd(a, b, c);
1000                 umodpoly w;
1001                 div(a, c, w);
1002                 while ( unequal_one(w) ) {
1003                         umodpoly y;
1004                         gcd(w, c, y);
1005                         umodpoly z;
1006                         div(w, y, z);
1007                         factors.push_back(z);
1008                         mult.push_back(i);
1009                         ++i;
1010                         w = y;
1011                         umodpoly buf;
1012                         div(c, y, buf);
1013                         c = buf;
1014                 }
1015                 if ( unequal_one(c) ) {
1016                         umodpoly cp;
1017                         expt_1_over_p(c, prime, cp);
1018                         size_t previ = mult.size();
1019                         modsqrfree(cp, factors, mult);
1020                         for ( size_t i=previ; i<mult.size(); ++i ) {
1021                                 mult[i] *= prime;
1022                         }
1023                 }
1024         }
1025         else {
1026                 umodpoly ap;
1027                 expt_1_over_p(a, prime, ap);
1028                 size_t previ = mult.size();
1029                 modsqrfree(ap, factors, mult);
1030                 for ( size_t i=previ; i<mult.size(); ++i ) {
1031                         mult[i] *= prime;
1032                 }
1033         }
1034 }
1035
1036 #endif // deactivation of square free factorization
1037
1038 /** Distinct degree factorization (DDF).
1039  *  
1040  *  The implementation follows the algorithm in chapter 8 of [GCL].
1041  *
1042  *  @param[in]  a_         modular polynomial
1043  *  @param[out] degrees    vector containing the degrees of the factors of the
1044  *                         corresponding polynomials in ddfactors.
1045  *  @param[out] ddfactors  vector containing polynomials which factors have the
1046  *                         degree given in degrees.
1047  */
1048 static void distinct_degree_factor(const umodpoly& a_, vector<int>& degrees, upvec& ddfactors)
1049 {
1050         umodpoly a = a_;
1051
1052         cl_modint_ring R = a[0].ring();
1053         int q = cl_I_to_int(R->modulus);
1054         int nhalf = degree(a)/2;
1055
1056         int i = 1;
1057         umodpoly w(2);
1058         w[0] = R->zero();
1059         w[1] = R->one();
1060         umodpoly x = w;
1061
1062         while ( i <= nhalf ) {
1063                 expt_pos(w, q);
1064                 umodpoly buf;
1065                 rem(w, a, buf);
1066                 w = buf;
1067                 umodpoly wx = w - x;
1068                 gcd(a, wx, buf);
1069                 if ( unequal_one(buf) ) {
1070                         degrees.push_back(i);
1071                         ddfactors.push_back(buf);
1072                 }
1073                 if ( unequal_one(buf) ) {
1074                         umodpoly buf2;
1075                         div(a, buf, buf2);
1076                         a = buf2;
1077                         nhalf = degree(a)/2;
1078                         rem(w, a, buf);
1079                         w = buf;
1080                 }
1081                 ++i;
1082         }
1083         if ( unequal_one(a) ) {
1084                 degrees.push_back(degree(a));
1085                 ddfactors.push_back(a);
1086         }
1087 }
1088
1089 /** Modular same degree factorization.
1090  *  Same degree factorization is a kind of misnomer. It performs distinct degree
1091  *  factorization, but instead of using the Cantor-Zassenhaus algorithm it
1092  *  (sub-optimally) uses Berlekamp's algorithm for the factors of the same
1093  *  degree.
1094  *
1095  *  @param[in]  a    modular polynomial
1096  *  @param[out] upv  vector containing modular factors. if upv was not empty the
1097  *                   new elements are added at the end
1098  */
1099 static void same_degree_factor(const umodpoly& a, upvec& upv)
1100 {
1101         cl_modint_ring R = a[0].ring();
1102
1103         vector<int> degrees;
1104         upvec ddfactors;
1105         distinct_degree_factor(a, degrees, ddfactors);
1106
1107         for ( size_t i=0; i<degrees.size(); ++i ) {
1108                 if ( degrees[i] == degree(ddfactors[i]) ) {
1109                         upv.push_back(ddfactors[i]);
1110                 }
1111                 else {
1112                         berlekamp(ddfactors[i], upv);
1113                 }
1114         }
1115 }
1116
1117 // Yes, we can (choose).
1118 #define USE_SAME_DEGREE_FACTOR
1119
1120 /** Modular univariate factorization.
1121  *
1122  *  In principle, we have two algorithms at our disposal: Berlekamp's algorithm
1123  *  and same degree factorization (SDF). SDF seems to be slightly faster in
1124  *  almost all cases so it is activated as default.
1125  *
1126  *  @param[in]  p    modular polynomial
1127  *  @param[out] upv  vector containing modular factors. if upv was not empty the
1128  *                   new elements are added at the end
1129  */
1130 static void factor_modular(const umodpoly& p, upvec& upv)
1131 {
1132 #ifdef USE_SAME_DEGREE_FACTOR
1133         same_degree_factor(p, upv);
1134 #else
1135         berlekamp(p, upv);
1136 #endif
1137 }
1138
1139 /** Calculates modular polynomials s and t such that a*s+b*t==1.
1140  *  Assertion: a and b are relatively prime and not zero.
1141  *
1142  *  @param[in]  a  polynomial
1143  *  @param[in]  b  polynomial
1144  *  @param[out] s  polynomial
1145  *  @param[out] t  polynomial
1146  */
1147 static void exteuclid(const umodpoly& a, const umodpoly& b, umodpoly& s, umodpoly& t)
1148 {
1149         if ( degree(a) < degree(b) ) {
1150                 exteuclid(b, a, t, s);
1151                 return;
1152         }
1153
1154         umodpoly one(1, a[0].ring()->one());
1155         umodpoly c = a; normalize_in_field(c);
1156         umodpoly d = b; normalize_in_field(d);
1157         s = one;
1158         t.clear();
1159         umodpoly d1;
1160         umodpoly d2 = one;
1161         umodpoly q;
1162         while ( true ) {
1163                 div(c, d, q);
1164                 umodpoly r = c - q * d;
1165                 umodpoly r1 = s - q * d1;
1166                 umodpoly r2 = t - q * d2;
1167                 c = d;
1168                 s = d1;
1169                 t = d2;
1170                 if ( r.empty() ) break;
1171                 d = r;
1172                 d1 = r1;
1173                 d2 = r2;
1174         }
1175         cl_MI fac = recip(lcoeff(a) * lcoeff(c));
1176         umodpoly::iterator i = s.begin(), end = s.end();
1177         for ( ; i!=end; ++i ) {
1178                 *i = *i * fac;
1179         }
1180         canonicalize(s);
1181         fac = recip(lcoeff(b) * lcoeff(c));
1182         i = t.begin(), end = t.end();
1183         for ( ; i!=end; ++i ) {
1184                 *i = *i * fac;
1185         }
1186         canonicalize(t);
1187 }
1188
1189 /** Replaces the leading coefficient in a polynomial by a given number.
1190  *
1191  *  @param[in] poly  polynomial to change
1192  *  @param[in] lc    new leading coefficient
1193  *  @return          changed polynomial
1194  */
1195 static upoly replace_lc(const upoly& poly, const cl_I& lc)
1196 {
1197         if ( poly.empty() ) return poly;
1198         upoly r = poly;
1199         r.back() = lc;
1200         return r;
1201 }
1202
1203 /** Calculates the bound for the modulus.
1204  *  See [Mig].
1205  */
1206 static inline cl_I calc_bound(const ex& a, const ex& x, int maxdeg)
1207 {
1208         cl_I maxcoeff = 0;
1209         cl_R coeff = 0;
1210         for ( int i=a.degree(x); i>=a.ldegree(x); --i ) {
1211                 cl_I aa = abs(the<cl_I>(ex_to<numeric>(a.coeff(x, i)).to_cl_N()));
1212                 if ( aa > maxcoeff ) maxcoeff = aa;
1213                 coeff = coeff + square(aa);
1214         }
1215         cl_I coeffnorm = ceiling1(the<cl_R>(cln::sqrt(coeff)));
1216         cl_I B = coeffnorm * expt_pos(cl_I(2), cl_I(maxdeg));
1217         return ( B > maxcoeff ) ? B : maxcoeff;
1218 }
1219
1220 /** Calculates the bound for the modulus.
1221  *  See [Mig].
1222  */
1223 static inline cl_I calc_bound(const upoly& a, int maxdeg)
1224 {
1225         cl_I maxcoeff = 0;
1226         cl_R coeff = 0;
1227         for ( int i=degree(a); i>=0; --i ) {
1228                 cl_I aa = abs(a[i]);
1229                 if ( aa > maxcoeff ) maxcoeff = aa;
1230                 coeff = coeff + square(aa);
1231         }
1232         cl_I coeffnorm = ceiling1(the<cl_R>(cln::sqrt(coeff)));
1233         cl_I B = coeffnorm * expt_pos(cl_I(2), cl_I(maxdeg));
1234         return ( B > maxcoeff ) ? B : maxcoeff;
1235 }
1236
1237 /** Hensel lifting as used by factor_univariate().
1238  *
1239  *  The implementation follows the algorithm in chapter 6 of [GCL].
1240  *
1241  *  @param[in]  a_   primitive univariate polynomials
1242  *  @param[in]  p    prime number that does not divide lcoeff(a)
1243  *  @param[in]  u1_  modular factor of a (mod p)
1244  *  @param[in]  w1_  modular factor of a (mod p), relatively prime to u1_,
1245  *                   fulfilling  u1_*w1_ == a mod p
1246  *  @param[out] u    lifted factor
1247  *  @param[out] w    lifted factor, u*w = a
1248  */
1249 static void hensel_univar(const upoly& a_, unsigned int p, const umodpoly& u1_, const umodpoly& w1_, upoly& u, upoly& w)
1250 {
1251         upoly a = a_;
1252         const cl_modint_ring& R = u1_[0].ring();
1253
1254         // calc bound B
1255         int maxdeg = (degree(u1_) > degree(w1_)) ? degree(u1_) : degree(w1_);
1256         cl_I maxmodulus = 2*calc_bound(a, maxdeg);
1257
1258         // step 1
1259         cl_I alpha = lcoeff(a);
1260         a = a * alpha;
1261         umodpoly nu1 = u1_;
1262         normalize_in_field(nu1);
1263         umodpoly nw1 = w1_;
1264         normalize_in_field(nw1);
1265         upoly phi;
1266         phi = umodpoly_to_upoly(nu1) * alpha;
1267         umodpoly u1;
1268         umodpoly_from_upoly(u1, phi, R);
1269         phi = umodpoly_to_upoly(nw1) * alpha;
1270         umodpoly w1;
1271         umodpoly_from_upoly(w1, phi, R);
1272
1273         // step 2
1274         umodpoly s;
1275         umodpoly t;
1276         exteuclid(u1, w1, s, t);
1277
1278         // step 3
1279         u = replace_lc(umodpoly_to_upoly(u1), alpha);
1280         w = replace_lc(umodpoly_to_upoly(w1), alpha);
1281         upoly e = a - u * w;
1282         cl_I modulus = p;
1283
1284         // step 4
1285         while ( !e.empty() && modulus < maxmodulus ) {
1286                 upoly c = e / modulus;
1287                 phi = umodpoly_to_upoly(s) * c;
1288                 umodpoly sigmatilde;
1289                 umodpoly_from_upoly(sigmatilde, phi, R);
1290                 phi = umodpoly_to_upoly(t) * c;
1291                 umodpoly tautilde;
1292                 umodpoly_from_upoly(tautilde, phi, R);
1293                 umodpoly r, q;
1294                 remdiv(sigmatilde, w1, r, q);
1295                 umodpoly sigma = r;
1296                 phi = umodpoly_to_upoly(tautilde) + umodpoly_to_upoly(q) * umodpoly_to_upoly(u1);
1297                 umodpoly tau;
1298                 umodpoly_from_upoly(tau, phi, R);
1299                 u = u + umodpoly_to_upoly(tau) * modulus;
1300                 w = w + umodpoly_to_upoly(sigma) * modulus;
1301                 e = a - u * w;
1302                 modulus = modulus * p;
1303         }
1304
1305         // step 5
1306         if ( e.empty() ) {
1307                 cl_I g = u[0];
1308                 for ( size_t i=1; i<u.size(); ++i ) {
1309                         g = gcd(g, u[i]);
1310                         if ( g == 1 ) break;
1311                 }
1312                 if ( g != 1 ) {
1313                         u = u / g;
1314                         w = w * g;
1315                 }
1316                 if ( alpha != 1 ) {
1317                         w = w / alpha;
1318                 }
1319         }
1320         else {
1321                 u.clear();
1322         }
1323 }
1324
1325 /** Returns a new prime number.
1326  *
1327  *  @param[in] p  prime number
1328  *  @return       next prime number after p
1329  */
1330 static unsigned int next_prime(unsigned int p)
1331 {
1332         static vector<unsigned int> primes;
1333         if ( primes.size() == 0 ) {
1334                 primes.push_back(3); primes.push_back(5); primes.push_back(7);
1335         }
1336         vector<unsigned int>::const_iterator it = primes.begin();
1337         if ( p >= primes.back() ) {
1338                 unsigned int candidate = primes.back() + 2;
1339                 while ( true ) {
1340                         size_t n = primes.size()/2;
1341                         for ( size_t i=0; i<n; ++i ) {
1342                                 if ( candidate % primes[i] ) continue;
1343                                 candidate += 2;
1344                                 i=-1;
1345                         }
1346                         primes.push_back(candidate);
1347                         if ( candidate > p ) break;
1348                 }
1349                 return candidate;
1350         }
1351         vector<unsigned int>::const_iterator end = primes.end();
1352         for ( ; it!=end; ++it ) {
1353                 if ( *it > p ) {
1354                         return *it;
1355                 }
1356         }
1357         throw logic_error("next_prime: should not reach this point!");
1358 }
1359
1360 /** Manages the splitting a vector of of modular factors into two partitions.
1361  */
1362 class factor_partition
1363 {
1364 public:
1365         /** Takes the vector of modular factors and initializes the first partition */
1366         factor_partition(const upvec& factors_) : factors(factors_)
1367         {
1368                 n = factors.size();
1369                 k.resize(n, 0);
1370                 k[0] = 1;
1371                 cache.resize(n-1);
1372                 one.resize(1, factors.front()[0].ring()->one());
1373                 len = 1;
1374                 last = 0;
1375                 split();
1376         }
1377         int operator[](size_t i) const { return k[i]; }
1378         size_t size() const { return n; }
1379         size_t size_left() const { return n-len; }
1380         size_t size_right() const { return len; }
1381         /** Initializes the next partition.
1382             Returns true, if there is one, false otherwise. */
1383         bool next()
1384         {
1385                 if ( last == n-1 ) {
1386                         int rem = len - 1;
1387                         int p = last - 1;
1388                         while ( rem ) {
1389                                 if ( k[p] ) {
1390                                         --rem;
1391                                         --p;
1392                                         continue;
1393                                 }
1394                                 last = p - 1;
1395                                 while ( k[last] == 0 ) { --last; }
1396                                 if ( last == 0 && n == 2*len ) return false;
1397                                 k[last++] = 0;
1398                                 for ( size_t i=0; i<=len-rem; ++i ) {
1399                                         k[last] = 1;
1400                                         ++last;
1401                                 }
1402                                 fill(k.begin()+last, k.end(), 0);
1403                                 --last;
1404                                 split();
1405                                 return true;
1406                         }
1407                         last = len;
1408                         ++len;
1409                         if ( len > n/2 ) return false;
1410                         fill(k.begin(), k.begin()+len, 1);
1411                         fill(k.begin()+len+1, k.end(), 0);
1412                 }
1413                 else {
1414                         k[last++] = 0;
1415                         k[last] = 1;
1416                 }
1417                 split();
1418                 return true;
1419         }
1420         /** Get first partition */
1421         umodpoly& left() { return lr[0]; }
1422         /** Get second partition */
1423         umodpoly& right() { return lr[1]; }
1424 private:
1425         void split_cached()
1426         {
1427                 size_t i = 0;
1428                 do {
1429                         size_t pos = i;
1430                         int group = k[i++];
1431                         size_t d = 0;
1432                         while ( i < n && k[i] == group ) { ++d; ++i; }
1433                         if ( d ) {
1434                                 if ( cache[pos].size() >= d ) {
1435                                         lr[group] = lr[group] * cache[pos][d-1];
1436                                 }
1437                                 else {
1438                                         if ( cache[pos].size() == 0 ) {
1439                                                 cache[pos].push_back(factors[pos] * factors[pos+1]);
1440                                         }
1441                                         size_t j = pos + cache[pos].size() + 1;
1442                                         d -= cache[pos].size();
1443                                         while ( d ) {
1444                                                 umodpoly buf = cache[pos].back() * factors[j];
1445                                                 cache[pos].push_back(buf);
1446                                                 --d;
1447                                                 ++j;
1448                                         }
1449                                         lr[group] = lr[group] * cache[pos].back();
1450                                 }
1451                         }
1452                         else {
1453                                 lr[group] = lr[group] * factors[pos];
1454                         }
1455                 } while ( i < n );
1456         }
1457         void split()
1458         {
1459                 lr[0] = one;
1460                 lr[1] = one;
1461                 if ( n > 6 ) {
1462                         split_cached();
1463                 }
1464                 else {
1465                         for ( size_t i=0; i<n; ++i ) {
1466                                 lr[k[i]] = lr[k[i]] * factors[i];
1467                         }
1468                 }
1469         }
1470 private:
1471         umodpoly lr[2];
1472         vector< vector<umodpoly> > cache;
1473         upvec factors;
1474         umodpoly one;
1475         size_t n;
1476         size_t len;
1477         size_t last;
1478         vector<int> k;
1479 };
1480
1481 /** Contains a pair of univariate polynomial and its modular factors.
1482  *  Used by factor_univariate().
1483  */
1484 struct ModFactors
1485 {
1486         upoly poly;
1487         upvec factors;
1488 };
1489
1490 /** Univariate polynomial factorization.
1491  *
1492  *  Modular factorization is tried for several primes to minimize the number of
1493  *  modular factors. Then, Hensel lifting is performed.
1494  *
1495  *  @param[in]     poly   expanded square free univariate polynomial
1496  *  @param[in]     x      symbol
1497  *  @param[in,out] prime  prime number to start trying modular factorization with,
1498  *                        output value is the prime number actually used
1499  */
1500 static ex factor_univariate(const ex& poly, const ex& x, unsigned int& prime)
1501 {
1502         ex unit, cont, prim_ex;
1503         poly.unitcontprim(x, unit, cont, prim_ex);
1504         upoly prim;
1505         upoly_from_ex(prim, prim_ex, x);
1506
1507         // determine proper prime and minimize number of modular factors
1508         prime = 3;
1509         unsigned int lastp = prime;
1510         cl_modint_ring R;
1511         unsigned int trials = 0;
1512         unsigned int minfactors = 0;
1513         cl_I lc = lcoeff(prim) * the<cl_I>(ex_to<numeric>(cont).to_cl_N());
1514         upvec factors;
1515         while ( trials < 2 ) {
1516                 umodpoly modpoly;
1517                 while ( true ) {
1518                         prime = next_prime(prime);
1519                         if ( !zerop(rem(lc, prime)) ) {
1520                                 R = find_modint_ring(prime);
1521                                 umodpoly_from_upoly(modpoly, prim, R);
1522                                 if ( squarefree(modpoly) ) break;
1523                         }
1524                 }
1525
1526                 // do modular factorization
1527                 upvec trialfactors;
1528                 factor_modular(modpoly, trialfactors);
1529                 if ( trialfactors.size() <= 1 ) {
1530                         // irreducible for sure
1531                         return poly;
1532                 }
1533
1534                 if ( minfactors == 0 || trialfactors.size() < minfactors ) {
1535                         factors = trialfactors;
1536                         minfactors = trialfactors.size();
1537                         lastp = prime;
1538                         trials = 1;
1539                 }
1540                 else {
1541                         ++trials;
1542                 }
1543         }
1544         prime = lastp;
1545         R = find_modint_ring(prime);
1546
1547         // lift all factor combinations
1548         stack<ModFactors> tocheck;
1549         ModFactors mf;
1550         mf.poly = prim;
1551         mf.factors = factors;
1552         tocheck.push(mf);
1553         upoly f1, f2;
1554         ex result = 1;
1555         while ( tocheck.size() ) {
1556                 const size_t n = tocheck.top().factors.size();
1557                 factor_partition part(tocheck.top().factors);
1558                 while ( true ) {
1559                         // call Hensel lifting
1560                         hensel_univar(tocheck.top().poly, prime, part.left(), part.right(), f1, f2);
1561                         if ( !f1.empty() ) {
1562                                 // successful, update the stack and the result
1563                                 if ( part.size_left() == 1 ) {
1564                                         if ( part.size_right() == 1 ) {
1565                                                 result *= upoly_to_ex(f1, x) * upoly_to_ex(f2, x);
1566                                                 tocheck.pop();
1567                                                 break;
1568                                         }
1569                                         result *= upoly_to_ex(f1, x);
1570                                         tocheck.top().poly = f2;
1571                                         for ( size_t i=0; i<n; ++i ) {
1572                                                 if ( part[i] == 0 ) {
1573                                                         tocheck.top().factors.erase(tocheck.top().factors.begin()+i);
1574                                                         break;
1575                                                 }
1576                                         }
1577                                         break;
1578                                 }
1579                                 else if ( part.size_right() == 1 ) {
1580                                         if ( part.size_left() == 1 ) {
1581                                                 result *= upoly_to_ex(f1, x) * upoly_to_ex(f2, x);
1582                                                 tocheck.pop();
1583                                                 break;
1584                                         }
1585                                         result *= upoly_to_ex(f2, x);
1586                                         tocheck.top().poly = f1;
1587                                         for ( size_t i=0; i<n; ++i ) {
1588                                                 if ( part[i] == 1 ) {
1589                                                         tocheck.top().factors.erase(tocheck.top().factors.begin()+i);
1590                                                         break;
1591                                                 }
1592                                         }
1593                                         break;
1594                                 }
1595                                 else {
1596                                         upvec newfactors1(part.size_left()), newfactors2(part.size_right());
1597                                         upvec::iterator i1 = newfactors1.begin(), i2 = newfactors2.begin();
1598                                         for ( size_t i=0; i<n; ++i ) {
1599                                                 if ( part[i] ) {
1600                                                         *i2++ = tocheck.top().factors[i];
1601                                                 }
1602                                                 else {
1603                                                         *i1++ = tocheck.top().factors[i];
1604                                                 }
1605                                         }
1606                                         tocheck.top().factors = newfactors1;
1607                                         tocheck.top().poly = f1;
1608                                         ModFactors mf;
1609                                         mf.factors = newfactors2;
1610                                         mf.poly = f2;
1611                                         tocheck.push(mf);
1612                                         break;
1613                                 }
1614                         }
1615                         else {
1616                                 // not successful
1617                                 if ( !part.next() ) {
1618                                         // if no more combinations left, return polynomial as
1619                                         // irreducible
1620                                         result *= upoly_to_ex(tocheck.top().poly, x);
1621                                         tocheck.pop();
1622                                         break;
1623                                 }
1624                         }
1625                 }
1626         }
1627
1628         return unit * cont * result;
1629 }
1630
1631 /** Second interface to factor_univariate() to be used if the information about
1632  *  the prime is not needed.
1633  */
1634 static inline ex factor_univariate(const ex& poly, const ex& x)
1635 {
1636         unsigned int prime;
1637         return factor_univariate(poly, x, prime);
1638 }
1639
1640 /** Represents an evaluation point (<symbol>==<integer>).
1641  */
1642 struct EvalPoint
1643 {
1644         ex x;
1645         int evalpoint;
1646 };
1647
1648 #ifdef DEBUGFACTOR
1649 ostream& operator<<(ostream& o, const vector<EvalPoint>& v)
1650 {
1651         for ( size_t i=0; i<v.size(); ++i ) {
1652                 o << "(" << v[i].x << "==" << v[i].evalpoint << ") ";
1653         }
1654         return o;
1655 }
1656 #endif // def DEBUGFACTOR
1657
1658 // forward declaration
1659 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);
1660
1661 /** Utility function for multivariate Hensel lifting.
1662  *
1663  *  Solves the equation
1664  *    s_1*b_1 + ... + s_r*b_r == 1 mod p^k
1665  *  with deg(s_i) < deg(a_i)
1666  *  and with given b_1 = a_1 * ... * a_{i-1} * a_{i+1} * ... * a_r
1667  *
1668  *  The implementation follows the algorithm in chapter 6 of [GCL].
1669  *
1670  *  @param[in]  a   vector of modular univariate polynomials
1671  *  @param[in]  x   symbol
1672  *  @param[in]  p   prime number
1673  *  @param[in]  k   p^k is modulus
1674  *  @return         vector of polynomials (s_i)
1675  */
1676 static upvec multiterm_eea_lift(const upvec& a, const ex& x, unsigned int p, unsigned int k)
1677 {
1678         const size_t r = a.size();
1679         cl_modint_ring R = find_modint_ring(expt_pos(cl_I(p),k));
1680         upvec q(r-1);
1681         q[r-2] = a[r-1];
1682         for ( size_t j=r-2; j>=1; --j ) {
1683                 q[j-1] = a[j] * q[j];
1684         }
1685         umodpoly beta(1, R->one());
1686         upvec s;
1687         for ( size_t j=1; j<r; ++j ) {
1688                 vector<ex> mdarg(2);
1689                 mdarg[0] = umodpoly_to_ex(q[j-1], x);
1690                 mdarg[1] = umodpoly_to_ex(a[j-1], x);
1691                 vector<EvalPoint> empty;
1692                 vector<ex> exsigma = multivar_diophant(mdarg, x, umodpoly_to_ex(beta, x), empty, 0, p, k);
1693                 umodpoly sigma1;
1694                 umodpoly_from_ex(sigma1, exsigma[0], x, R);
1695                 umodpoly sigma2;
1696                 umodpoly_from_ex(sigma2, exsigma[1], x, R);
1697                 beta = sigma1;
1698                 s.push_back(sigma2);
1699         }
1700         s.push_back(beta);
1701         return s;
1702 }
1703
1704 /** Changes the modulus of a modular polynomial. Used by eea_lift().
1705  *
1706  *  @param[in]     R  new modular ring
1707  *  @param[in,out] a  polynomial to change (in situ)
1708  */
1709 static void change_modulus(const cl_modint_ring& R, umodpoly& a)
1710 {
1711         if ( a.empty() ) return;
1712         cl_modint_ring oldR = a[0].ring();
1713         umodpoly::iterator i = a.begin(), end = a.end();
1714         for ( ; i!=end; ++i ) {
1715                 *i = R->canonhom(oldR->retract(*i));
1716         }
1717         canonicalize(a);
1718 }
1719
1720 /** Utility function for multivariate Hensel lifting.
1721  *
1722  *  Solves  s*a + t*b == 1 mod p^k  given a,b.
1723  *
1724  *  The implementation follows the algorithm in chapter 6 of [GCL].
1725  *
1726  *  @param[in]  a   polynomial
1727  *  @param[in]  b   polynomial
1728  *  @param[in]  x   symbol
1729  *  @param[in]  p   prime number
1730  *  @param[in]  k   p^k is modulus
1731  *  @param[out] s_  output polynomial
1732  *  @param[out] t_  output polynomial
1733  */
1734 static void eea_lift(const umodpoly& a, const umodpoly& b, const ex& x, unsigned int p, unsigned int k, umodpoly& s_, umodpoly& t_)
1735 {
1736         cl_modint_ring R = find_modint_ring(p);
1737         umodpoly amod = a;
1738         change_modulus(R, amod);
1739         umodpoly bmod = b;
1740         change_modulus(R, bmod);
1741
1742         umodpoly smod;
1743         umodpoly tmod;
1744         exteuclid(amod, bmod, smod, tmod);
1745
1746         cl_modint_ring Rpk = find_modint_ring(expt_pos(cl_I(p),k));
1747         umodpoly s = smod;
1748         change_modulus(Rpk, s);
1749         umodpoly t = tmod;
1750         change_modulus(Rpk, t);
1751
1752         cl_I modulus(p);
1753         umodpoly one(1, Rpk->one());
1754         for ( size_t j=1; j<k; ++j ) {
1755                 umodpoly e = one - a * s - b * t;
1756                 reduce_coeff(e, modulus);
1757                 umodpoly c = e;
1758                 change_modulus(R, c);
1759                 umodpoly sigmabar = smod * c;
1760                 umodpoly taubar = tmod * c;
1761                 umodpoly sigma, q;
1762                 remdiv(sigmabar, bmod, sigma, q);
1763                 umodpoly tau = taubar + q * amod;
1764                 umodpoly sadd = sigma;
1765                 change_modulus(Rpk, sadd);
1766                 cl_MI modmodulus(Rpk, modulus);
1767                 s = s + sadd * modmodulus;
1768                 umodpoly tadd = tau;
1769                 change_modulus(Rpk, tadd);
1770                 t = t + tadd * modmodulus;
1771                 modulus = modulus * p;
1772         }
1773
1774         s_ = s; t_ = t;
1775 }
1776
1777 /** Utility function for multivariate Hensel lifting.
1778  *
1779  *  Solves the equation
1780  *    s_1*b_1 + ... + s_r*b_r == x^m mod p^k
1781  *  with given b_1 = a_1 * ... * a_{i-1} * a_{i+1} * ... * a_r
1782  *
1783  *  The implementation follows the algorithm in chapter 6 of [GCL].
1784  *
1785  *  @param a  vector with univariate polynomials mod p^k
1786  *  @param x  symbol
1787  *  @param m  exponent of x^m in the equation to solve
1788  *  @param p  prime number
1789  *  @param k  p^k is modulus
1790  *  @return   vector of polynomials (s_i)
1791  */
1792 static upvec univar_diophant(const upvec& a, const ex& x, unsigned int m, unsigned int p, unsigned int k)
1793 {
1794         cl_modint_ring R = find_modint_ring(expt_pos(cl_I(p),k));
1795
1796         const size_t r = a.size();
1797         upvec result;
1798         if ( r > 2 ) {
1799                 upvec s = multiterm_eea_lift(a, x, p, k);
1800                 for ( size_t j=0; j<r; ++j ) {
1801                         umodpoly bmod = umodpoly_to_umodpoly(s[j], R, m);
1802                         umodpoly buf;
1803                         rem(bmod, a[j], buf);
1804                         result.push_back(buf);
1805                 }
1806         }
1807         else {
1808                 umodpoly s, t;
1809                 eea_lift(a[1], a[0], x, p, k, s, t);
1810                 umodpoly bmod = umodpoly_to_umodpoly(s, R, m);
1811                 umodpoly buf, q;
1812                 remdiv(bmod, a[0], buf, q);
1813                 result.push_back(buf);
1814                 umodpoly t1mod = umodpoly_to_umodpoly(t, R, m);
1815                 buf = t1mod + q * a[1];
1816                 result.push_back(buf);
1817         }
1818
1819         return result;
1820 }
1821
1822 /** Map used by function make_modular().
1823  *  Finds every coefficient in a polynomial and replaces it by is value in the
1824  *  given modular ring R (symmetric representation).
1825  */
1826 struct make_modular_map : public map_function {
1827         cl_modint_ring R;
1828         make_modular_map(const cl_modint_ring& R_) : R(R_) { }
1829         ex operator()(const ex& e)
1830         {
1831                 if ( is_a<add>(e) || is_a<mul>(e) ) {
1832                         return e.map(*this);
1833                 }
1834                 else if ( is_a<numeric>(e) ) {
1835                         numeric mod(R->modulus);
1836                         numeric halfmod = (mod-1)/2;
1837                         cl_MI emod = R->canonhom(the<cl_I>(ex_to<numeric>(e).to_cl_N()));
1838                         numeric n(R->retract(emod));
1839                         if ( n > halfmod ) {
1840                                 return n-mod;
1841                         }
1842                         else {
1843                                 return n;
1844                         }
1845                 }
1846                 return e;
1847         }
1848 };
1849
1850 /** Helps mimicking modular multivariate polynomial arithmetic.
1851  *
1852  *  @param e  expression of which to make the coefficients equal to their value
1853  *            in the modular ring R (symmetric representation)
1854  *  @param R  modular ring
1855  *  @return   resulting expression
1856  */
1857 static ex make_modular(const ex& e, const cl_modint_ring& R)
1858 {
1859         make_modular_map map(R);
1860         return map(e.expand());
1861 }
1862
1863 /** Utility function for multivariate Hensel lifting.
1864  *
1865  *  Returns the polynomials s_i that fulfill
1866  *    s_1*b_1 + ... + s_r*b_r == c mod <I^(d+1),p^k>
1867  *  with given b_1 = a_1 * ... * a_{i-1} * a_{i+1} * ... * a_r
1868  *
1869  *  The implementation follows the algorithm in chapter 6 of [GCL].
1870  *
1871  *  @param a_  vector of multivariate factors mod p^k
1872  *  @param x   symbol (equiv. x_1 in [GCL])
1873  *  @param c   polynomial mod p^k
1874  *  @param I   vector of evaluation points
1875  *  @param d   maximum total degree of result
1876  *  @param p   prime number
1877  *  @param k   p^k is modulus
1878  *  @return    vector of polynomials (s_i)
1879  */
1880 static vector<ex> multivar_diophant(const vector<ex>& a_, const ex& x, const ex& c, const vector<EvalPoint>& I,
1881                                     unsigned int d, unsigned int p, unsigned int k)
1882 {
1883         vector<ex> a = a_;
1884
1885         const cl_modint_ring R = find_modint_ring(expt_pos(cl_I(p),k));
1886         const size_t r = a.size();
1887         const size_t nu = I.size() + 1;
1888
1889         vector<ex> sigma;
1890         if ( nu > 1 ) {
1891                 ex xnu = I.back().x;
1892                 int alphanu = I.back().evalpoint;
1893
1894                 ex A = 1;
1895                 for ( size_t i=0; i<r; ++i ) {
1896                         A *= a[i];
1897                 }
1898                 vector<ex> b(r);
1899                 for ( size_t i=0; i<r; ++i ) {
1900                         b[i] = normal(A / a[i]);
1901                 }
1902
1903                 vector<ex> anew = a;
1904                 for ( size_t i=0; i<r; ++i ) {
1905                         anew[i] = anew[i].subs(xnu == alphanu);
1906                 }
1907                 ex cnew = c.subs(xnu == alphanu);
1908                 vector<EvalPoint> Inew = I;
1909                 Inew.pop_back();
1910                 sigma = multivar_diophant(anew, x, cnew, Inew, d, p, k);
1911
1912                 ex buf = c;
1913                 for ( size_t i=0; i<r; ++i ) {
1914                         buf -= sigma[i] * b[i];
1915                 }
1916                 ex e = make_modular(buf, R);
1917
1918                 ex monomial = 1;
1919                 for ( size_t m=1; !e.is_zero() && e.has(xnu) && m<=d; ++m ) {
1920                         monomial *= (xnu - alphanu);
1921                         monomial = expand(monomial);
1922                         ex cm = e.diff(ex_to<symbol>(xnu), m).subs(xnu==alphanu) / factorial(m);
1923                         cm = make_modular(cm, R);
1924                         if ( !cm.is_zero() ) {
1925                                 vector<ex> delta_s = multivar_diophant(anew, x, cm, Inew, d, p, k);
1926                                 ex buf = e;
1927                                 for ( size_t j=0; j<delta_s.size(); ++j ) {
1928                                         delta_s[j] *= monomial;
1929                                         sigma[j] += delta_s[j];
1930                                         buf -= delta_s[j] * b[j];
1931                                 }
1932                                 e = make_modular(buf, R);
1933                         }
1934                 }
1935         }
1936         else {
1937                 upvec amod;
1938                 for ( size_t i=0; i<a.size(); ++i ) {
1939                         umodpoly up;
1940                         umodpoly_from_ex(up, a[i], x, R);
1941                         amod.push_back(up);
1942                 }
1943
1944                 sigma.insert(sigma.begin(), r, 0);
1945                 size_t nterms;
1946                 ex z;
1947                 if ( is_a<add>(c) ) {
1948                         nterms = c.nops();
1949                         z = c.op(0);
1950                 }
1951                 else {
1952                         nterms = 1;
1953                         z = c;
1954                 }
1955                 for ( size_t i=0; i<nterms; ++i ) {
1956                         int m = z.degree(x);
1957                         cl_I cm = the<cl_I>(ex_to<numeric>(z.lcoeff(x)).to_cl_N());
1958                         upvec delta_s = univar_diophant(amod, x, m, p, k);
1959                         cl_MI modcm;
1960                         cl_I poscm = cm;
1961                         while ( poscm < 0 ) {
1962                                 poscm = poscm + expt_pos(cl_I(p),k);
1963                         }
1964                         modcm = cl_MI(R, poscm);
1965                         for ( size_t j=0; j<delta_s.size(); ++j ) {
1966                                 delta_s[j] = delta_s[j] * modcm;
1967                                 sigma[j] = sigma[j] + umodpoly_to_ex(delta_s[j], x);
1968                         }
1969                         if ( nterms > 1 ) {
1970                                 z = c.op(i+1);
1971                         }
1972                 }
1973         }
1974
1975         for ( size_t i=0; i<sigma.size(); ++i ) {
1976                 sigma[i] = make_modular(sigma[i], R);
1977         }
1978
1979         return sigma;
1980 }
1981
1982 /** Multivariate Hensel lifting.
1983  *  The implementation follows the algorithm in chapter 6 of [GCL].
1984  *  Since we don't have a data type for modular multivariate polynomials, the
1985  *  respective operations are done in a GiNaC::ex and the function
1986  *  make_modular() is then called to make the coefficient modular p^l.
1987  *
1988  *  @param a    multivariate polynomial primitive in x
1989  *  @param x    symbol (equiv. x_1 in [GCL])
1990  *  @param I    vector of evaluation points (x_2==a_2,x_3==a_3,...)
1991  *  @param p    prime number (should not divide lcoeff(a mod I))
1992  *  @param l    p^l is the modulus of the lifted univariate field
1993  *  @param u    vector of modular (mod p^l) factors of a mod I
1994  *  @param lcU  correct leading coefficient of the univariate factors of a mod I
1995  *  @return     list GiNaC::lst with lifted factors (multivariate factors of a),
1996  *              empty if Hensel lifting did not succeed
1997  */
1998 static ex hensel_multivar(const ex& a, const ex& x, const vector<EvalPoint>& I,
1999                           unsigned int p, const cl_I& l, const upvec& u, const vector<ex>& lcU)
2000 {
2001         const size_t nu = I.size() + 1;
2002         const cl_modint_ring R = find_modint_ring(expt_pos(cl_I(p),l));
2003
2004         vector<ex> A(nu);
2005         A[nu-1] = a;
2006
2007         for ( size_t j=nu; j>=2; --j ) {
2008                 ex x = I[j-2].x;
2009                 int alpha = I[j-2].evalpoint;
2010                 A[j-2] = A[j-1].subs(x==alpha);
2011                 A[j-2] = make_modular(A[j-2], R);
2012         }
2013
2014         int maxdeg = a.degree(I.front().x);
2015         for ( size_t i=1; i<I.size(); ++i ) {
2016                 int maxdeg2 = a.degree(I[i].x);
2017                 if ( maxdeg2 > maxdeg ) maxdeg = maxdeg2;
2018         }
2019
2020         const size_t n = u.size();
2021         vector<ex> U(n);
2022         for ( size_t i=0; i<n; ++i ) {
2023                 U[i] = umodpoly_to_ex(u[i], x);
2024         }
2025
2026         for ( size_t j=2; j<=nu; ++j ) {
2027                 vector<ex> U1 = U;
2028                 ex monomial = 1;
2029                 for ( size_t m=0; m<n; ++m) {
2030                         if ( lcU[m] != 1 ) {
2031                                 ex coef = lcU[m];
2032                                 for ( size_t i=j-1; i<nu-1; ++i ) {
2033                                         coef = coef.subs(I[i].x == I[i].evalpoint);
2034                                 }
2035                                 coef = make_modular(coef, R);
2036                                 int deg = U[m].degree(x);
2037                                 U[m] = U[m] - U[m].lcoeff(x) * pow(x,deg) + coef * pow(x,deg);
2038                         }
2039                 }
2040                 ex Uprod = 1;
2041                 for ( size_t i=0; i<n; ++i ) {
2042                         Uprod *= U[i];
2043                 }
2044                 ex e = expand(A[j-1] - Uprod);
2045
2046                 vector<EvalPoint> newI;
2047                 for ( size_t i=1; i<=j-2; ++i ) {
2048                         newI.push_back(I[i-1]);
2049                 }
2050
2051                 ex xj = I[j-2].x;
2052                 int alphaj = I[j-2].evalpoint;
2053                 size_t deg = A[j-1].degree(xj);
2054                 for ( size_t k=1; k<=deg; ++k ) {
2055                         if ( !e.is_zero() ) {
2056                                 monomial *= (xj - alphaj);
2057                                 monomial = expand(monomial);
2058                                 ex dif = e.diff(ex_to<symbol>(xj), k);
2059                                 ex c = dif.subs(xj==alphaj) / factorial(k);
2060                                 if ( !c.is_zero() ) {
2061                                         vector<ex> deltaU = multivar_diophant(U1, x, c, newI, maxdeg, p, cl_I_to_uint(l));
2062                                         for ( size_t i=0; i<n; ++i ) {
2063                                                 deltaU[i] *= monomial;
2064                                                 U[i] += deltaU[i];
2065                                                 U[i] = make_modular(U[i], R);
2066                                         }
2067                                         ex Uprod = 1;
2068                                         for ( size_t i=0; i<n; ++i ) {
2069                                                 Uprod *= U[i];
2070                                         }
2071                                         e = A[j-1] - Uprod;
2072                                         e = make_modular(e, R);
2073                                 }
2074                         }
2075                 }
2076         }
2077
2078         ex acand = 1;
2079         for ( size_t i=0; i<U.size(); ++i ) {
2080                 acand *= U[i];
2081         }
2082         if ( expand(a-acand).is_zero() ) {
2083                 lst res;
2084                 for ( size_t i=0; i<U.size(); ++i ) {
2085                         res.append(U[i]);
2086                 }
2087                 return res;
2088         }
2089         else {
2090                 lst res;
2091                 return lst();
2092         }
2093 }
2094
2095 /** Takes a factorized expression and puts the factors in a lst. The exponents
2096  *  of the factors are discarded, e.g. 7*x^2*(y+1)^4 --> {7,x,y+1}. The first
2097  *  element of the list is always the numeric coefficient.
2098  */
2099 static ex put_factors_into_lst(const ex& e)
2100 {
2101         lst result;
2102         if ( is_a<numeric>(e) ) {
2103                 result.append(e);
2104                 return result;
2105         }
2106         if ( is_a<power>(e) ) {
2107                 result.append(1);
2108                 result.append(e.op(0));
2109                 return result;
2110         }
2111         if ( is_a<symbol>(e) || is_a<add>(e) ) {
2112                 result.append(1);
2113                 result.append(e);
2114                 return result;
2115         }
2116         if ( is_a<mul>(e) ) {
2117                 ex nfac = 1;
2118                 for ( size_t i=0; i<e.nops(); ++i ) {
2119                         ex op = e.op(i);
2120                         if ( is_a<numeric>(op) ) {
2121                                 nfac = op;
2122                         }
2123                         if ( is_a<power>(op) ) {
2124                                 result.append(op.op(0));
2125                         }
2126                         if ( is_a<symbol>(op) || is_a<add>(op) ) {
2127                                 result.append(op);
2128                         }
2129                 }
2130                 result.prepend(nfac);
2131                 return result;
2132         }
2133         throw runtime_error("put_factors_into_lst: bad term.");
2134 }
2135
2136 /** Checks a set of numbers for whether each number has a unique prime factor.
2137  *
2138  *  @param[in]  f  list of numbers to check
2139  *  @return        true: if number set is bad, false: if set is okay (has unique
2140  *                 prime factors)
2141  */
2142 static bool checkdivisors(const lst& f)
2143 {
2144         const int k = f.nops();
2145         numeric q, r;
2146         vector<numeric> d(k);
2147         d[0] = ex_to<numeric>(abs(f.op(0)));
2148         for ( int i=1; i<k; ++i ) {
2149                 q = ex_to<numeric>(abs(f.op(i)));
2150                 for ( int j=i-1; j>=0; --j ) {
2151                         r = d[j];
2152                         do {
2153                                 r = gcd(r, q);
2154                                 q = q/r;
2155                         } while ( r != 1 );
2156                         if ( q == 1 ) {
2157                                 return true;
2158                         }
2159                 }
2160                 d[i] = q;
2161         }
2162         return false;
2163 }
2164
2165 /** Generates a set of evaluation points for a multivariate polynomial.
2166  *  The set fulfills the following conditions:
2167  *  1. lcoeff(evaluated_polynomial) does not vanish
2168  *  2. factors of lcoeff(evaluated_polynomial) have each a unique prime factor
2169  *  3. evaluated_polynomial is square free
2170  *  See [Wan] for more details.
2171  *
2172  *  @param[in]     u        multivariate polynomial to be factored
2173  *  @param[in]     vn       leading coefficient of u in x (x==first symbol in syms)
2174  *  @param[in]     syms     set of symbols that appear in u
2175  *  @param[in]     f        lst containing the factors of the leading coefficient vn
2176  *  @param[in,out] modulus  integer modulus for random number generation (i.e. |a_i| < modulus)
2177  *  @param[out]    u0       returns the evaluated (univariate) polynomial
2178  *  @param[out]    a        returns the valid evaluation points. must have initial size equal
2179  *                          number of symbols-1 before calling generate_set
2180  */
2181 static void generate_set(const ex& u, const ex& vn, const exset& syms, const lst& f,
2182                          numeric& modulus, ex& u0, vector<numeric>& a)
2183 {
2184         const ex& x = *syms.begin();
2185         while ( true ) {
2186                 ++modulus;
2187                 // generate a set of integers ...
2188                 u0 = u;
2189                 ex vna = vn;
2190                 ex vnatry;
2191                 exset::const_iterator s = syms.begin();
2192                 ++s;
2193                 for ( size_t i=0; i<a.size(); ++i ) {
2194                         do {
2195                                 a[i] = mod(numeric(rand()), 2*modulus) - modulus;
2196                                 vnatry = vna.subs(*s == a[i]);
2197                                 // ... for which the leading coefficient doesn't vanish ...
2198                         } while ( vnatry == 0 );
2199                         vna = vnatry;
2200                         u0 = u0.subs(*s == a[i]);
2201                         ++s;
2202                 }
2203                 // ... for which u0 is square free ...
2204                 ex g = gcd(u0, u0.diff(ex_to<symbol>(x)));
2205                 if ( !is_a<numeric>(g) ) {
2206                         continue;
2207                 }
2208                 if ( !is_a<numeric>(vn) ) {
2209                         // ... and for which the evaluated factors have each an unique prime factor
2210                         lst fnum = f;
2211                         fnum.let_op(0) = fnum.op(0) * u0.content(x);
2212                         for ( size_t i=1; i<fnum.nops(); ++i ) {
2213                                 if ( !is_a<numeric>(fnum.op(i)) ) {
2214                                         s = syms.begin();
2215                                         ++s;
2216                                         for ( size_t j=0; j<a.size(); ++j, ++s ) {
2217                                                 fnum.let_op(i) = fnum.op(i).subs(*s == a[j]);
2218                                         }
2219                                 }
2220                         }
2221                         if ( checkdivisors(fnum) ) {
2222                                 continue;
2223                         }
2224                 }
2225                 // ok, we have a valid set now
2226                 return;
2227         }
2228 }
2229
2230 // forward declaration
2231 static ex factor_sqrfree(const ex& poly);
2232
2233 /** Multivariate factorization.
2234  *  
2235  *  The implementation is based on the algorithm described in [Wan].
2236  *  An evaluation homomorphism (a set of integers) is determined that fulfills
2237  *  certain criteria. The evaluated polynomial is univariate and is factorized
2238  *  by factor_univariate(). The main work then is to find the correct leading
2239  *  coefficients of the univariate factors. They have to correspond to the
2240  *  factors of the (multivariate) leading coefficient of the input polynomial
2241  *  (as defined for a specific variable x). After that the Hensel lifting can be
2242  *  performed.
2243  *
2244  *  @param[in] poly  expanded, square free polynomial
2245  *  @param[in] syms  contains the symbols in the polynomial
2246  *  @return          factorized polynomial
2247  */
2248 static ex factor_multivariate(const ex& poly, const exset& syms)
2249 {
2250         exset::const_iterator s;
2251         const ex& x = *syms.begin();
2252
2253         // make polynomial primitive
2254         ex unit, cont, pp;
2255         poly.unitcontprim(x, unit, cont, pp);
2256         if ( !is_a<numeric>(cont) ) {
2257                 return factor_sqrfree(cont) * factor_sqrfree(pp);
2258         }
2259
2260         // factor leading coefficient
2261         ex vn = pp.collect(x).lcoeff(x);
2262         ex vnlst;
2263         if ( is_a<numeric>(vn) ) {
2264                 vnlst = lst(vn);
2265         }
2266         else {
2267                 ex vnfactors = factor(vn);
2268                 vnlst = put_factors_into_lst(vnfactors);
2269         }
2270
2271         const unsigned int maxtrials = 3;
2272         numeric modulus = (vnlst.nops() > 3) ? vnlst.nops() : 3;
2273         vector<numeric> a(syms.size()-1, 0);
2274
2275         // try now to factorize until we are successful
2276         while ( true ) {
2277
2278                 unsigned int trialcount = 0;
2279                 unsigned int prime;
2280                 int factor_count = 0;
2281                 int min_factor_count = -1;
2282                 ex u, delta;
2283                 ex ufac, ufaclst;
2284
2285                 // try several evaluation points to reduce the number of factors
2286                 while ( trialcount < maxtrials ) {
2287
2288                         // generate a set of valid evaluation points
2289                         generate_set(pp, vn, syms, ex_to<lst>(vnlst), modulus, u, a);
2290
2291                         ufac = factor_univariate(u, x, prime);
2292                         ufaclst = put_factors_into_lst(ufac);
2293                         factor_count = ufaclst.nops()-1;
2294                         delta = ufaclst.op(0);
2295
2296                         if ( factor_count <= 1 ) {
2297                                 // irreducible
2298                                 return poly;
2299                         }
2300                         if ( min_factor_count < 0 ) {
2301                                 // first time here
2302                                 min_factor_count = factor_count;
2303                         }
2304                         else if ( min_factor_count == factor_count ) {
2305                                 // one less to try
2306                                 ++trialcount;
2307                         }
2308                         else if ( min_factor_count > factor_count ) {
2309                                 // new minimum, reset trial counter
2310                                 min_factor_count = factor_count;
2311                                 trialcount = 0;
2312                         }
2313                 }
2314
2315                 // determine true leading coefficients for the Hensel lifting
2316                 vector<ex> C(factor_count);
2317                 if ( is_a<numeric>(vn) ) {
2318                         // easy case
2319                         for ( size_t i=1; i<ufaclst.nops(); ++i ) {
2320                                 C[i-1] = ufaclst.op(i).lcoeff(x);
2321                         }
2322                 }
2323                 else {
2324                         // difficult case.
2325                         // we use the property of the ftilde having a unique prime factor.
2326                         // details can be found in [Wan].
2327                         // calculate ftilde
2328                         vector<numeric> ftilde(vnlst.nops()-1);
2329                         for ( size_t i=0; i<ftilde.size(); ++i ) {
2330                                 ex ft = vnlst.op(i+1);
2331                                 s = syms.begin();
2332                                 ++s;
2333                                 for ( size_t j=0; j<a.size(); ++j ) {
2334                                         ft = ft.subs(*s == a[j]);
2335                                         ++s;
2336                                 }
2337                                 ftilde[i] = ex_to<numeric>(ft);
2338                         }
2339                         // calculate D and C
2340                         vector<bool> used_flag(ftilde.size(), false);
2341                         vector<ex> D(factor_count, 1);
2342                         if ( delta == 1 ) {
2343                                 for ( int i=0; i<factor_count; ++i ) {
2344                                         numeric prefac = ex_to<numeric>(ufaclst.op(i+1).lcoeff(x));
2345                                         for ( int j=ftilde.size()-1; j>=0; --j ) {
2346                                                 int count = 0;
2347                                                 while ( irem(prefac, ftilde[j]) == 0 ) {
2348                                                         prefac = iquo(prefac, ftilde[j]);
2349                                                         ++count;
2350                                                 }
2351                                                 if ( count ) {
2352                                                         used_flag[j] = true;
2353                                                         D[i] = D[i] * pow(vnlst.op(j+1), count);
2354                                                 }
2355                                         }
2356                                         C[i] = D[i] * prefac;
2357                                 }
2358                         }
2359                         else {
2360                                 for ( int i=0; i<factor_count; ++i ) {
2361                                         numeric prefac = ex_to<numeric>(ufaclst.op(i+1).lcoeff(x));
2362                                         for ( int j=ftilde.size()-1; j>=0; --j ) {
2363                                                 int count = 0;
2364                                                 while ( irem(prefac, ftilde[j]) == 0 ) {
2365                                                         prefac = iquo(prefac, ftilde[j]);
2366                                                         ++count;
2367                                                 }
2368                                                 while ( irem(ex_to<numeric>(delta)*prefac, ftilde[j]) == 0 ) {
2369                                                         numeric g = gcd(prefac, ex_to<numeric>(ftilde[j]));
2370                                                         prefac = iquo(prefac, g);
2371                                                         delta = delta / (ftilde[j]/g);
2372                                                         ufaclst.let_op(i+1) = ufaclst.op(i+1) * (ftilde[j]/g);
2373                                                         ++count;
2374                                                 }
2375                                                 if ( count ) {
2376                                                         used_flag[j] = true;
2377                                                         D[i] = D[i] * pow(vnlst.op(j+1), count);
2378                                                 }
2379                                         }
2380                                         C[i] = D[i] * prefac;
2381                                 }
2382                         }
2383                         // check if something went wrong
2384                         bool some_factor_unused = false;
2385                         for ( size_t i=0; i<used_flag.size(); ++i ) {
2386                                 if ( !used_flag[i] ) {
2387                                         some_factor_unused = true;
2388                                         break;
2389                                 }
2390                         }
2391                         if ( some_factor_unused ) {
2392                                 continue;
2393                         }
2394                 }
2395                 
2396                 // multiply the remaining content of the univariate polynomial into the
2397                 // first factor
2398                 if ( delta != 1 ) {
2399                         C[0] = C[0] * delta;
2400                         ufaclst.let_op(1) = ufaclst.op(1) * delta;
2401                 }
2402
2403                 // set up evaluation points
2404                 EvalPoint ep;
2405                 vector<EvalPoint> epv;
2406                 s = syms.begin();
2407                 ++s;
2408                 for ( size_t i=0; i<a.size(); ++i ) {
2409                         ep.x = *s++;
2410                         ep.evalpoint = a[i].to_int();
2411                         epv.push_back(ep);
2412                 }
2413
2414                 // calc bound p^l
2415                 int maxdeg = 0;
2416                 for ( int i=1; i<=factor_count; ++i ) {
2417                         if ( ufaclst.op(i).degree(x) > maxdeg ) {
2418                                 maxdeg = ufaclst[i].degree(x);
2419                         }
2420                 }
2421                 cl_I B = 2*calc_bound(u, x, maxdeg);
2422                 cl_I l = 1;
2423                 cl_I pl = prime;
2424                 while ( pl < B ) {
2425                         l = l + 1;
2426                         pl = pl * prime;
2427                 }
2428                 
2429                 // set up modular factors (mod p^l)
2430                 cl_modint_ring R = find_modint_ring(expt_pos(cl_I(prime),l));
2431                 upvec modfactors(ufaclst.nops()-1);
2432                 for ( size_t i=1; i<ufaclst.nops(); ++i ) {
2433                         umodpoly_from_ex(modfactors[i-1], ufaclst.op(i), x, R);
2434                 }
2435
2436                 // try Hensel lifting
2437                 ex res = hensel_multivar(pp, x, epv, prime, l, modfactors, C);
2438                 if ( res != lst() ) {
2439                         ex result = cont * unit;
2440                         for ( size_t i=0; i<res.nops(); ++i ) {
2441                                 result *= res.op(i).content(x) * res.op(i).unit(x);
2442                                 result *= res.op(i).primpart(x);
2443                         }
2444                         return result;
2445                 }
2446         }
2447 }
2448
2449 /** Finds all symbols in an expression. Used by factor_sqrfree() and factor().
2450  */
2451 struct find_symbols_map : public map_function {
2452         exset syms;
2453         ex operator()(const ex& e)
2454         {
2455                 if ( is_a<symbol>(e) ) {
2456                         syms.insert(e);
2457                         return e;
2458                 }
2459                 return e.map(*this);
2460         }
2461 };
2462
2463 /** Factorizes a polynomial that is square free. It calls either the univariate
2464  *  or the multivariate factorization functions.
2465  */
2466 static ex factor_sqrfree(const ex& poly)
2467 {
2468         // determine all symbols in poly
2469         find_symbols_map findsymbols;
2470         findsymbols(poly);
2471         if ( findsymbols.syms.size() == 0 ) {
2472                 return poly;
2473         }
2474
2475         if ( findsymbols.syms.size() == 1 ) {
2476                 // univariate case
2477                 const ex& x = *(findsymbols.syms.begin());
2478                 if ( poly.ldegree(x) > 0 ) {
2479                         // pull out direct factors
2480                         int ld = poly.ldegree(x);
2481                         ex res = factor_univariate(expand(poly/pow(x, ld)), x);
2482                         return res * pow(x,ld);
2483                 }
2484                 else {
2485                         ex res = factor_univariate(poly, x);
2486                         return res;
2487                 }
2488         }
2489
2490         // multivariate case
2491         ex res = factor_multivariate(poly, findsymbols.syms);
2492         return res;
2493 }
2494
2495 /** Map used by factor() when factor_options::all is given to access all
2496  *  subexpressions and to call factor() on them.
2497  */
2498 struct apply_factor_map : public map_function {
2499         unsigned options;
2500         apply_factor_map(unsigned options_) : options(options_) { }
2501         ex operator()(const ex& e)
2502         {
2503                 if ( e.info(info_flags::polynomial) ) {
2504                         return factor(e, options);
2505                 }
2506                 if ( is_a<add>(e) ) {
2507                         ex s1, s2;
2508                         for ( size_t i=0; i<e.nops(); ++i ) {
2509                                 if ( e.op(i).info(info_flags::polynomial) ) {
2510                                         s1 += e.op(i);
2511                                 }
2512                                 else {
2513                                         s2 += e.op(i);
2514                                 }
2515                         }
2516                         s1 = s1.eval();
2517                         s2 = s2.eval();
2518                         return factor(s1, options) + s2.map(*this);
2519                 }
2520                 return e.map(*this);
2521         }
2522 };
2523
2524 } // anonymous namespace
2525
2526 /** Interface function to the outside world. It checks the arguments, tries a
2527  *  square free factorization, and then calls factor_sqrfree to do the hard
2528  *  work.
2529  */
2530 ex factor(const ex& poly, unsigned options)
2531 {
2532         // check arguments
2533         if ( !poly.info(info_flags::polynomial) ) {
2534                 if ( options & factor_options::all ) {
2535                         options &= ~factor_options::all;
2536                         apply_factor_map factor_map(options);
2537                         return factor_map(poly);
2538                 }
2539                 return poly;
2540         }
2541
2542         // determine all symbols in poly
2543         find_symbols_map findsymbols;
2544         findsymbols(poly);
2545         if ( findsymbols.syms.size() == 0 ) {
2546                 return poly;
2547         }
2548         lst syms;
2549         exset::const_iterator i=findsymbols.syms.begin(), end=findsymbols.syms.end();
2550         for ( ; i!=end; ++i ) {
2551                 syms.append(*i);
2552         }
2553
2554         // make poly square free
2555         ex sfpoly = sqrfree(poly.expand(), syms);
2556
2557         // factorize the square free components
2558         if ( is_a<power>(sfpoly) ) {
2559                 // case: (polynomial)^exponent
2560                 const ex& base = sfpoly.op(0);
2561                 if ( !is_a<add>(base) ) {
2562                         // simple case: (monomial)^exponent
2563                         return sfpoly;
2564                 }
2565                 ex f = factor_sqrfree(base);
2566                 return pow(f, sfpoly.op(1));
2567         }
2568         if ( is_a<mul>(sfpoly) ) {
2569                 // case: multiple factors
2570                 ex res = 1;
2571                 for ( size_t i=0; i<sfpoly.nops(); ++i ) {
2572                         const ex& t = sfpoly.op(i);
2573                         if ( is_a<power>(t) ) {
2574                                 const ex& base = t.op(0);
2575                                 if ( !is_a<add>(base) ) {
2576                                         res *= t;
2577                                 }
2578                                 else {
2579                                         ex f = factor_sqrfree(base);
2580                                         res *= pow(f, t.op(1));
2581                                 }
2582                         }
2583                         else if ( is_a<add>(t) ) {
2584                                 ex f = factor_sqrfree(t);
2585                                 res *= f;
2586                         }
2587                         else {
2588                                 res *= t;
2589                         }
2590                 }
2591                 return res;
2592         }
2593         if ( is_a<symbol>(sfpoly) ) {
2594                 return poly;
2595         }
2596         // case: (polynomial)
2597         ex f = factor_sqrfree(sfpoly);
2598         return f;
2599 }
2600
2601 } // namespace GiNaC
2602
2603 #ifdef DEBUGFACTOR
2604 #include "test.h"
2605 #endif