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