]> www.ginac.de Git - ginac.git/blob - ginac/factor.cpp
Introduce status_flags::{is_positive,is_negative,purely_indefinite}
[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-2011 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                 for ( size_t rr=0; rr<r; ++rr ) {
741                         std::size_t i = col + rr*c;
742                         if ( !zerop(m[i]) ) {
743                                 return false;
744                         }
745                 }
746                 return true;
747         }
748         bool is_row_zero(size_t row) const
749         {
750                 for ( size_t cc=0; cc<c; ++cc ) {
751                         std::size_t i = row*c + cc;
752                         if ( !zerop(m[i]) ) {
753                                 return false;
754                         }
755                 }
756                 return true;
757         }
758         void set_row(size_t row, const vector<cl_MI>& newrow)
759         {
760                 for (std::size_t i2 = 0; i2 < newrow.size(); ++i2) {
761                         std::size_t i1 = row*c + i2;
762                         m[i1] = newrow[i2];
763                 }
764         }
765         mvec::const_iterator row_begin(size_t row) const { return m.begin()+row*c; }
766         mvec::const_iterator row_end(size_t row) const { return m.begin()+row*c+r; }
767 private:
768         size_t r, c;
769         mvec m;
770 };
771
772 #ifdef DEBUGFACTOR
773 modular_matrix operator*(const modular_matrix& m1, const modular_matrix& m2)
774 {
775         const unsigned int r = m1.rowsize();
776         const unsigned int c = m2.colsize();
777         modular_matrix o(r,c,m1(0,0));
778
779         for ( size_t i=0; i<r; ++i ) {
780                 for ( size_t j=0; j<c; ++j ) {
781                         cl_MI buf;
782                         buf = m1(i,0) * m2(0,j);
783                         for ( size_t k=1; k<c; ++k ) {
784                                 buf = buf + m1(i,k)*m2(k,j);
785                         }
786                         o(i,j) = buf;
787                 }
788         }
789         return o;
790 }
791
792 ostream& operator<<(ostream& o, const modular_matrix& m)
793 {
794         cl_modint_ring R = m(0,0).ring();
795         o << "{";
796         for ( size_t i=0; i<m.rowsize(); ++i ) {
797                 o << "{";
798                 for ( size_t j=0; j<m.colsize()-1; ++j ) {
799                         o << R->retract(m(i,j)) << ",";
800                 }
801                 o << R->retract(m(i,m.colsize()-1)) << "}";
802                 if ( i != m.rowsize()-1 ) {
803                         o << ",";
804                 }
805         }
806         o << "}";
807         return o;
808 }
809 #endif // def DEBUGFACTOR
810
811 // END modular matrix
812 ////////////////////////////////////////////////////////////////////////////////
813
814 /** Calculates the Q matrix for a polynomial. Used by Berlekamp's algorithm.
815  *
816  *  @param[in]  a_  modular polynomial
817  *  @param[out] Q   Q matrix
818  */
819 static void q_matrix(const umodpoly& a_, modular_matrix& Q)
820 {
821         umodpoly a = a_;
822         normalize_in_field(a);
823
824         int n = degree(a);
825         unsigned int q = cl_I_to_uint(a[0].ring()->modulus);
826         umodpoly r(n, a[0].ring()->zero());
827         r[0] = a[0].ring()->one();
828         Q.set_row(0, r);
829         unsigned int max = (n-1) * q;
830         for ( size_t m=1; m<=max; ++m ) {
831                 cl_MI rn_1 = r.back();
832                 for ( size_t i=n-1; i>0; --i ) {
833                         r[i] = r[i-1] - (rn_1 * a[i]);
834                 }
835                 r[0] = -rn_1 * a[0];
836                 if ( (m % q) == 0 ) {
837                         Q.set_row(m/q, r);
838                 }
839         }
840 }
841
842 /** Determine the nullspace of a matrix M-1.
843  *
844  *  @param[in,out] M      matrix, will be modified
845  *  @param[out]    basis  calculated nullspace of M-1
846  */
847 static void nullspace(modular_matrix& M, vector<mvec>& basis)
848 {
849         const size_t n = M.rowsize();
850         const cl_MI one = M(0,0).ring()->one();
851         for ( size_t i=0; i<n; ++i ) {
852                 M(i,i) = M(i,i) - one;
853         }
854         for ( size_t r=0; r<n; ++r ) {
855                 size_t cc = 0;
856                 for ( ; cc<n; ++cc ) {
857                         if ( !zerop(M(r,cc)) ) {
858                                 if ( cc < r ) {
859                                         if ( !zerop(M(cc,cc)) ) {
860                                                 continue;
861                                         }
862                                         M.switch_col(cc, r);
863                                 }
864                                 else if ( cc > r ) {
865                                         M.switch_col(cc, r);
866                                 }
867                                 break;
868                         }
869                 }
870                 if ( cc < n ) {
871                         M.mul_col(r, recip(M(r,r)));
872                         for ( cc=0; cc<n; ++cc ) {
873                                 if ( cc != r ) {
874                                         M.sub_col(cc, r, M(r,cc));
875                                 }
876                         }
877                 }
878         }
879
880         for ( size_t i=0; i<n; ++i ) {
881                 M(i,i) = M(i,i) - one;
882         }
883         for ( size_t i=0; i<n; ++i ) {
884                 if ( !M.is_row_zero(i) ) {
885                         mvec nu(M.row_begin(i), M.row_end(i));
886                         basis.push_back(nu);
887                 }
888         }
889 }
890
891 /** Berlekamp's modular factorization.
892  *  
893  *  The implementation follows the algorithm in chapter 8 of [GCL].
894  *
895  *  @param[in]  a    modular polynomial
896  *  @param[out] upv  vector containing modular factors. if upv was not empty the
897  *                   new elements are added at the end
898  */
899 static void berlekamp(const umodpoly& a, upvec& upv)
900 {
901         cl_modint_ring R = a[0].ring();
902         umodpoly one(1, R->one());
903
904         // find nullspace of Q matrix
905         modular_matrix Q(degree(a), degree(a), R->zero());
906         q_matrix(a, Q);
907         vector<mvec> nu;
908         nullspace(Q, nu);
909
910         const unsigned int k = nu.size();
911         if ( k == 1 ) {
912                 // irreducible
913                 return;
914         }
915
916         list<umodpoly> factors;
917         factors.push_back(a);
918         unsigned int size = 1;
919         unsigned int r = 1;
920         unsigned int q = cl_I_to_uint(R->modulus);
921
922         list<umodpoly>::iterator u = factors.begin();
923
924         // calculate all gcd's
925         while ( true ) {
926                 for ( unsigned int s=0; s<q; ++s ) {
927                         umodpoly nur = nu[r];
928                         nur[0] = nur[0] - cl_MI(R, s);
929                         canonicalize(nur);
930                         umodpoly g;
931                         gcd(nur, *u, g);
932                         if ( unequal_one(g) && g != *u ) {
933                                 umodpoly uo;
934                                 div(*u, g, uo);
935                                 if ( equal_one(uo) ) {
936                                         throw logic_error("berlekamp: unexpected divisor.");
937                                 }
938                                 else {
939                                         *u = uo;
940                                 }
941                                 factors.push_back(g);
942                                 size = 0;
943                                 list<umodpoly>::const_iterator i = factors.begin(), end = factors.end();
944                                 while ( i != end ) {
945                                         if ( degree(*i) ) ++size; 
946                                         ++i;
947                                 }
948                                 if ( size == k ) {
949                                         list<umodpoly>::const_iterator i = factors.begin(), end = factors.end();
950                                         while ( i != end ) {
951                                                 upv.push_back(*i++);
952                                         }
953                                         return;
954                                 }
955                         }
956                 }
957                 if ( ++r == k ) {
958                         r = 1;
959                         ++u;
960                 }
961         }
962 }
963
964 // modular square free factorization is not used at the moment so we deactivate
965 // the code
966 #if 0
967
968 /** Calculates a^(1/prime).
969  *  
970  *  @param[in] a      polynomial
971  *  @param[in] prime  prime number -> exponent 1/prime
972  *  @param[in] ap     resulting polynomial
973  */
974 static void expt_1_over_p(const umodpoly& a, unsigned int prime, umodpoly& ap)
975 {
976         size_t newdeg = degree(a)/prime;
977         ap.resize(newdeg+1);
978         ap[0] = a[0];
979         for ( size_t i=1; i<=newdeg; ++i ) {
980                 ap[i] = a[i*prime];
981         }
982 }
983
984 /** Modular square free factorization.
985  *
986  *  @param[in]  a        polynomial
987  *  @param[out] factors  modular factors
988  *  @param[out] mult     corresponding multiplicities (exponents)
989  */
990 static void modsqrfree(const umodpoly& a, upvec& factors, vector<int>& mult)
991 {
992         const unsigned int prime = cl_I_to_uint(a[0].ring()->modulus);
993         int i = 1;
994         umodpoly b;
995         deriv(a, b);
996         if ( b.size() ) {
997                 umodpoly c;
998                 gcd(a, b, c);
999                 umodpoly w;
1000                 div(a, c, w);
1001                 while ( unequal_one(w) ) {
1002                         umodpoly y;
1003                         gcd(w, c, y);
1004                         umodpoly z;
1005                         div(w, y, z);
1006                         factors.push_back(z);
1007                         mult.push_back(i);
1008                         ++i;
1009                         w = y;
1010                         umodpoly buf;
1011                         div(c, y, buf);
1012                         c = buf;
1013                 }
1014                 if ( unequal_one(c) ) {
1015                         umodpoly cp;
1016                         expt_1_over_p(c, prime, cp);
1017                         size_t previ = mult.size();
1018                         modsqrfree(cp, factors, mult);
1019                         for ( size_t i=previ; i<mult.size(); ++i ) {
1020                                 mult[i] *= prime;
1021                         }
1022                 }
1023         }
1024         else {
1025                 umodpoly ap;
1026                 expt_1_over_p(a, prime, ap);
1027                 size_t previ = mult.size();
1028                 modsqrfree(ap, factors, mult);
1029                 for ( size_t i=previ; i<mult.size(); ++i ) {
1030                         mult[i] *= prime;
1031                 }
1032         }
1033 }
1034
1035 #endif // deactivation of square free factorization
1036
1037 /** Distinct degree factorization (DDF).
1038  *  
1039  *  The implementation follows the algorithm in chapter 8 of [GCL].
1040  *
1041  *  @param[in]  a_         modular polynomial
1042  *  @param[out] degrees    vector containing the degrees of the factors of the
1043  *                         corresponding polynomials in ddfactors.
1044  *  @param[out] ddfactors  vector containing polynomials which factors have the
1045  *                         degree given in degrees.
1046  */
1047 static void distinct_degree_factor(const umodpoly& a_, vector<int>& degrees, upvec& ddfactors)
1048 {
1049         umodpoly a = a_;
1050
1051         cl_modint_ring R = a[0].ring();
1052         int q = cl_I_to_int(R->modulus);
1053         int nhalf = degree(a)/2;
1054
1055         int i = 1;
1056         umodpoly w(2);
1057         w[0] = R->zero();
1058         w[1] = R->one();
1059         umodpoly x = w;
1060
1061         while ( i <= nhalf ) {
1062                 expt_pos(w, q);
1063                 umodpoly buf;
1064                 rem(w, a, buf);
1065                 w = buf;
1066                 umodpoly wx = w - x;
1067                 gcd(a, wx, buf);
1068                 if ( unequal_one(buf) ) {
1069                         degrees.push_back(i);
1070                         ddfactors.push_back(buf);
1071                 }
1072                 if ( unequal_one(buf) ) {
1073                         umodpoly buf2;
1074                         div(a, buf, buf2);
1075                         a = buf2;
1076                         nhalf = degree(a)/2;
1077                         rem(w, a, buf);
1078                         w = buf;
1079                 }
1080                 ++i;
1081         }
1082         if ( unequal_one(a) ) {
1083                 degrees.push_back(degree(a));
1084                 ddfactors.push_back(a);
1085         }
1086 }
1087
1088 /** Modular same degree factorization.
1089  *  Same degree factorization is a kind of misnomer. It performs distinct degree
1090  *  factorization, but instead of using the Cantor-Zassenhaus algorithm it
1091  *  (sub-optimally) uses Berlekamp's algorithm for the factors of the same
1092  *  degree.
1093  *
1094  *  @param[in]  a    modular polynomial
1095  *  @param[out] upv  vector containing modular factors. if upv was not empty the
1096  *                   new elements are added at the end
1097  */
1098 static void same_degree_factor(const umodpoly& a, upvec& upv)
1099 {
1100         cl_modint_ring R = a[0].ring();
1101
1102         vector<int> degrees;
1103         upvec ddfactors;
1104         distinct_degree_factor(a, degrees, ddfactors);
1105
1106         for ( size_t i=0; i<degrees.size(); ++i ) {
1107                 if ( degrees[i] == degree(ddfactors[i]) ) {
1108                         upv.push_back(ddfactors[i]);
1109                 }
1110                 else {
1111                         berlekamp(ddfactors[i], upv);
1112                 }
1113         }
1114 }
1115
1116 // Yes, we can (choose).
1117 #define USE_SAME_DEGREE_FACTOR
1118
1119 /** Modular univariate factorization.
1120  *
1121  *  In principle, we have two algorithms at our disposal: Berlekamp's algorithm
1122  *  and same degree factorization (SDF). SDF seems to be slightly faster in
1123  *  almost all cases so it is activated as default.
1124  *
1125  *  @param[in]  p    modular polynomial
1126  *  @param[out] upv  vector containing modular factors. if upv was not empty the
1127  *                   new elements are added at the end
1128  */
1129 static void factor_modular(const umodpoly& p, upvec& upv)
1130 {
1131 #ifdef USE_SAME_DEGREE_FACTOR
1132         same_degree_factor(p, upv);
1133 #else
1134         berlekamp(p, upv);
1135 #endif
1136 }
1137
1138 /** Calculates modular polynomials s and t such that a*s+b*t==1.
1139  *  Assertion: a and b are relatively prime and not zero.
1140  *
1141  *  @param[in]  a  polynomial
1142  *  @param[in]  b  polynomial
1143  *  @param[out] s  polynomial
1144  *  @param[out] t  polynomial
1145  */
1146 static void exteuclid(const umodpoly& a, const umodpoly& b, umodpoly& s, umodpoly& t)
1147 {
1148         if ( degree(a) < degree(b) ) {
1149                 exteuclid(b, a, t, s);
1150                 return;
1151         }
1152
1153         umodpoly one(1, a[0].ring()->one());
1154         umodpoly c = a; normalize_in_field(c);
1155         umodpoly d = b; normalize_in_field(d);
1156         s = one;
1157         t.clear();
1158         umodpoly d1;
1159         umodpoly d2 = one;
1160         umodpoly q;
1161         while ( true ) {
1162                 div(c, d, q);
1163                 umodpoly r = c - q * d;
1164                 umodpoly r1 = s - q * d1;
1165                 umodpoly r2 = t - q * d2;
1166                 c = d;
1167                 s = d1;
1168                 t = d2;
1169                 if ( r.empty() ) break;
1170                 d = r;
1171                 d1 = r1;
1172                 d2 = r2;
1173         }
1174         cl_MI fac = recip(lcoeff(a) * lcoeff(c));
1175         umodpoly::iterator i = s.begin(), end = s.end();
1176         for ( ; i!=end; ++i ) {
1177                 *i = *i * fac;
1178         }
1179         canonicalize(s);
1180         fac = recip(lcoeff(b) * lcoeff(c));
1181         i = t.begin(), end = t.end();
1182         for ( ; i!=end; ++i ) {
1183                 *i = *i * fac;
1184         }
1185         canonicalize(t);
1186 }
1187
1188 /** Replaces the leading coefficient in a polynomial by a given number.
1189  *
1190  *  @param[in] poly  polynomial to change
1191  *  @param[in] lc    new leading coefficient
1192  *  @return          changed polynomial
1193  */
1194 static upoly replace_lc(const upoly& poly, const cl_I& lc)
1195 {
1196         if ( poly.empty() ) return poly;
1197         upoly r = poly;
1198         r.back() = lc;
1199         return r;
1200 }
1201
1202 /** Calculates the bound for the modulus.
1203  *  See [Mig].
1204  */
1205 static inline cl_I calc_bound(const ex& a, const ex& x, int maxdeg)
1206 {
1207         cl_I maxcoeff = 0;
1208         cl_R coeff = 0;
1209         for ( int i=a.degree(x); i>=a.ldegree(x); --i ) {
1210                 cl_I aa = abs(the<cl_I>(ex_to<numeric>(a.coeff(x, i)).to_cl_N()));
1211                 if ( aa > maxcoeff ) maxcoeff = aa;
1212                 coeff = coeff + square(aa);
1213         }
1214         cl_I coeffnorm = ceiling1(the<cl_R>(cln::sqrt(coeff)));
1215         cl_I B = coeffnorm * expt_pos(cl_I(2), cl_I(maxdeg));
1216         return ( B > maxcoeff ) ? B : maxcoeff;
1217 }
1218
1219 /** Calculates the bound for the modulus.
1220  *  See [Mig].
1221  */
1222 static inline cl_I calc_bound(const upoly& a, int maxdeg)
1223 {
1224         cl_I maxcoeff = 0;
1225         cl_R coeff = 0;
1226         for ( int i=degree(a); i>=0; --i ) {
1227                 cl_I aa = abs(a[i]);
1228                 if ( aa > maxcoeff ) maxcoeff = aa;
1229                 coeff = coeff + square(aa);
1230         }
1231         cl_I coeffnorm = ceiling1(the<cl_R>(cln::sqrt(coeff)));
1232         cl_I B = coeffnorm * expt_pos(cl_I(2), cl_I(maxdeg));
1233         return ( B > maxcoeff ) ? B : maxcoeff;
1234 }
1235
1236 /** Hensel lifting as used by factor_univariate().
1237  *
1238  *  The implementation follows the algorithm in chapter 6 of [GCL].
1239  *
1240  *  @param[in]  a_   primitive univariate polynomials
1241  *  @param[in]  p    prime number that does not divide lcoeff(a)
1242  *  @param[in]  u1_  modular factor of a (mod p)
1243  *  @param[in]  w1_  modular factor of a (mod p), relatively prime to u1_,
1244  *                   fulfilling  u1_*w1_ == a mod p
1245  *  @param[out] u    lifted factor
1246  *  @param[out] w    lifted factor, u*w = a
1247  */
1248 static void hensel_univar(const upoly& a_, unsigned int p, const umodpoly& u1_, const umodpoly& w1_, upoly& u, upoly& w)
1249 {
1250         upoly a = a_;
1251         const cl_modint_ring& R = u1_[0].ring();
1252
1253         // calc bound B
1254         int maxdeg = (degree(u1_) > degree(w1_)) ? degree(u1_) : degree(w1_);
1255         cl_I maxmodulus = 2*calc_bound(a, maxdeg);
1256
1257         // step 1
1258         cl_I alpha = lcoeff(a);
1259         a = a * alpha;
1260         umodpoly nu1 = u1_;
1261         normalize_in_field(nu1);
1262         umodpoly nw1 = w1_;
1263         normalize_in_field(nw1);
1264         upoly phi;
1265         phi = umodpoly_to_upoly(nu1) * alpha;
1266         umodpoly u1;
1267         umodpoly_from_upoly(u1, phi, R);
1268         phi = umodpoly_to_upoly(nw1) * alpha;
1269         umodpoly w1;
1270         umodpoly_from_upoly(w1, phi, R);
1271
1272         // step 2
1273         umodpoly s;
1274         umodpoly t;
1275         exteuclid(u1, w1, s, t);
1276
1277         // step 3
1278         u = replace_lc(umodpoly_to_upoly(u1), alpha);
1279         w = replace_lc(umodpoly_to_upoly(w1), alpha);
1280         upoly e = a - u * w;
1281         cl_I modulus = p;
1282
1283         // step 4
1284         while ( !e.empty() && modulus < maxmodulus ) {
1285                 upoly c = e / modulus;
1286                 phi = umodpoly_to_upoly(s) * c;
1287                 umodpoly sigmatilde;
1288                 umodpoly_from_upoly(sigmatilde, phi, R);
1289                 phi = umodpoly_to_upoly(t) * c;
1290                 umodpoly tautilde;
1291                 umodpoly_from_upoly(tautilde, phi, R);
1292                 umodpoly r, q;
1293                 remdiv(sigmatilde, w1, r, q);
1294                 umodpoly sigma = r;
1295                 phi = umodpoly_to_upoly(tautilde) + umodpoly_to_upoly(q) * umodpoly_to_upoly(u1);
1296                 umodpoly tau;
1297                 umodpoly_from_upoly(tau, phi, R);
1298                 u = u + umodpoly_to_upoly(tau) * modulus;
1299                 w = w + umodpoly_to_upoly(sigma) * modulus;
1300                 e = a - u * w;
1301                 modulus = modulus * p;
1302         }
1303
1304         // step 5
1305         if ( e.empty() ) {
1306                 cl_I g = u[0];
1307                 for ( size_t i=1; i<u.size(); ++i ) {
1308                         g = gcd(g, u[i]);
1309                         if ( g == 1 ) break;
1310                 }
1311                 if ( g != 1 ) {
1312                         u = u / g;
1313                         w = w * g;
1314                 }
1315                 if ( alpha != 1 ) {
1316                         w = w / alpha;
1317                 }
1318         }
1319         else {
1320                 u.clear();
1321         }
1322 }
1323
1324 /** Returns a new prime number.
1325  *
1326  *  @param[in] p  prime number
1327  *  @return       next prime number after p
1328  */
1329 static unsigned int next_prime(unsigned int p)
1330 {
1331         static vector<unsigned int> primes;
1332         if ( primes.size() == 0 ) {
1333                 primes.push_back(3); primes.push_back(5); primes.push_back(7);
1334         }
1335         vector<unsigned int>::const_iterator it = primes.begin();
1336         if ( p >= primes.back() ) {
1337                 unsigned int candidate = primes.back() + 2;
1338                 while ( true ) {
1339                         size_t n = primes.size()/2;
1340                         for ( size_t i=0; i<n; ++i ) {
1341                                 if ( candidate % primes[i] ) continue;
1342                                 candidate += 2;
1343                                 i=-1;
1344                         }
1345                         primes.push_back(candidate);
1346                         if ( candidate > p ) break;
1347                 }
1348                 return candidate;
1349         }
1350         vector<unsigned int>::const_iterator end = primes.end();
1351         for ( ; it!=end; ++it ) {
1352                 if ( *it > p ) {
1353                         return *it;
1354                 }
1355         }
1356         throw logic_error("next_prime: should not reach this point!");
1357 }
1358
1359 /** Manages the splitting a vector of of modular factors into two partitions.
1360  */
1361 class factor_partition
1362 {
1363 public:
1364         /** Takes the vector of modular factors and initializes the first partition */
1365         factor_partition(const upvec& factors_) : factors(factors_)
1366         {
1367                 n = factors.size();
1368                 k.resize(n, 0);
1369                 k[0] = 1;
1370                 cache.resize(n-1);
1371                 one.resize(1, factors.front()[0].ring()->one());
1372                 len = 1;
1373                 last = 0;
1374                 split();
1375         }
1376         int operator[](size_t i) const { return k[i]; }
1377         size_t size() const { return n; }
1378         size_t size_left() const { return n-len; }
1379         size_t size_right() const { return len; }
1380         /** Initializes the next partition.
1381             Returns true, if there is one, false otherwise. */
1382         bool next()
1383         {
1384                 if ( last == n-1 ) {
1385                         int rem = len - 1;
1386                         int p = last - 1;
1387                         while ( rem ) {
1388                                 if ( k[p] ) {
1389                                         --rem;
1390                                         --p;
1391                                         continue;
1392                                 }
1393                                 last = p - 1;
1394                                 while ( k[last] == 0 ) { --last; }
1395                                 if ( last == 0 && n == 2*len ) return false;
1396                                 k[last++] = 0;
1397                                 for ( size_t i=0; i<=len-rem; ++i ) {
1398                                         k[last] = 1;
1399                                         ++last;
1400                                 }
1401                                 fill(k.begin()+last, k.end(), 0);
1402                                 --last;
1403                                 split();
1404                                 return true;
1405                         }
1406                         last = len;
1407                         ++len;
1408                         if ( len > n/2 ) return false;
1409                         fill(k.begin(), k.begin()+len, 1);
1410                         fill(k.begin()+len+1, k.end(), 0);
1411                 }
1412                 else {
1413                         k[last++] = 0;
1414                         k[last] = 1;
1415                 }
1416                 split();
1417                 return true;
1418         }
1419         /** Get first partition */
1420         umodpoly& left() { return lr[0]; }
1421         /** Get second partition */
1422         umodpoly& right() { return lr[1]; }
1423 private:
1424         void split_cached()
1425         {
1426                 size_t i = 0;
1427                 do {
1428                         size_t pos = i;
1429                         int group = k[i++];
1430                         size_t d = 0;
1431                         while ( i < n && k[i] == group ) { ++d; ++i; }
1432                         if ( d ) {
1433                                 if ( cache[pos].size() >= d ) {
1434                                         lr[group] = lr[group] * cache[pos][d-1];
1435                                 }
1436                                 else {
1437                                         if ( cache[pos].size() == 0 ) {
1438                                                 cache[pos].push_back(factors[pos] * factors[pos+1]);
1439                                         }
1440                                         size_t j = pos + cache[pos].size() + 1;
1441                                         d -= cache[pos].size();
1442                                         while ( d ) {
1443                                                 umodpoly buf = cache[pos].back() * factors[j];
1444                                                 cache[pos].push_back(buf);
1445                                                 --d;
1446                                                 ++j;
1447                                         }
1448                                         lr[group] = lr[group] * cache[pos].back();
1449                                 }
1450                         }
1451                         else {
1452                                 lr[group] = lr[group] * factors[pos];
1453                         }
1454                 } while ( i < n );
1455         }
1456         void split()
1457         {
1458                 lr[0] = one;
1459                 lr[1] = one;
1460                 if ( n > 6 ) {
1461                         split_cached();
1462                 }
1463                 else {
1464                         for ( size_t i=0; i<n; ++i ) {
1465                                 lr[k[i]] = lr[k[i]] * factors[i];
1466                         }
1467                 }
1468         }
1469 private:
1470         umodpoly lr[2];
1471         vector< vector<umodpoly> > cache;
1472         upvec factors;
1473         umodpoly one;
1474         size_t n;
1475         size_t len;
1476         size_t last;
1477         vector<int> k;
1478 };
1479
1480 /** Contains a pair of univariate polynomial and its modular factors.
1481  *  Used by factor_univariate().
1482  */
1483 struct ModFactors
1484 {
1485         upoly poly;
1486         upvec factors;
1487 };
1488
1489 /** Univariate polynomial factorization.
1490  *
1491  *  Modular factorization is tried for several primes to minimize the number of
1492  *  modular factors. Then, Hensel lifting is performed.
1493  *
1494  *  @param[in]     poly   expanded square free univariate polynomial
1495  *  @param[in]     x      symbol
1496  *  @param[in,out] prime  prime number to start trying modular factorization with,
1497  *                        output value is the prime number actually used
1498  */
1499 static ex factor_univariate(const ex& poly, const ex& x, unsigned int& prime)
1500 {
1501         ex unit, cont, prim_ex;
1502         poly.unitcontprim(x, unit, cont, prim_ex);
1503         upoly prim;
1504         upoly_from_ex(prim, prim_ex, x);
1505
1506         // determine proper prime and minimize number of modular factors
1507         prime = 3;
1508         unsigned int lastp = prime;
1509         cl_modint_ring R;
1510         unsigned int trials = 0;
1511         unsigned int minfactors = 0;
1512
1513         const numeric& cont_n = ex_to<numeric>(cont);
1514         cl_I i_cont;
1515         if (cont_n.is_integer()) {
1516                 i_cont = the<cl_I>(cont_n.to_cl_N());
1517         } else {
1518                 // poly \in Q[x] => poly = q ipoly, ipoly \in Z[x], q \in Q
1519                 // factor(poly) \equiv q factor(ipoly)
1520                 i_cont = cl_I(1);
1521         }
1522         cl_I lc = lcoeff(prim)*i_cont;
1523         upvec factors;
1524         while ( trials < 2 ) {
1525                 umodpoly modpoly;
1526                 while ( true ) {
1527                         prime = next_prime(prime);
1528                         if ( !zerop(rem(lc, prime)) ) {
1529                                 R = find_modint_ring(prime);
1530                                 umodpoly_from_upoly(modpoly, prim, R);
1531                                 if ( squarefree(modpoly) ) break;
1532                         }
1533                 }
1534
1535                 // do modular factorization
1536                 upvec trialfactors;
1537                 factor_modular(modpoly, trialfactors);
1538                 if ( trialfactors.size() <= 1 ) {
1539                         // irreducible for sure
1540                         return poly;
1541                 }
1542
1543                 if ( minfactors == 0 || trialfactors.size() < minfactors ) {
1544                         factors = trialfactors;
1545                         minfactors = trialfactors.size();
1546                         lastp = prime;
1547                         trials = 1;
1548                 }
1549                 else {
1550                         ++trials;
1551                 }
1552         }
1553         prime = lastp;
1554         R = find_modint_ring(prime);
1555
1556         // lift all factor combinations
1557         stack<ModFactors> tocheck;
1558         ModFactors mf;
1559         mf.poly = prim;
1560         mf.factors = factors;
1561         tocheck.push(mf);
1562         upoly f1, f2;
1563         ex result = 1;
1564         while ( tocheck.size() ) {
1565                 const size_t n = tocheck.top().factors.size();
1566                 factor_partition part(tocheck.top().factors);
1567                 while ( true ) {
1568                         // call Hensel lifting
1569                         hensel_univar(tocheck.top().poly, prime, part.left(), part.right(), f1, f2);
1570                         if ( !f1.empty() ) {
1571                                 // successful, update the stack and the result
1572                                 if ( part.size_left() == 1 ) {
1573                                         if ( part.size_right() == 1 ) {
1574                                                 result *= upoly_to_ex(f1, x) * upoly_to_ex(f2, x);
1575                                                 tocheck.pop();
1576                                                 break;
1577                                         }
1578                                         result *= upoly_to_ex(f1, x);
1579                                         tocheck.top().poly = f2;
1580                                         for ( size_t i=0; i<n; ++i ) {
1581                                                 if ( part[i] == 0 ) {
1582                                                         tocheck.top().factors.erase(tocheck.top().factors.begin()+i);
1583                                                         break;
1584                                                 }
1585                                         }
1586                                         break;
1587                                 }
1588                                 else if ( part.size_right() == 1 ) {
1589                                         if ( part.size_left() == 1 ) {
1590                                                 result *= upoly_to_ex(f1, x) * upoly_to_ex(f2, x);
1591                                                 tocheck.pop();
1592                                                 break;
1593                                         }
1594                                         result *= upoly_to_ex(f2, x);
1595                                         tocheck.top().poly = f1;
1596                                         for ( size_t i=0; i<n; ++i ) {
1597                                                 if ( part[i] == 1 ) {
1598                                                         tocheck.top().factors.erase(tocheck.top().factors.begin()+i);
1599                                                         break;
1600                                                 }
1601                                         }
1602                                         break;
1603                                 }
1604                                 else {
1605                                         upvec newfactors1(part.size_left()), newfactors2(part.size_right());
1606                                         upvec::iterator i1 = newfactors1.begin(), i2 = newfactors2.begin();
1607                                         for ( size_t i=0; i<n; ++i ) {
1608                                                 if ( part[i] ) {
1609                                                         *i2++ = tocheck.top().factors[i];
1610                                                 }
1611                                                 else {
1612                                                         *i1++ = tocheck.top().factors[i];
1613                                                 }
1614                                         }
1615                                         tocheck.top().factors = newfactors1;
1616                                         tocheck.top().poly = f1;
1617                                         ModFactors mf;
1618                                         mf.factors = newfactors2;
1619                                         mf.poly = f2;
1620                                         tocheck.push(mf);
1621                                         break;
1622                                 }
1623                         }
1624                         else {
1625                                 // not successful
1626                                 if ( !part.next() ) {
1627                                         // if no more combinations left, return polynomial as
1628                                         // irreducible
1629                                         result *= upoly_to_ex(tocheck.top().poly, x);
1630                                         tocheck.pop();
1631                                         break;
1632                                 }
1633                         }
1634                 }
1635         }
1636
1637         return unit * cont * result;
1638 }
1639
1640 /** Second interface to factor_univariate() to be used if the information about
1641  *  the prime is not needed.
1642  */
1643 static inline ex factor_univariate(const ex& poly, const ex& x)
1644 {
1645         unsigned int prime;
1646         return factor_univariate(poly, x, prime);
1647 }
1648
1649 /** Represents an evaluation point (<symbol>==<integer>).
1650  */
1651 struct EvalPoint
1652 {
1653         ex x;
1654         int evalpoint;
1655 };
1656
1657 #ifdef DEBUGFACTOR
1658 ostream& operator<<(ostream& o, const vector<EvalPoint>& v)
1659 {
1660         for ( size_t i=0; i<v.size(); ++i ) {
1661                 o << "(" << v[i].x << "==" << v[i].evalpoint << ") ";
1662         }
1663         return o;
1664 }
1665 #endif // def DEBUGFACTOR
1666
1667 // forward declaration
1668 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);
1669
1670 /** Utility function for multivariate Hensel lifting.
1671  *
1672  *  Solves the equation
1673  *    s_1*b_1 + ... + s_r*b_r == 1 mod p^k
1674  *  with deg(s_i) < deg(a_i)
1675  *  and with given b_1 = a_1 * ... * a_{i-1} * a_{i+1} * ... * a_r
1676  *
1677  *  The implementation follows the algorithm in chapter 6 of [GCL].
1678  *
1679  *  @param[in]  a   vector of modular univariate polynomials
1680  *  @param[in]  x   symbol
1681  *  @param[in]  p   prime number
1682  *  @param[in]  k   p^k is modulus
1683  *  @return         vector of polynomials (s_i)
1684  */
1685 static upvec multiterm_eea_lift(const upvec& a, const ex& x, unsigned int p, unsigned int k)
1686 {
1687         const size_t r = a.size();
1688         cl_modint_ring R = find_modint_ring(expt_pos(cl_I(p),k));
1689         upvec q(r-1);
1690         q[r-2] = a[r-1];
1691         for ( size_t j=r-2; j>=1; --j ) {
1692                 q[j-1] = a[j] * q[j];
1693         }
1694         umodpoly beta(1, R->one());
1695         upvec s;
1696         for ( size_t j=1; j<r; ++j ) {
1697                 vector<ex> mdarg(2);
1698                 mdarg[0] = umodpoly_to_ex(q[j-1], x);
1699                 mdarg[1] = umodpoly_to_ex(a[j-1], x);
1700                 vector<EvalPoint> empty;
1701                 vector<ex> exsigma = multivar_diophant(mdarg, x, umodpoly_to_ex(beta, x), empty, 0, p, k);
1702                 umodpoly sigma1;
1703                 umodpoly_from_ex(sigma1, exsigma[0], x, R);
1704                 umodpoly sigma2;
1705                 umodpoly_from_ex(sigma2, exsigma[1], x, R);
1706                 beta = sigma1;
1707                 s.push_back(sigma2);
1708         }
1709         s.push_back(beta);
1710         return s;
1711 }
1712
1713 /** Changes the modulus of a modular polynomial. Used by eea_lift().
1714  *
1715  *  @param[in]     R  new modular ring
1716  *  @param[in,out] a  polynomial to change (in situ)
1717  */
1718 static void change_modulus(const cl_modint_ring& R, umodpoly& a)
1719 {
1720         if ( a.empty() ) return;
1721         cl_modint_ring oldR = a[0].ring();
1722         umodpoly::iterator i = a.begin(), end = a.end();
1723         for ( ; i!=end; ++i ) {
1724                 *i = R->canonhom(oldR->retract(*i));
1725         }
1726         canonicalize(a);
1727 }
1728
1729 /** Utility function for multivariate Hensel lifting.
1730  *
1731  *  Solves  s*a + t*b == 1 mod p^k  given a,b.
1732  *
1733  *  The implementation follows the algorithm in chapter 6 of [GCL].
1734  *
1735  *  @param[in]  a   polynomial
1736  *  @param[in]  b   polynomial
1737  *  @param[in]  x   symbol
1738  *  @param[in]  p   prime number
1739  *  @param[in]  k   p^k is modulus
1740  *  @param[out] s_  output polynomial
1741  *  @param[out] t_  output polynomial
1742  */
1743 static void eea_lift(const umodpoly& a, const umodpoly& b, const ex& x, unsigned int p, unsigned int k, umodpoly& s_, umodpoly& t_)
1744 {
1745         cl_modint_ring R = find_modint_ring(p);
1746         umodpoly amod = a;
1747         change_modulus(R, amod);
1748         umodpoly bmod = b;
1749         change_modulus(R, bmod);
1750
1751         umodpoly smod;
1752         umodpoly tmod;
1753         exteuclid(amod, bmod, smod, tmod);
1754
1755         cl_modint_ring Rpk = find_modint_ring(expt_pos(cl_I(p),k));
1756         umodpoly s = smod;
1757         change_modulus(Rpk, s);
1758         umodpoly t = tmod;
1759         change_modulus(Rpk, t);
1760
1761         cl_I modulus(p);
1762         umodpoly one(1, Rpk->one());
1763         for ( size_t j=1; j<k; ++j ) {
1764                 umodpoly e = one - a * s - b * t;
1765                 reduce_coeff(e, modulus);
1766                 umodpoly c = e;
1767                 change_modulus(R, c);
1768                 umodpoly sigmabar = smod * c;
1769                 umodpoly taubar = tmod * c;
1770                 umodpoly sigma, q;
1771                 remdiv(sigmabar, bmod, sigma, q);
1772                 umodpoly tau = taubar + q * amod;
1773                 umodpoly sadd = sigma;
1774                 change_modulus(Rpk, sadd);
1775                 cl_MI modmodulus(Rpk, modulus);
1776                 s = s + sadd * modmodulus;
1777                 umodpoly tadd = tau;
1778                 change_modulus(Rpk, tadd);
1779                 t = t + tadd * modmodulus;
1780                 modulus = modulus * p;
1781         }
1782
1783         s_ = s; t_ = t;
1784 }
1785
1786 /** Utility function for multivariate Hensel lifting.
1787  *
1788  *  Solves the equation
1789  *    s_1*b_1 + ... + s_r*b_r == x^m mod p^k
1790  *  with given b_1 = a_1 * ... * a_{i-1} * a_{i+1} * ... * a_r
1791  *
1792  *  The implementation follows the algorithm in chapter 6 of [GCL].
1793  *
1794  *  @param a  vector with univariate polynomials mod p^k
1795  *  @param x  symbol
1796  *  @param m  exponent of x^m in the equation to solve
1797  *  @param p  prime number
1798  *  @param k  p^k is modulus
1799  *  @return   vector of polynomials (s_i)
1800  */
1801 static upvec univar_diophant(const upvec& a, const ex& x, unsigned int m, unsigned int p, unsigned int k)
1802 {
1803         cl_modint_ring R = find_modint_ring(expt_pos(cl_I(p),k));
1804
1805         const size_t r = a.size();
1806         upvec result;
1807         if ( r > 2 ) {
1808                 upvec s = multiterm_eea_lift(a, x, p, k);
1809                 for ( size_t j=0; j<r; ++j ) {
1810                         umodpoly bmod = umodpoly_to_umodpoly(s[j], R, m);
1811                         umodpoly buf;
1812                         rem(bmod, a[j], buf);
1813                         result.push_back(buf);
1814                 }
1815         }
1816         else {
1817                 umodpoly s, t;
1818                 eea_lift(a[1], a[0], x, p, k, s, t);
1819                 umodpoly bmod = umodpoly_to_umodpoly(s, R, m);
1820                 umodpoly buf, q;
1821                 remdiv(bmod, a[0], buf, q);
1822                 result.push_back(buf);
1823                 umodpoly t1mod = umodpoly_to_umodpoly(t, R, m);
1824                 buf = t1mod + q * a[1];
1825                 result.push_back(buf);
1826         }
1827
1828         return result;
1829 }
1830
1831 /** Map used by function make_modular().
1832  *  Finds every coefficient in a polynomial and replaces it by is value in the
1833  *  given modular ring R (symmetric representation).
1834  */
1835 struct make_modular_map : public map_function {
1836         cl_modint_ring R;
1837         make_modular_map(const cl_modint_ring& R_) : R(R_) { }
1838         ex operator()(const ex& e)
1839         {
1840                 if ( is_a<add>(e) || is_a<mul>(e) ) {
1841                         return e.map(*this);
1842                 }
1843                 else if ( is_a<numeric>(e) ) {
1844                         numeric mod(R->modulus);
1845                         numeric halfmod = (mod-1)/2;
1846                         cl_MI emod = R->canonhom(the<cl_I>(ex_to<numeric>(e).to_cl_N()));
1847                         numeric n(R->retract(emod));
1848                         if ( n > halfmod ) {
1849                                 return n-mod;
1850                         }
1851                         else {
1852                                 return n;
1853                         }
1854                 }
1855                 return e;
1856         }
1857 };
1858
1859 /** Helps mimicking modular multivariate polynomial arithmetic.
1860  *
1861  *  @param e  expression of which to make the coefficients equal to their value
1862  *            in the modular ring R (symmetric representation)
1863  *  @param R  modular ring
1864  *  @return   resulting expression
1865  */
1866 static ex make_modular(const ex& e, const cl_modint_ring& R)
1867 {
1868         make_modular_map map(R);
1869         return map(e.expand());
1870 }
1871
1872 /** Utility function for multivariate Hensel lifting.
1873  *
1874  *  Returns the polynomials s_i that fulfill
1875  *    s_1*b_1 + ... + s_r*b_r == c mod <I^(d+1),p^k>
1876  *  with given b_1 = a_1 * ... * a_{i-1} * a_{i+1} * ... * a_r
1877  *
1878  *  The implementation follows the algorithm in chapter 6 of [GCL].
1879  *
1880  *  @param a_  vector of multivariate factors mod p^k
1881  *  @param x   symbol (equiv. x_1 in [GCL])
1882  *  @param c   polynomial mod p^k
1883  *  @param I   vector of evaluation points
1884  *  @param d   maximum total degree of result
1885  *  @param p   prime number
1886  *  @param k   p^k is modulus
1887  *  @return    vector of polynomials (s_i)
1888  */
1889 static vector<ex> multivar_diophant(const vector<ex>& a_, const ex& x, const ex& c, const vector<EvalPoint>& I,
1890                                     unsigned int d, unsigned int p, unsigned int k)
1891 {
1892         vector<ex> a = a_;
1893
1894         const cl_modint_ring R = find_modint_ring(expt_pos(cl_I(p),k));
1895         const size_t r = a.size();
1896         const size_t nu = I.size() + 1;
1897
1898         vector<ex> sigma;
1899         if ( nu > 1 ) {
1900                 ex xnu = I.back().x;
1901                 int alphanu = I.back().evalpoint;
1902
1903                 ex A = 1;
1904                 for ( size_t i=0; i<r; ++i ) {
1905                         A *= a[i];
1906                 }
1907                 vector<ex> b(r);
1908                 for ( size_t i=0; i<r; ++i ) {
1909                         b[i] = normal(A / a[i]);
1910                 }
1911
1912                 vector<ex> anew = a;
1913                 for ( size_t i=0; i<r; ++i ) {
1914                         anew[i] = anew[i].subs(xnu == alphanu);
1915                 }
1916                 ex cnew = c.subs(xnu == alphanu);
1917                 vector<EvalPoint> Inew = I;
1918                 Inew.pop_back();
1919                 sigma = multivar_diophant(anew, x, cnew, Inew, d, p, k);
1920
1921                 ex buf = c;
1922                 for ( size_t i=0; i<r; ++i ) {
1923                         buf -= sigma[i] * b[i];
1924                 }
1925                 ex e = make_modular(buf, R);
1926
1927                 ex monomial = 1;
1928                 for ( size_t m=1; !e.is_zero() && e.has(xnu) && m<=d; ++m ) {
1929                         monomial *= (xnu - alphanu);
1930                         monomial = expand(monomial);
1931                         ex cm = e.diff(ex_to<symbol>(xnu), m).subs(xnu==alphanu) / factorial(m);
1932                         cm = make_modular(cm, R);
1933                         if ( !cm.is_zero() ) {
1934                                 vector<ex> delta_s = multivar_diophant(anew, x, cm, Inew, d, p, k);
1935                                 ex buf = e;
1936                                 for ( size_t j=0; j<delta_s.size(); ++j ) {
1937                                         delta_s[j] *= monomial;
1938                                         sigma[j] += delta_s[j];
1939                                         buf -= delta_s[j] * b[j];
1940                                 }
1941                                 e = make_modular(buf, R);
1942                         }
1943                 }
1944         }
1945         else {
1946                 upvec amod;
1947                 for ( size_t i=0; i<a.size(); ++i ) {
1948                         umodpoly up;
1949                         umodpoly_from_ex(up, a[i], x, R);
1950                         amod.push_back(up);
1951                 }
1952
1953                 sigma.insert(sigma.begin(), r, 0);
1954                 size_t nterms;
1955                 ex z;
1956                 if ( is_a<add>(c) ) {
1957                         nterms = c.nops();
1958                         z = c.op(0);
1959                 }
1960                 else {
1961                         nterms = 1;
1962                         z = c;
1963                 }
1964                 for ( size_t i=0; i<nterms; ++i ) {
1965                         int m = z.degree(x);
1966                         cl_I cm = the<cl_I>(ex_to<numeric>(z.lcoeff(x)).to_cl_N());
1967                         upvec delta_s = univar_diophant(amod, x, m, p, k);
1968                         cl_MI modcm;
1969                         cl_I poscm = cm;
1970                         while ( poscm < 0 ) {
1971                                 poscm = poscm + expt_pos(cl_I(p),k);
1972                         }
1973                         modcm = cl_MI(R, poscm);
1974                         for ( size_t j=0; j<delta_s.size(); ++j ) {
1975                                 delta_s[j] = delta_s[j] * modcm;
1976                                 sigma[j] = sigma[j] + umodpoly_to_ex(delta_s[j], x);
1977                         }
1978                         if ( nterms > 1 ) {
1979                                 z = c.op(i+1);
1980                         }
1981                 }
1982         }
1983
1984         for ( size_t i=0; i<sigma.size(); ++i ) {
1985                 sigma[i] = make_modular(sigma[i], R);
1986         }
1987
1988         return sigma;
1989 }
1990
1991 /** Multivariate Hensel lifting.
1992  *  The implementation follows the algorithm in chapter 6 of [GCL].
1993  *  Since we don't have a data type for modular multivariate polynomials, the
1994  *  respective operations are done in a GiNaC::ex and the function
1995  *  make_modular() is then called to make the coefficient modular p^l.
1996  *
1997  *  @param a    multivariate polynomial primitive in x
1998  *  @param x    symbol (equiv. x_1 in [GCL])
1999  *  @param I    vector of evaluation points (x_2==a_2,x_3==a_3,...)
2000  *  @param p    prime number (should not divide lcoeff(a mod I))
2001  *  @param l    p^l is the modulus of the lifted univariate field
2002  *  @param u    vector of modular (mod p^l) factors of a mod I
2003  *  @param lcU  correct leading coefficient of the univariate factors of a mod I
2004  *  @return     list GiNaC::lst with lifted factors (multivariate factors of a),
2005  *              empty if Hensel lifting did not succeed
2006  */
2007 static ex hensel_multivar(const ex& a, const ex& x, const vector<EvalPoint>& I,
2008                           unsigned int p, const cl_I& l, const upvec& u, const vector<ex>& lcU)
2009 {
2010         const size_t nu = I.size() + 1;
2011         const cl_modint_ring R = find_modint_ring(expt_pos(cl_I(p),l));
2012
2013         vector<ex> A(nu);
2014         A[nu-1] = a;
2015
2016         for ( size_t j=nu; j>=2; --j ) {
2017                 ex x = I[j-2].x;
2018                 int alpha = I[j-2].evalpoint;
2019                 A[j-2] = A[j-1].subs(x==alpha);
2020                 A[j-2] = make_modular(A[j-2], R);
2021         }
2022
2023         int maxdeg = a.degree(I.front().x);
2024         for ( size_t i=1; i<I.size(); ++i ) {
2025                 int maxdeg2 = a.degree(I[i].x);
2026                 if ( maxdeg2 > maxdeg ) maxdeg = maxdeg2;
2027         }
2028
2029         const size_t n = u.size();
2030         vector<ex> U(n);
2031         for ( size_t i=0; i<n; ++i ) {
2032                 U[i] = umodpoly_to_ex(u[i], x);
2033         }
2034
2035         for ( size_t j=2; j<=nu; ++j ) {
2036                 vector<ex> U1 = U;
2037                 ex monomial = 1;
2038                 for ( size_t m=0; m<n; ++m) {
2039                         if ( lcU[m] != 1 ) {
2040                                 ex coef = lcU[m];
2041                                 for ( size_t i=j-1; i<nu-1; ++i ) {
2042                                         coef = coef.subs(I[i].x == I[i].evalpoint);
2043                                 }
2044                                 coef = make_modular(coef, R);
2045                                 int deg = U[m].degree(x);
2046                                 U[m] = U[m] - U[m].lcoeff(x) * pow(x,deg) + coef * pow(x,deg);
2047                         }
2048                 }
2049                 ex Uprod = 1;
2050                 for ( size_t i=0; i<n; ++i ) {
2051                         Uprod *= U[i];
2052                 }
2053                 ex e = expand(A[j-1] - Uprod);
2054
2055                 vector<EvalPoint> newI;
2056                 for ( size_t i=1; i<=j-2; ++i ) {
2057                         newI.push_back(I[i-1]);
2058                 }
2059
2060                 ex xj = I[j-2].x;
2061                 int alphaj = I[j-2].evalpoint;
2062                 size_t deg = A[j-1].degree(xj);
2063                 for ( size_t k=1; k<=deg; ++k ) {
2064                         if ( !e.is_zero() ) {
2065                                 monomial *= (xj - alphaj);
2066                                 monomial = expand(monomial);
2067                                 ex dif = e.diff(ex_to<symbol>(xj), k);
2068                                 ex c = dif.subs(xj==alphaj) / factorial(k);
2069                                 if ( !c.is_zero() ) {
2070                                         vector<ex> deltaU = multivar_diophant(U1, x, c, newI, maxdeg, p, cl_I_to_uint(l));
2071                                         for ( size_t i=0; i<n; ++i ) {
2072                                                 deltaU[i] *= monomial;
2073                                                 U[i] += deltaU[i];
2074                                                 U[i] = make_modular(U[i], R);
2075                                         }
2076                                         ex Uprod = 1;
2077                                         for ( size_t i=0; i<n; ++i ) {
2078                                                 Uprod *= U[i];
2079                                         }
2080                                         e = A[j-1] - Uprod;
2081                                         e = make_modular(e, R);
2082                                 }
2083                         }
2084                 }
2085         }
2086
2087         ex acand = 1;
2088         for ( size_t i=0; i<U.size(); ++i ) {
2089                 acand *= U[i];
2090         }
2091         if ( expand(a-acand).is_zero() ) {
2092                 lst res;
2093                 for ( size_t i=0; i<U.size(); ++i ) {
2094                         res.append(U[i]);
2095                 }
2096                 return res;
2097         }
2098         else {
2099                 lst res;
2100                 return lst();
2101         }
2102 }
2103
2104 /** Takes a factorized expression and puts the factors in a lst. The exponents
2105  *  of the factors are discarded, e.g. 7*x^2*(y+1)^4 --> {7,x,y+1}. The first
2106  *  element of the list is always the numeric coefficient.
2107  */
2108 static ex put_factors_into_lst(const ex& e)
2109 {
2110         lst result;
2111         if ( is_a<numeric>(e) ) {
2112                 result.append(e);
2113                 return result;
2114         }
2115         if ( is_a<power>(e) ) {
2116                 result.append(1);
2117                 result.append(e.op(0));
2118                 return result;
2119         }
2120         if ( is_a<symbol>(e) || is_a<add>(e) ) {
2121                 result.append(1);
2122                 result.append(e);
2123                 return result;
2124         }
2125         if ( is_a<mul>(e) ) {
2126                 ex nfac = 1;
2127                 for ( size_t i=0; i<e.nops(); ++i ) {
2128                         ex op = e.op(i);
2129                         if ( is_a<numeric>(op) ) {
2130                                 nfac = op;
2131                         }
2132                         if ( is_a<power>(op) ) {
2133                                 result.append(op.op(0));
2134                         }
2135                         if ( is_a<symbol>(op) || is_a<add>(op) ) {
2136                                 result.append(op);
2137                         }
2138                 }
2139                 result.prepend(nfac);
2140                 return result;
2141         }
2142         throw runtime_error("put_factors_into_lst: bad term.");
2143 }
2144
2145 /** Checks a set of numbers for whether each number has a unique prime factor.
2146  *
2147  *  @param[in]  f  list of numbers to check
2148  *  @return        true: if number set is bad, false: if set is okay (has unique
2149  *                 prime factors)
2150  */
2151 static bool checkdivisors(const lst& f)
2152 {
2153         const int k = f.nops();
2154         numeric q, r;
2155         vector<numeric> d(k);
2156         d[0] = ex_to<numeric>(abs(f.op(0)));
2157         for ( int i=1; i<k; ++i ) {
2158                 q = ex_to<numeric>(abs(f.op(i)));
2159                 for ( int j=i-1; j>=0; --j ) {
2160                         r = d[j];
2161                         do {
2162                                 r = gcd(r, q);
2163                                 q = q/r;
2164                         } while ( r != 1 );
2165                         if ( q == 1 ) {
2166                                 return true;
2167                         }
2168                 }
2169                 d[i] = q;
2170         }
2171         return false;
2172 }
2173
2174 /** Generates a set of evaluation points for a multivariate polynomial.
2175  *  The set fulfills the following conditions:
2176  *  1. lcoeff(evaluated_polynomial) does not vanish
2177  *  2. factors of lcoeff(evaluated_polynomial) have each a unique prime factor
2178  *  3. evaluated_polynomial is square free
2179  *  See [Wan] for more details.
2180  *
2181  *  @param[in]     u        multivariate polynomial to be factored
2182  *  @param[in]     vn       leading coefficient of u in x (x==first symbol in syms)
2183  *  @param[in]     syms     set of symbols that appear in u
2184  *  @param[in]     f        lst containing the factors of the leading coefficient vn
2185  *  @param[in,out] modulus  integer modulus for random number generation (i.e. |a_i| < modulus)
2186  *  @param[out]    u0       returns the evaluated (univariate) polynomial
2187  *  @param[out]    a        returns the valid evaluation points. must have initial size equal
2188  *                          number of symbols-1 before calling generate_set
2189  */
2190 static void generate_set(const ex& u, const ex& vn, const exset& syms, const lst& f,
2191                          numeric& modulus, ex& u0, vector<numeric>& a)
2192 {
2193         const ex& x = *syms.begin();
2194         while ( true ) {
2195                 ++modulus;
2196                 // generate a set of integers ...
2197                 u0 = u;
2198                 ex vna = vn;
2199                 ex vnatry;
2200                 exset::const_iterator s = syms.begin();
2201                 ++s;
2202                 for ( size_t i=0; i<a.size(); ++i ) {
2203                         do {
2204                                 a[i] = mod(numeric(rand()), 2*modulus) - modulus;
2205                                 vnatry = vna.subs(*s == a[i]);
2206                                 // ... for which the leading coefficient doesn't vanish ...
2207                         } while ( vnatry == 0 );
2208                         vna = vnatry;
2209                         u0 = u0.subs(*s == a[i]);
2210                         ++s;
2211                 }
2212                 // ... for which u0 is square free ...
2213                 ex g = gcd(u0, u0.diff(ex_to<symbol>(x)));
2214                 if ( !is_a<numeric>(g) ) {
2215                         continue;
2216                 }
2217                 if ( !is_a<numeric>(vn) ) {
2218                         // ... and for which the evaluated factors have each an unique prime factor
2219                         lst fnum = f;
2220                         fnum.let_op(0) = fnum.op(0) * u0.content(x);
2221                         for ( size_t i=1; i<fnum.nops(); ++i ) {
2222                                 if ( !is_a<numeric>(fnum.op(i)) ) {
2223                                         s = syms.begin();
2224                                         ++s;
2225                                         for ( size_t j=0; j<a.size(); ++j, ++s ) {
2226                                                 fnum.let_op(i) = fnum.op(i).subs(*s == a[j]);
2227                                         }
2228                                 }
2229                         }
2230                         if ( checkdivisors(fnum) ) {
2231                                 continue;
2232                         }
2233                 }
2234                 // ok, we have a valid set now
2235                 return;
2236         }
2237 }
2238
2239 // forward declaration
2240 static ex factor_sqrfree(const ex& poly);
2241
2242 /** Multivariate factorization.
2243  *  
2244  *  The implementation is based on the algorithm described in [Wan].
2245  *  An evaluation homomorphism (a set of integers) is determined that fulfills
2246  *  certain criteria. The evaluated polynomial is univariate and is factorized
2247  *  by factor_univariate(). The main work then is to find the correct leading
2248  *  coefficients of the univariate factors. They have to correspond to the
2249  *  factors of the (multivariate) leading coefficient of the input polynomial
2250  *  (as defined for a specific variable x). After that the Hensel lifting can be
2251  *  performed.
2252  *
2253  *  @param[in] poly  expanded, square free polynomial
2254  *  @param[in] syms  contains the symbols in the polynomial
2255  *  @return          factorized polynomial
2256  */
2257 static ex factor_multivariate(const ex& poly, const exset& syms)
2258 {
2259         exset::const_iterator s;
2260         const ex& x = *syms.begin();
2261
2262         // make polynomial primitive
2263         ex unit, cont, pp;
2264         poly.unitcontprim(x, unit, cont, pp);
2265         if ( !is_a<numeric>(cont) ) {
2266                 return factor_sqrfree(cont) * factor_sqrfree(pp);
2267         }
2268
2269         // factor leading coefficient
2270         ex vn = pp.collect(x).lcoeff(x);
2271         ex vnlst;
2272         if ( is_a<numeric>(vn) ) {
2273                 vnlst = lst(vn);
2274         }
2275         else {
2276                 ex vnfactors = factor(vn);
2277                 vnlst = put_factors_into_lst(vnfactors);
2278         }
2279
2280         const unsigned int maxtrials = 3;
2281         numeric modulus = (vnlst.nops() > 3) ? vnlst.nops() : 3;
2282         vector<numeric> a(syms.size()-1, 0);
2283
2284         // try now to factorize until we are successful
2285         while ( true ) {
2286
2287                 unsigned int trialcount = 0;
2288                 unsigned int prime;
2289                 int factor_count = 0;
2290                 int min_factor_count = -1;
2291                 ex u, delta;
2292                 ex ufac, ufaclst;
2293
2294                 // try several evaluation points to reduce the number of factors
2295                 while ( trialcount < maxtrials ) {
2296
2297                         // generate a set of valid evaluation points
2298                         generate_set(pp, vn, syms, ex_to<lst>(vnlst), modulus, u, a);
2299
2300                         ufac = factor_univariate(u, x, prime);
2301                         ufaclst = put_factors_into_lst(ufac);
2302                         factor_count = ufaclst.nops()-1;
2303                         delta = ufaclst.op(0);
2304
2305                         if ( factor_count <= 1 ) {
2306                                 // irreducible
2307                                 return poly;
2308                         }
2309                         if ( min_factor_count < 0 ) {
2310                                 // first time here
2311                                 min_factor_count = factor_count;
2312                         }
2313                         else if ( min_factor_count == factor_count ) {
2314                                 // one less to try
2315                                 ++trialcount;
2316                         }
2317                         else if ( min_factor_count > factor_count ) {
2318                                 // new minimum, reset trial counter
2319                                 min_factor_count = factor_count;
2320                                 trialcount = 0;
2321                         }
2322                 }
2323
2324                 // determine true leading coefficients for the Hensel lifting
2325                 vector<ex> C(factor_count);
2326                 if ( is_a<numeric>(vn) ) {
2327                         // easy case
2328                         for ( size_t i=1; i<ufaclst.nops(); ++i ) {
2329                                 C[i-1] = ufaclst.op(i).lcoeff(x);
2330                         }
2331                 }
2332                 else {
2333                         // difficult case.
2334                         // we use the property of the ftilde having a unique prime factor.
2335                         // details can be found in [Wan].
2336                         // calculate ftilde
2337                         vector<numeric> ftilde(vnlst.nops()-1);
2338                         for ( size_t i=0; i<ftilde.size(); ++i ) {
2339                                 ex ft = vnlst.op(i+1);
2340                                 s = syms.begin();
2341                                 ++s;
2342                                 for ( size_t j=0; j<a.size(); ++j ) {
2343                                         ft = ft.subs(*s == a[j]);
2344                                         ++s;
2345                                 }
2346                                 ftilde[i] = ex_to<numeric>(ft);
2347                         }
2348                         // calculate D and C
2349                         vector<bool> used_flag(ftilde.size(), false);
2350                         vector<ex> D(factor_count, 1);
2351                         if ( delta == 1 ) {
2352                                 for ( int i=0; i<factor_count; ++i ) {
2353                                         numeric prefac = ex_to<numeric>(ufaclst.op(i+1).lcoeff(x));
2354                                         for ( int j=ftilde.size()-1; j>=0; --j ) {
2355                                                 int count = 0;
2356                                                 while ( irem(prefac, ftilde[j]) == 0 ) {
2357                                                         prefac = iquo(prefac, ftilde[j]);
2358                                                         ++count;
2359                                                 }
2360                                                 if ( count ) {
2361                                                         used_flag[j] = true;
2362                                                         D[i] = D[i] * pow(vnlst.op(j+1), count);
2363                                                 }
2364                                         }
2365                                         C[i] = D[i] * prefac;
2366                                 }
2367                         }
2368                         else {
2369                                 for ( int i=0; i<factor_count; ++i ) {
2370                                         numeric prefac = ex_to<numeric>(ufaclst.op(i+1).lcoeff(x));
2371                                         for ( int j=ftilde.size()-1; j>=0; --j ) {
2372                                                 int count = 0;
2373                                                 while ( irem(prefac, ftilde[j]) == 0 ) {
2374                                                         prefac = iquo(prefac, ftilde[j]);
2375                                                         ++count;
2376                                                 }
2377                                                 while ( irem(ex_to<numeric>(delta)*prefac, ftilde[j]) == 0 ) {
2378                                                         numeric g = gcd(prefac, ex_to<numeric>(ftilde[j]));
2379                                                         prefac = iquo(prefac, g);
2380                                                         delta = delta / (ftilde[j]/g);
2381                                                         ufaclst.let_op(i+1) = ufaclst.op(i+1) * (ftilde[j]/g);
2382                                                         ++count;
2383                                                 }
2384                                                 if ( count ) {
2385                                                         used_flag[j] = true;
2386                                                         D[i] = D[i] * pow(vnlst.op(j+1), count);
2387                                                 }
2388                                         }
2389                                         C[i] = D[i] * prefac;
2390                                 }
2391                         }
2392                         // check if something went wrong
2393                         bool some_factor_unused = false;
2394                         for ( size_t i=0; i<used_flag.size(); ++i ) {
2395                                 if ( !used_flag[i] ) {
2396                                         some_factor_unused = true;
2397                                         break;
2398                                 }
2399                         }
2400                         if ( some_factor_unused ) {
2401                                 continue;
2402                         }
2403                 }
2404                 
2405                 // multiply the remaining content of the univariate polynomial into the
2406                 // first factor
2407                 if ( delta != 1 ) {
2408                         C[0] = C[0] * delta;
2409                         ufaclst.let_op(1) = ufaclst.op(1) * delta;
2410                 }
2411
2412                 // set up evaluation points
2413                 EvalPoint ep;
2414                 vector<EvalPoint> epv;
2415                 s = syms.begin();
2416                 ++s;
2417                 for ( size_t i=0; i<a.size(); ++i ) {
2418                         ep.x = *s++;
2419                         ep.evalpoint = a[i].to_int();
2420                         epv.push_back(ep);
2421                 }
2422
2423                 // calc bound p^l
2424                 int maxdeg = 0;
2425                 for ( int i=1; i<=factor_count; ++i ) {
2426                         if ( ufaclst.op(i).degree(x) > maxdeg ) {
2427                                 maxdeg = ufaclst[i].degree(x);
2428                         }
2429                 }
2430                 cl_I B = 2*calc_bound(u, x, maxdeg);
2431                 cl_I l = 1;
2432                 cl_I pl = prime;
2433                 while ( pl < B ) {
2434                         l = l + 1;
2435                         pl = pl * prime;
2436                 }
2437                 
2438                 // set up modular factors (mod p^l)
2439                 cl_modint_ring R = find_modint_ring(expt_pos(cl_I(prime),l));
2440                 upvec modfactors(ufaclst.nops()-1);
2441                 for ( size_t i=1; i<ufaclst.nops(); ++i ) {
2442                         umodpoly_from_ex(modfactors[i-1], ufaclst.op(i), x, R);
2443                 }
2444
2445                 // try Hensel lifting
2446                 ex res = hensel_multivar(pp, x, epv, prime, l, modfactors, C);
2447                 if ( res != lst() ) {
2448                         ex result = cont * unit;
2449                         for ( size_t i=0; i<res.nops(); ++i ) {
2450                                 result *= res.op(i).content(x) * res.op(i).unit(x);
2451                                 result *= res.op(i).primpart(x);
2452                         }
2453                         return result;
2454                 }
2455         }
2456 }
2457
2458 /** Finds all symbols in an expression. Used by factor_sqrfree() and factor().
2459  */
2460 struct find_symbols_map : public map_function {
2461         exset syms;
2462         ex operator()(const ex& e)
2463         {
2464                 if ( is_a<symbol>(e) ) {
2465                         syms.insert(e);
2466                         return e;
2467                 }
2468                 return e.map(*this);
2469         }
2470 };
2471
2472 /** Factorizes a polynomial that is square free. It calls either the univariate
2473  *  or the multivariate factorization functions.
2474  */
2475 static ex factor_sqrfree(const ex& poly)
2476 {
2477         // determine all symbols in poly
2478         find_symbols_map findsymbols;
2479         findsymbols(poly);
2480         if ( findsymbols.syms.size() == 0 ) {
2481                 return poly;
2482         }
2483
2484         if ( findsymbols.syms.size() == 1 ) {
2485                 // univariate case
2486                 const ex& x = *(findsymbols.syms.begin());
2487                 if ( poly.ldegree(x) > 0 ) {
2488                         // pull out direct factors
2489                         int ld = poly.ldegree(x);
2490                         ex res = factor_univariate(expand(poly/pow(x, ld)), x);
2491                         return res * pow(x,ld);
2492                 }
2493                 else {
2494                         ex res = factor_univariate(poly, x);
2495                         return res;
2496                 }
2497         }
2498
2499         // multivariate case
2500         ex res = factor_multivariate(poly, findsymbols.syms);
2501         return res;
2502 }
2503
2504 /** Map used by factor() when factor_options::all is given to access all
2505  *  subexpressions and to call factor() on them.
2506  */
2507 struct apply_factor_map : public map_function {
2508         unsigned options;
2509         apply_factor_map(unsigned options_) : options(options_) { }
2510         ex operator()(const ex& e)
2511         {
2512                 if ( e.info(info_flags::polynomial) ) {
2513                         return factor(e, options);
2514                 }
2515                 if ( is_a<add>(e) ) {
2516                         ex s1, s2;
2517                         for ( size_t i=0; i<e.nops(); ++i ) {
2518                                 if ( e.op(i).info(info_flags::polynomial) ) {
2519                                         s1 += e.op(i);
2520                                 }
2521                                 else {
2522                                         s2 += e.op(i);
2523                                 }
2524                         }
2525                         s1 = s1.eval();
2526                         s2 = s2.eval();
2527                         return factor(s1, options) + s2.map(*this);
2528                 }
2529                 return e.map(*this);
2530         }
2531 };
2532
2533 } // anonymous namespace
2534
2535 /** Interface function to the outside world. It checks the arguments, tries a
2536  *  square free factorization, and then calls factor_sqrfree to do the hard
2537  *  work.
2538  */
2539 ex factor(const ex& poly, unsigned options)
2540 {
2541         // check arguments
2542         if ( !poly.info(info_flags::polynomial) ) {
2543                 if ( options & factor_options::all ) {
2544                         options &= ~factor_options::all;
2545                         apply_factor_map factor_map(options);
2546                         return factor_map(poly);
2547                 }
2548                 return poly;
2549         }
2550
2551         // determine all symbols in poly
2552         find_symbols_map findsymbols;
2553         findsymbols(poly);
2554         if ( findsymbols.syms.size() == 0 ) {
2555                 return poly;
2556         }
2557         lst syms;
2558         exset::const_iterator i=findsymbols.syms.begin(), end=findsymbols.syms.end();
2559         for ( ; i!=end; ++i ) {
2560                 syms.append(*i);
2561         }
2562
2563         // make poly square free
2564         ex sfpoly = sqrfree(poly.expand(), syms);
2565
2566         // factorize the square free components
2567         if ( is_a<power>(sfpoly) ) {
2568                 // case: (polynomial)^exponent
2569                 const ex& base = sfpoly.op(0);
2570                 if ( !is_a<add>(base) ) {
2571                         // simple case: (monomial)^exponent
2572                         return sfpoly;
2573                 }
2574                 ex f = factor_sqrfree(base);
2575                 return pow(f, sfpoly.op(1));
2576         }
2577         if ( is_a<mul>(sfpoly) ) {
2578                 // case: multiple factors
2579                 ex res = 1;
2580                 for ( size_t i=0; i<sfpoly.nops(); ++i ) {
2581                         const ex& t = sfpoly.op(i);
2582                         if ( is_a<power>(t) ) {
2583                                 const ex& base = t.op(0);
2584                                 if ( !is_a<add>(base) ) {
2585                                         res *= t;
2586                                 }
2587                                 else {
2588                                         ex f = factor_sqrfree(base);
2589                                         res *= pow(f, t.op(1));
2590                                 }
2591                         }
2592                         else if ( is_a<add>(t) ) {
2593                                 ex f = factor_sqrfree(t);
2594                                 res *= f;
2595                         }
2596                         else {
2597                                 res *= t;
2598                         }
2599                 }
2600                 return res;
2601         }
2602         if ( is_a<symbol>(sfpoly) ) {
2603                 return poly;
2604         }
2605         // case: (polynomial)
2606         ex f = factor_sqrfree(sfpoly);
2607         return f;
2608 }
2609
2610 } // namespace GiNaC
2611
2612 #ifdef DEBUGFACTOR
2613 #include "test.h"
2614 #endif