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