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