Merge branch 'master' of git://ffmssmsc.jinr.ru:443/varg/ginac
[ginac.git] / ginac / factor.cpp
1 /** @file factor.cpp
2  *
3  *  Polynomial factorization routines.
4  *  Only univariate at the moment and completely non-optimized!
5  */
6
7 /*
8  *  GiNaC Copyright (C) 1999-2008 Johannes Gutenberg University Mainz, Germany
9  *
10  *  This program is free software; you can redistribute it and/or modify
11  *  it under the terms of the GNU General Public License as published by
12  *  the Free Software Foundation; either version 2 of the License, or
13  *  (at your option) any later version.
14  *
15  *  This program is distributed in the hope that it will be useful,
16  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
17  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  *  GNU General Public License for more details.
19  *
20  *  You should have received a copy of the GNU General Public License
21  *  along with this program; if not, write to the Free Software
22  *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
23  */
24
25 //#define DEBUGFACTOR
26
27 #ifdef DEBUGFACTOR
28 #include <ostream>
29 #include <ginac/ginac.h>
30 using namespace GiNaC;
31 #else
32 #include "factor.h"
33
34 #include "ex.h"
35 #include "numeric.h"
36 #include "operators.h"
37 #include "inifcns.h"
38 #include "symbol.h"
39 #include "relational.h"
40 #include "power.h"
41 #include "mul.h"
42 #include "normal.h"
43 #include "add.h"
44 #endif
45
46 #include <algorithm>
47 #include <list>
48 #include <vector>
49 using namespace std;
50
51 #include <cln/cln.h>
52 using namespace cln;
53
54 #ifdef DEBUGFACTOR
55 namespace Factor {
56 #else
57 namespace GiNaC {
58 #endif
59
60 #ifdef DEBUGFACTOR
61 #define DCOUT(str) cout << #str << endl
62 #define DCOUTVAR(var) cout << #var << ": " << var << endl
63 #define DCOUT2(str,var) cout << #str << ": " << var << endl
64 #else
65 #define DCOUT(str)
66 #define DCOUTVAR(var)
67 #define DCOUT2(str,var)
68 #endif
69
70 namespace {
71
72 typedef vector<cl_MI> Vec;
73 typedef vector<Vec> VecVec;
74
75 #ifdef DEBUGFACTOR
76 ostream& operator<<(ostream& o, const Vec& v)
77 {
78         Vec::const_iterator i = v.begin(), end = v.end();
79         while ( i != end ) {
80                 o << *i++ << " ";
81         }
82         return o;
83 }
84 #endif // def DEBUGFACTOR
85
86 #ifdef DEBUGFACTOR
87 ostream& operator<<(ostream& o, const VecVec& v)
88 {
89         VecVec::const_iterator i = v.begin(), end = v.end();
90         while ( i != end ) {
91                 o << *i++ << endl;
92         }
93         return o;
94 }
95 #endif // def DEBUGFACTOR
96
97 struct Term
98 {
99         cl_MI c;          // coefficient
100         unsigned int exp; // exponent >=0
101 };
102
103 #ifdef DEBUGFACTOR
104 ostream& operator<<(ostream& o, const Term& t)
105 {
106         if ( t.exp ) {
107                 o << "(" << t.c << ")x^" << t.exp;
108         }
109         else {
110                 o << "(" << t.c << ")";
111         }
112         return o;
113 }
114 #endif // def DEBUGFACTOR
115
116 struct UniPoly
117 {
118         cl_modint_ring R;
119         list<Term> terms;  // highest exponent first
120
121         UniPoly(const cl_modint_ring& ring) : R(ring) { }
122         UniPoly(const cl_modint_ring& ring, const ex& poly, const ex& x) : R(ring)
123         { 
124                 // assert: poly is in Z[x]
125                 Term t;
126                 for ( int i=poly.degree(x); i>=poly.ldegree(x); --i ) {
127                         cl_I coeff = the<cl_I>(ex_to<numeric>(poly.coeff(x,i)).to_cl_N());
128                         if ( !zerop(coeff) ) {
129                                 t.c = R->canonhom(coeff);
130                                 if ( !zerop(t.c) ) {
131                                         t.exp = i;
132                                         terms.push_back(t);
133                                 }
134                         }
135                 }
136         }
137         UniPoly(const cl_modint_ring& ring, const UniPoly& poly) : R(ring)
138         { 
139                 if ( R->modulus == poly.R->modulus ) {
140                         terms = poly.terms;
141                 }
142                 else {
143                         list<Term>::const_iterator i=poly.terms.begin(), end=poly.terms.end();
144                         for ( ; i!=end; ++i ) {
145                                 terms.push_back(*i);
146                                 terms.back().c = R->canonhom(poly.R->retract(i->c));
147                                 if ( zerop(terms.back().c) ) {
148                                         terms.pop_back();
149                                 }
150                         }
151                 }
152         }
153         UniPoly(const cl_modint_ring& ring, const Vec& v) : R(ring)
154         {
155                 Term t;
156                 for ( unsigned int i=0; i<v.size(); ++i ) {
157                         if ( !zerop(v[i]) ) {
158                                 t.c = v[i];
159                                 t.exp = i;
160                                 terms.push_front(t);
161                         }
162                 }
163         }
164         unsigned int degree() const
165         {
166                 if ( terms.size() ) {
167                         return terms.front().exp;
168                 }
169                 else {
170                         return 0;
171                 }
172         }
173         bool zero() const { return (terms.size() == 0); }
174         const cl_MI operator[](unsigned int deg) const
175         {
176                 list<Term>::const_iterator i = terms.begin(), end = terms.end();
177                 for ( ; i != end; ++i ) {
178                         if ( i->exp == deg ) {
179                                 return i->c;
180                         }
181                         if ( i->exp < deg ) {
182                                 break;
183                         }
184                 }
185                 return R->zero();
186         }
187         void set(unsigned int deg, const cl_MI& c)
188         {
189                 list<Term>::iterator i = terms.begin(), end = terms.end();
190                 while ( i != end ) {
191                         if ( i->exp == deg ) {
192                                 if ( !zerop(c) ) {
193                                         i->c = c;
194                                 }
195                                 else {
196                                         terms.erase(i);
197                                 }
198                                 return;
199                         }
200                         if ( i->exp < deg ) {
201                                 break;
202                         }
203                         ++i;
204                 }
205                 if ( !zerop(c) ) {
206                         Term t;
207                         t.c = c;
208                         t.exp = deg;
209                         terms.insert(i, t);
210                 }
211         }
212         ex to_ex(const ex& x, bool symmetric = true) const
213         {
214                 ex r;
215                 list<Term>::const_iterator i = terms.begin(), end = terms.end();
216                 if ( symmetric ) {
217                         numeric mod(R->modulus);
218                         numeric halfmod = (mod-1)/2;
219                         for ( ; i != end; ++i ) {
220                                 numeric n(R->retract(i->c));
221                                 if ( n > halfmod ) {
222                                         r += pow(x, i->exp) * (n-mod);
223                                 }
224                                 else {
225                                         r += pow(x, i->exp) * n;
226                                 }
227                         }
228                 }
229                 else {
230                         for ( ; i != end; ++i ) {
231                                 r += pow(x, i->exp) * numeric(R->retract(i->c));
232                         }
233                 }
234                 return r;
235         }
236         void unit_normal()
237         {
238                 if ( terms.size() ) {
239                         if ( terms.front().c != R->one() ) {
240                                 list<Term>::iterator i = terms.begin(), end = terms.end();
241                                 cl_MI cont = i->c;
242                                 i->c = R->one();
243                                 while ( ++i != end ) {
244                                         i->c = div(i->c, cont);
245                                         if ( zerop(i->c) ) {
246                                                 terms.erase(i);
247                                         }
248                                 }
249                         }
250                 }
251         }
252         cl_MI unit() const
253         {
254                 return terms.front().c;
255         }
256         void divide(const cl_MI& x)
257         {
258                 list<Term>::iterator i = terms.begin(), end = terms.end();
259                 for ( ; i != end; ++i ) {
260                         i->c = div(i->c, x);
261                         if ( zerop(i->c) ) {
262                                 terms.erase(i);
263                         }
264                 }
265         }
266         void divide(const cl_I& x)
267         {
268                 list<Term>::iterator i = terms.begin(), end = terms.end();
269                 for ( ; i != end; ++i ) {
270                         i->c = cl_MI(R, the<cl_I>(R->retract(i->c) / x));
271                 }
272         }
273         void reduce_exponents(unsigned int prime)
274         {
275                 list<Term>::iterator i = terms.begin(), end = terms.end();
276                 while ( i != end ) {
277                         if ( i->exp > 0 ) {
278                                 // assert: i->exp is multiple of prime
279                                 i->exp /= prime;
280                         }
281                         ++i;
282                 }
283         }
284         void deriv(UniPoly& d) const
285         {
286                 list<Term>::const_iterator i = terms.begin(), end = terms.end();
287                 while ( i != end ) {
288                         if ( i->exp ) {
289                                 cl_MI newc = i->c * i->exp;
290                                 if ( !zerop(newc) ) {
291                                         Term t;
292                                         t.c = newc;
293                                         t.exp = i->exp-1;
294                                         d.terms.push_back(t);
295                                 }
296                         }
297                         ++i;
298                 }
299         }
300         bool operator<(const UniPoly& o) const
301         {
302                 if ( terms.size() != o.terms.size() ) {
303                         return terms.size() < o.terms.size();
304                 }
305                 list<Term>::const_iterator i1 = terms.begin(), end = terms.end();
306                 list<Term>::const_iterator i2 = o.terms.begin();
307                 while ( i1 != end ) {
308                         if ( i1->exp != i2->exp ) {
309                                 return i1->exp < i2->exp;
310                         }
311                         if ( i1->c != i2->c ) {
312                                 return R->retract(i1->c) < R->retract(i2->c);
313                         }
314                         ++i1; ++i2;
315                 }
316                 return true;
317         }
318         bool operator==(const UniPoly& o) const
319         {
320                 if ( terms.size() != o.terms.size() ) {
321                         return false;
322                 }
323                 list<Term>::const_iterator i1 = terms.begin(), end = terms.end();
324                 list<Term>::const_iterator i2 = o.terms.begin();
325                 while ( i1 != end ) {
326                         if ( i1->exp != i2->exp ) {
327                                 return false;
328                         }
329                         if ( i1->c != i2->c ) {
330                                 return false;
331                         }
332                         ++i1; ++i2;
333                 }
334                 return true;
335         }
336         bool operator!=(const UniPoly& o) const
337         {
338                 bool res = !(*this == o);
339                 return res;
340         }
341 };
342
343 static UniPoly operator*(const UniPoly& a, const UniPoly& b)
344 {
345         unsigned int n = a.degree()+b.degree();
346         UniPoly c(a.R);
347         Term t;
348         for ( unsigned int i=0 ; i<=n; ++i ) {
349                 t.c = a.R->zero();
350                 for ( unsigned int j=0 ; j<=i; ++j ) {
351                         t.c = t.c + a[j] * b[i-j];
352                 }
353                 if ( !zerop(t.c) ) {
354                         t.exp = i;
355                         c.terms.push_front(t);
356                 }
357         }
358         return c;
359 }
360
361 static UniPoly operator-(const UniPoly& a, const UniPoly& b)
362 {
363         list<Term>::const_iterator ia = a.terms.begin(), aend = a.terms.end();
364         list<Term>::const_iterator ib = b.terms.begin(), bend = b.terms.end();
365         UniPoly c(a.R);
366         while ( ia != aend && ib != bend ) {
367                 if ( ia->exp > ib->exp ) {
368                         c.terms.push_back(*ia);
369                         ++ia;
370                 }
371                 else if ( ia->exp < ib->exp ) {
372                         c.terms.push_back(*ib);
373                         c.terms.back().c = -c.terms.back().c;
374                         ++ib;
375                 }
376                 else {
377                         Term t;
378                         t.exp = ia->exp;
379                         t.c = ia->c - ib->c;
380                         if ( !zerop(t.c) ) {
381                                 c.terms.push_back(t);
382                         }
383                         ++ia; ++ib;
384                 }
385         }
386         while ( ia != aend ) {
387                 c.terms.push_back(*ia);
388                 ++ia;
389         }
390         while ( ib != bend ) {
391                 c.terms.push_back(*ib);
392                 c.terms.back().c = -c.terms.back().c;
393                 ++ib;
394         }
395         return c;
396 }
397
398 static UniPoly operator*(const UniPoly& a, const cl_MI& fac)
399 {
400         unsigned int n = a.degree();
401         UniPoly c(a.R);
402         Term t;
403         for ( unsigned int i=0 ; i<=n; ++i ) {
404                 t.c = a[i] * fac;
405                 if ( !zerop(t.c) ) {
406                         t.exp = i;
407                         c.terms.push_front(t);
408                 }
409         }
410         return c;
411 }
412
413 static UniPoly operator+(const UniPoly& a, const UniPoly& b)
414 {
415         list<Term>::const_iterator ia = a.terms.begin(), aend = a.terms.end();
416         list<Term>::const_iterator ib = b.terms.begin(), bend = b.terms.end();
417         UniPoly c(a.R);
418         while ( ia != aend && ib != bend ) {
419                 if ( ia->exp > ib->exp ) {
420                         c.terms.push_back(*ia);
421                         ++ia;
422                 }
423                 else if ( ia->exp < ib->exp ) {
424                         c.terms.push_back(*ib);
425                         ++ib;
426                 }
427                 else {
428                         Term t;
429                         t.exp = ia->exp;
430                         t.c = ia->c + ib->c;
431                         if ( !zerop(t.c) ) {
432                                 c.terms.push_back(t);
433                         }
434                         ++ia; ++ib;
435                 }
436         }
437         while ( ia != aend ) {
438                 c.terms.push_back(*ia);
439                 ++ia;
440         }
441         while ( ib != bend ) {
442                 c.terms.push_back(*ib);
443                 ++ib;
444         }
445         return c;
446 }
447
448 // static UniPoly operator-(const UniPoly& a)
449 // {
450 //      list<Term>::const_iterator ia = a.terms.begin(), aend = a.terms.end();
451 //      UniPoly c(a.R);
452 //      while ( ia != aend ) {
453 //              c.terms.push_back(*ia);
454 //              c.terms.back().c = -c.terms.back().c;
455 //              ++ia;
456 //      }
457 //      return c;
458 // }
459
460 #ifdef DEBUGFACTOR
461 ostream& operator<<(ostream& o, const UniPoly& t)
462 {
463         list<Term>::const_iterator i = t.terms.begin(), end = t.terms.end();
464         if ( i == end ) {
465                 o << "0";
466                 return o;
467         }
468         for ( ; i != end; ) {
469                 o << *i++;
470                 if ( i != end ) {
471                         o << " + ";
472                 }
473         }
474         return o;
475 }
476 #endif // def DEBUGFACTOR
477
478 #ifdef DEBUGFACTOR
479 ostream& operator<<(ostream& o, const list<UniPoly>& t)
480 {
481         list<UniPoly>::const_iterator i = t.begin(), end = t.end();
482         o << "{" << endl;
483         for ( ; i != end; ) {
484                 o << *i++ << endl;
485         }
486         o << "}" << endl;
487         return o;
488 }
489 #endif // def DEBUGFACTOR
490
491 typedef vector<UniPoly> UniPolyVec;
492
493 #ifdef DEBUGFACTOR
494 ostream& operator<<(ostream& o, const UniPolyVec& v)
495 {
496         UniPolyVec::const_iterator i = v.begin(), end = v.end();
497         while ( i != end ) {
498                 o << *i++ << " , " << endl;
499         }
500         return o;
501 }
502 #endif // def DEBUGFACTOR
503
504 struct UniFactor
505 {
506         UniPoly p;
507         unsigned int exp;
508
509         UniFactor(const cl_modint_ring& ring) : p(ring) { }
510         UniFactor(const UniPoly& p_, unsigned int exp_) : p(p_), exp(exp_) { }
511         bool operator<(const UniFactor& o) const
512         {
513                 return p < o.p;
514         }
515 };
516
517 struct UniFactorVec
518 {
519         vector<UniFactor> factors;
520
521         void unique()
522         {
523                 sort(factors.begin(), factors.end());
524                 if ( factors.size() > 1 ) {
525                         vector<UniFactor>::iterator i = factors.begin();
526                         vector<UniFactor>::const_iterator cmp = factors.begin()+1;
527                         vector<UniFactor>::iterator end = factors.end();
528                         while ( cmp != end ) {
529                                 if ( i->p != cmp->p ) {
530                                         ++i;
531                                         ++cmp;
532                                 }
533                                 else {
534                                         i->exp += cmp->exp;
535                                         ++cmp;
536                                 }
537                         }
538                         if ( i != end-1 ) {
539                                 factors.erase(i+1, end);
540                         }
541                 }
542         }
543 };
544
545 #ifdef DEBUGFACTOR
546 ostream& operator<<(ostream& o, const UniFactorVec& ufv)
547 {
548         for ( size_t i=0; i<ufv.factors.size(); ++i ) {
549                 if ( i != ufv.factors.size()-1 ) {
550                         o << "*";
551                 }
552                 else {
553                         o << " ";
554                 }
555                 o << "[ " << ufv.factors[i].p << " ]^" << ufv.factors[i].exp << endl;
556         }
557         return o;
558 }
559 #endif // def DEBUGFACTOR
560
561 static void rem(const UniPoly& a_, const UniPoly& b, UniPoly& c)
562 {
563         if ( a_.degree() < b.degree() ) {
564                 c = a_;
565                 return;
566         }
567
568         unsigned int k, n;
569         n = b.degree();
570         k = a_.degree() - n;
571
572         if ( n == 0 ) {
573                 c.terms.clear();
574                 return;
575         }
576
577         c = a_;
578         Term termbuf;
579
580         while ( true ) {
581                 cl_MI qk = div(c[n+k], b[n]);
582                 if ( !zerop(qk) ) {
583                         unsigned int j;
584                         for ( unsigned int i=0; i<n; ++i ) {
585                                 j = n + k - 1 - i;
586                                 c.set(j, c[j] - qk*b[j-k]);
587                         }
588                 }
589                 if ( k == 0 ) break;
590                 --k;
591         }
592         list<Term>::iterator i = c.terms.begin(), end = c.terms.end();
593         while ( i != end ) {
594                 if ( i->exp <= n-1 ) {
595                         break;
596                 }
597                 ++i;
598         }
599         c.terms.erase(c.terms.begin(), i);
600 }
601
602 static void div(const UniPoly& a_, const UniPoly& b, UniPoly& q)
603 {
604         if ( a_.degree() < b.degree() ) {
605                 q.terms.clear();
606                 return;
607         }
608
609         unsigned int k, n;
610         n = b.degree();
611         k = a_.degree() - n;
612
613         UniPoly c = a_;
614         Term termbuf;
615
616         while ( true ) {
617                 cl_MI qk = div(c[n+k], b[n]);
618                 if ( !zerop(qk) ) {
619                         Term t;
620                         t.c = qk;
621                         t.exp = k;
622                         q.terms.push_back(t);
623                         unsigned int j;
624                         for ( unsigned int i=0; i<n; ++i ) {
625                                 j = n + k - 1 - i;
626                                 c.set(j, c[j] - qk*b[j-k]);
627                         }
628                 }
629                 if ( k == 0 ) break;
630                 --k;
631         }
632 }
633
634 static void gcd(const UniPoly& a, const UniPoly& b, UniPoly& c)
635 {
636         c = a;
637         c.unit_normal();
638         UniPoly d = b;
639         d.unit_normal();
640
641         if ( c.degree() < d.degree() ) {
642                 gcd(b, a, c);
643                 return;
644         }
645
646         while ( !d.zero() ) {
647                 UniPoly r(a.R);
648                 rem(c, d, r);
649                 c = d;
650                 d = r;
651         }
652         c.unit_normal();
653 }
654
655 static bool is_one(const UniPoly& w)
656 {
657         if ( w.terms.size() == 1 && w[0] == w.R->one() ) {
658                 return true;
659         }
660         return false;
661 }
662
663 static void sqrfree_main(const UniPoly& a, UniFactorVec& fvec)
664 {
665         unsigned int i = 1;
666         UniPoly b(a.R);
667         a.deriv(b);
668         if ( !b.zero() ) {
669                 UniPoly c(a.R), w(a.R);
670                 gcd(a, b, c);
671                 div(a, c, w);
672                 while ( !is_one(w) ) {
673                         UniPoly y(a.R), z(a.R);
674                         gcd(w, c, y);
675                         div(w, y, z);
676                         if ( !is_one(z) ) {
677                                 UniFactor uf(z, i);
678                                 fvec.factors.push_back(uf);
679                         }
680                         ++i;
681                         w = y;
682                         UniPoly cbuf(a.R);
683                         div(c, y, cbuf);
684                         c = cbuf;
685                 }
686                 if ( !is_one(c) ) {
687                         unsigned int prime = cl_I_to_uint(c.R->modulus);
688                         c.reduce_exponents(prime);
689                         unsigned int pos = fvec.factors.size();
690                         sqrfree_main(c, fvec);
691                         for ( unsigned int p=pos; p<fvec.factors.size(); ++p ) {
692                                 fvec.factors[p].exp *= prime;
693                         }
694                         return;
695                 }
696         }
697         else {
698                 unsigned int prime = cl_I_to_uint(a.R->modulus);
699                 UniPoly amod = a;
700                 amod.reduce_exponents(prime);
701                 unsigned int pos = fvec.factors.size();
702                 sqrfree_main(amod, fvec);
703                 for ( unsigned int p=pos; p<fvec.factors.size(); ++p ) {
704                         fvec.factors[p].exp *= prime;
705                 }
706                 return;
707         }
708 }
709
710 static void squarefree(const UniPoly& a, UniFactorVec& fvec)
711 {
712         sqrfree_main(a, fvec);
713         fvec.unique();
714 }
715
716 class Matrix
717 {
718         friend ostream& operator<<(ostream& o, const Matrix& m);
719 public:
720         Matrix(size_t r_, size_t c_, const cl_MI& init) : r(r_), c(c_)
721         {
722                 m.resize(c*r, init);
723         }
724         size_t rowsize() const { return r; }
725         size_t colsize() const { return c; }
726         cl_MI& operator()(size_t row, size_t col) { return m[row*c + col]; }
727         cl_MI operator()(size_t row, size_t col) const { return m[row*c + col]; }
728         void mul_col(size_t col, const cl_MI x)
729         {
730                 Vec::iterator i = m.begin() + col;
731                 for ( size_t rc=0; rc<r; ++rc ) {
732                         *i = *i * x;
733                         i += c;
734                 }
735         }
736         void sub_col(size_t col1, size_t col2, const cl_MI fac)
737         {
738                 Vec::iterator i1 = m.begin() + col1;
739                 Vec::iterator i2 = m.begin() + col2;
740                 for ( size_t rc=0; rc<r; ++rc ) {
741                         *i1 = *i1 - *i2 * fac;
742                         i1 += c;
743                         i2 += c;
744                 }
745         }
746         void switch_col(size_t col1, size_t col2)
747         {
748                 cl_MI buf;
749                 Vec::iterator i1 = m.begin() + col1;
750                 Vec::iterator i2 = m.begin() + col2;
751                 for ( size_t rc=0; rc<r; ++rc ) {
752                         buf = *i1; *i1 = *i2; *i2 = buf;
753                         i1 += c;
754                         i2 += c;
755                 }
756         }
757         void mul_row(size_t row, const cl_MI x)
758         {
759                 vector<cl_MI>::iterator i = m.begin() + row*c;
760                 for ( size_t cc=0; cc<c; ++cc ) {
761                         *i = *i * x;
762                         ++i;
763                 }
764         }
765         void sub_row(size_t row1, size_t row2, const cl_MI fac)
766         {
767                 vector<cl_MI>::iterator i1 = m.begin() + row1*c;
768                 vector<cl_MI>::iterator i2 = m.begin() + row2*c;
769                 for ( size_t cc=0; cc<c; ++cc ) {
770                         *i1 = *i1 - *i2 * fac;
771                         ++i1;
772                         ++i2;
773                 }
774         }
775         void switch_row(size_t row1, size_t row2)
776         {
777                 cl_MI buf;
778                 vector<cl_MI>::iterator i1 = m.begin() + row1*c;
779                 vector<cl_MI>::iterator i2 = m.begin() + row2*c;
780                 for ( size_t cc=0; cc<c; ++cc ) {
781                         buf = *i1; *i1 = *i2; *i2 = buf;
782                         ++i1;
783                         ++i2;
784                 }
785         }
786         bool is_col_zero(size_t col) const
787         {
788                 Vec::const_iterator i = m.begin() + col;
789                 for ( size_t rr=0; rr<r; ++rr ) {
790                         if ( !zerop(*i) ) {
791                                 return false;
792                         }
793                         i += c;
794                 }
795                 return true;
796         }
797         bool is_row_zero(size_t row) const
798         {
799                 Vec::const_iterator i = m.begin() + row*c;
800                 for ( size_t cc=0; cc<c; ++cc ) {
801                         if ( !zerop(*i) ) {
802                                 return false;
803                         }
804                         ++i;
805                 }
806                 return true;
807         }
808         void set_row(size_t row, const vector<cl_MI>& newrow)
809         {
810                 Vec::iterator i1 = m.begin() + row*c;
811                 Vec::const_iterator i2 = newrow.begin(), end = newrow.end();
812                 for ( ; i2 != end; ++i1, ++i2 ) {
813                         *i1 = *i2;
814                 }
815         }
816         Vec::const_iterator row_begin(size_t row) const { return m.begin()+row*c; }
817         Vec::const_iterator row_end(size_t row) const { return m.begin()+row*c+r; }
818 private:
819         size_t r, c;
820         Vec m;
821 };
822
823 #ifdef DEBUGFACTOR
824 Matrix operator*(const Matrix& m1, const Matrix& m2)
825 {
826         const unsigned int r = m1.rowsize();
827         const unsigned int c = m2.colsize();
828         Matrix o(r,c,m1(0,0));
829
830         for ( size_t i=0; i<r; ++i ) {
831                 for ( size_t j=0; j<c; ++j ) {
832                         cl_MI buf;
833                         buf = m1(i,0) * m2(0,j);
834                         for ( size_t k=1; k<c; ++k ) {
835                                 buf = buf + m1(i,k)*m2(k,j);
836                         }
837                         o(i,j) = buf;
838                 }
839         }
840         return o;
841 }
842
843 ostream& operator<<(ostream& o, const Matrix& m)
844 {
845         vector<cl_MI>::const_iterator i = m.m.begin(), end = m.m.end();
846         size_t wrap = 1;
847         for ( ; i != end; ++i ) {
848                 o << *i << " ";
849                 if ( !(wrap++ % m.c) ) {
850                         o << endl;
851                 }
852         }
853         o << endl;
854         return o;
855 }
856 #endif // def DEBUGFACTOR
857
858 static void q_matrix(const UniPoly& a, Matrix& Q)
859 {
860         unsigned int n = a.degree();
861         unsigned int q = cl_I_to_uint(a.R->modulus);
862 // fast and buggy
863 //      vector<cl_MI> r(n, a.R->zero());
864 //      r[0] = a.R->one();
865 //      Q.set_row(0, r);
866 //      unsigned int max = (n-1) * q;
867 //      for ( size_t m=1; m<=max; ++m ) {
868 //              cl_MI rn_1 = r.back();
869 //              for ( size_t i=n-1; i>0; --i ) {
870 //                      r[i] = r[i-1] - rn_1 * a[i];
871 //              }
872 //              r[0] = -rn_1 * a[0];
873 //              if ( (m % q) == 0 ) {
874 //                      Q.set_row(m/q, r);
875 //              }
876 //      }
877 // slow and (hopefully) correct
878         for ( size_t i=0; i<n; ++i ) {
879                 UniPoly qk(a.R);
880                 qk.set(i*q, a.R->one());
881                 UniPoly r(a.R);
882                 rem(qk, a, r);
883                 Vec rvec;
884                 for ( size_t j=0; j<n; ++j ) {
885                         rvec.push_back(r[j]);
886                 }
887                 Q.set_row(i, rvec);
888         }
889 }
890
891 static void nullspace(Matrix& M, vector<Vec>& basis)
892 {
893         const size_t n = M.rowsize();
894         const cl_MI one = M(0,0).ring()->one();
895         for ( size_t i=0; i<n; ++i ) {
896                 M(i,i) = M(i,i) - one;
897         }
898         for ( size_t r=0; r<n; ++r ) {
899                 size_t cc = 0;
900                 for ( ; cc<n; ++cc ) {
901                         if ( !zerop(M(r,cc)) ) {
902                                 if ( cc < r ) {
903                                         if ( !zerop(M(cc,cc)) ) {
904                                                 continue;
905                                         }
906                                         M.switch_col(cc, r);
907                                 }
908                                 else if ( cc > r ) {
909                                         M.switch_col(cc, r);
910                                 }
911                                 break;
912                         }
913                 }
914                 if ( cc < n ) {
915                         M.mul_col(r, recip(M(r,r)));
916                         for ( cc=0; cc<n; ++cc ) {
917                                 if ( cc != r ) {
918                                         M.sub_col(cc, r, M(r,cc));
919                                 }
920                         }
921                 }
922         }
923
924         for ( size_t i=0; i<n; ++i ) {
925                 M(i,i) = M(i,i) - one;
926         }
927         for ( size_t i=0; i<n; ++i ) {
928                 if ( !M.is_row_zero(i) ) {
929                         Vec nu(M.row_begin(i), M.row_end(i));
930                         basis.push_back(nu);
931                 }
932         }
933 }
934
935 static void berlekamp(const UniPoly& a, UniPolyVec& upv)
936 {
937         Matrix Q(a.degree(), a.degree(), a.R->zero());
938         q_matrix(a, Q);
939         VecVec nu;
940         nullspace(Q, nu);
941         const unsigned int k = nu.size();
942         if ( k == 1 ) {
943                 return;
944         }
945
946         list<UniPoly> factors;
947         factors.push_back(a);
948         unsigned int size = 1;
949         unsigned int r = 1;
950         unsigned int q = cl_I_to_uint(a.R->modulus);
951
952         list<UniPoly>::iterator u = factors.begin();
953
954         while ( true ) {
955                 for ( unsigned int s=0; s<q; ++s ) {
956                         UniPoly g(a.R);
957                         UniPoly nur(a.R, nu[r]);
958                         nur.set(0, nur[0] - cl_MI(a.R, s));
959                         gcd(nur, *u, g);
960                         if ( !is_one(g) && g != *u ) {
961                                 UniPoly uo(a.R);
962                                 div(*u, g, uo);
963                                 if ( is_one(uo) ) {
964                                         throw logic_error("berlekamp: unexpected divisor.");
965                                 }
966                                 else {
967                                         *u = uo;
968                                 }
969                                 factors.push_back(g);
970                                 size = 0;
971                                 list<UniPoly>::const_iterator i = factors.begin(), end = factors.end();
972                                 while ( i != end ) {
973                                         if ( i->degree() ) ++size; 
974                                         ++i;
975                                 }
976                                 if ( size == k ) {
977                                         list<UniPoly>::const_iterator i = factors.begin(), end = factors.end();
978                                         while ( i != end ) {
979                                                 upv.push_back(*i++);
980                                         }
981                                         return;
982                                 }
983 //                              if ( u->degree() < nur.degree() ) {
984 //                                      break;
985 //                              }
986                         }
987                 }
988                 if ( ++r == k ) {
989                         r = 1;
990                         ++u;
991                 }
992         }
993 }
994
995 static void factor_modular(const UniPoly& p, UniPolyVec& upv)
996 {
997         berlekamp(p, upv);
998         return;
999 }
1000
1001 static void exteuclid(const UniPoly& a, const UniPoly& b, UniPoly& g, UniPoly& s, UniPoly& t)
1002 {
1003         if ( a.degree() < b.degree() ) {
1004                 exteuclid(b, a, g, t, s);
1005                 return;
1006         }
1007         UniPoly c1(a.R), c2(a.R), d1(a.R), d2(a.R), q(a.R), r(a.R), r1(a.R), r2(a.R);
1008         UniPoly c = a; c.unit_normal();
1009         UniPoly d = b; d.unit_normal();
1010         c1.set(0, a.R->one());
1011         d2.set(0, a.R->one());
1012         while ( !d.zero() ) {
1013                 q.terms.clear();
1014                 div(c, d, q);
1015                 r = c - q * d;
1016                 r1 = c1 - q * d1;
1017                 r2 = c2 - q * d2;
1018                 c = d;
1019                 c1 = d1;
1020                 c2 = d2;
1021                 d = r;
1022                 d1 = r1;
1023                 d2 = r2;
1024         }
1025         g = c; g.unit_normal();
1026         s = c1;
1027         s.divide(a.unit());
1028         s.divide(c.unit());
1029         t = c2;
1030         t.divide(b.unit());
1031         t.divide(c.unit());
1032 }
1033
1034 static ex replace_lc(const ex& poly, const ex& x, const ex& lc)
1035 {
1036         ex r = expand(poly + (lc - poly.lcoeff(x)) * pow(x, poly.degree(x)));
1037         return r;
1038 }
1039
1040 static ex hensel_univar(const ex& a_, const ex& x, unsigned int p, const UniPoly& u1_, const UniPoly& w1_, const ex& gamma_ = 0)
1041 {
1042         ex a = a_;
1043         const cl_modint_ring& R = u1_.R;
1044
1045         // calc bound B
1046         ex maxcoeff;
1047         for ( int i=a.degree(x); i>=a.ldegree(x); --i ) {
1048                 maxcoeff += pow(abs(a.coeff(x, i)),2);
1049         }
1050         cl_I normmc = ceiling1(the<cl_R>(cln::sqrt(ex_to<numeric>(maxcoeff).to_cl_N())));
1051         cl_I maxdegree = (u1_.degree() > w1_.degree()) ? u1_.degree() : w1_.degree();
1052         cl_I B = normmc * expt_pos(cl_I(2), maxdegree);
1053
1054         // step 1
1055         ex alpha = a.lcoeff(x);
1056         ex gamma = gamma_;
1057         if ( gamma == 0 ) {
1058                 gamma = alpha;
1059         }
1060         numeric gamma_ui = ex_to<numeric>(abs(gamma));
1061         a = a * gamma;
1062         UniPoly nu1 = u1_;
1063         nu1.unit_normal();
1064         UniPoly nw1 = w1_;
1065         nw1.unit_normal();
1066         ex phi;
1067         phi = expand(gamma * nu1.to_ex(x));
1068         UniPoly u1(R, phi, x);
1069         phi = expand(alpha * nw1.to_ex(x));
1070         UniPoly w1(R, phi, x);
1071
1072         // step 2
1073         UniPoly s(R), t(R), g(R);
1074         exteuclid(u1, w1, g, s, t);
1075
1076         // step 3
1077         ex u = replace_lc(u1.to_ex(x), x, gamma);
1078         ex w = replace_lc(w1.to_ex(x), x, alpha);
1079         ex e = expand(a - u * w);
1080         numeric modulus = p;
1081         const numeric maxmodulus = 2*numeric(B)*gamma_ui;
1082
1083         // step 4
1084         while ( !e.is_zero() && modulus < maxmodulus ) {
1085                 ex c = e / modulus;
1086                 phi = expand(s.to_ex(x)*c);
1087                 UniPoly sigmatilde(R, phi, x);
1088                 phi = expand(t.to_ex(x)*c);
1089                 UniPoly tautilde(R, phi, x);
1090                 UniPoly q(R), r(R);
1091                 div(sigmatilde, w1, q);
1092                 rem(sigmatilde, w1, r);
1093                 UniPoly sigma = r;
1094                 phi = expand(tautilde.to_ex(x) + q.to_ex(x) * u1.to_ex(x));
1095                 UniPoly tau(R, phi, x);
1096                 u = expand(u + tau.to_ex(x) * modulus);
1097                 w = expand(w + sigma.to_ex(x) * modulus);
1098                 e = expand(a - u * w);
1099                 modulus = modulus * p;
1100         }
1101
1102         // step 5
1103         if ( e.is_zero() ) {
1104                 ex delta = u.content(x);
1105                 u = u / delta;
1106                 w = w / gamma * delta;
1107                 return lst(u, w);
1108         }
1109         else {
1110                 return lst();
1111         }
1112 }
1113
1114 static unsigned int next_prime(unsigned int p)
1115 {
1116         static vector<unsigned int> primes;
1117         if ( primes.size() == 0 ) {
1118                 primes.push_back(3); primes.push_back(5); primes.push_back(7);
1119         }
1120         vector<unsigned int>::const_iterator it = primes.begin();
1121         if ( p >= primes.back() ) {
1122                 unsigned int candidate = primes.back() + 2;
1123                 while ( true ) {
1124                         size_t n = primes.size()/2;
1125                         for ( size_t i=0; i<n; ++i ) {
1126                                 if ( candidate % primes[i] ) continue;
1127                                 candidate += 2;
1128                                 i=-1;
1129                         }
1130                         primes.push_back(candidate);
1131                         if ( candidate > p ) break;
1132                 }
1133                 return candidate;
1134         }
1135         vector<unsigned int>::const_iterator end = primes.end();
1136         for ( ; it!=end; ++it ) {
1137                 if ( *it > p ) {
1138                         return *it;
1139                 }
1140         }
1141         throw logic_error("next_prime: should not reach this point!");
1142 }
1143
1144 class Partition
1145 {
1146 public:
1147         Partition(size_t n_) : n(n_)
1148         {
1149                 k.resize(n, 1);
1150                 k[0] = 0;
1151                 sum = n-1;
1152         }
1153         int operator[](size_t i) const { return k[i]; }
1154         size_t size() const { return n; }
1155         size_t size_first() const { return n-sum; }
1156         size_t size_second() const { return sum; }
1157 #ifdef DEBUGFACTOR
1158         void get() const
1159         {
1160                 for ( size_t i=0; i<k.size(); ++i ) {
1161                         cout << k[i] << " ";
1162                 }
1163                 cout << endl;
1164         }
1165 #endif
1166         bool next()
1167         {
1168                 for ( size_t i=n-1; i>=1; --i ) {
1169                         if ( k[i] ) {
1170                                 --k[i];
1171                                 --sum;
1172                                 return sum > 0;
1173                         }
1174                         ++k[i];
1175                         ++sum;
1176                 }
1177                 return false;
1178         }
1179 private:
1180         size_t n, sum;
1181         vector<int> k;
1182 };
1183
1184 static void split(const UniPolyVec& factors, const Partition& part, UniPoly& a, UniPoly& b)
1185 {
1186         a.set(0, a.R->one());
1187         b.set(0, a.R->one());
1188         for ( size_t i=0; i<part.size(); ++i ) {
1189                 if ( part[i] ) {
1190                         b = b * factors[i];
1191                 }
1192                 else {
1193                         a = a * factors[i];
1194                 }
1195         }
1196 }
1197
1198 struct ModFactors
1199 {
1200         ex poly;
1201         UniPolyVec factors;
1202 };
1203
1204 static ex factor_univariate(const ex& poly, const ex& x)
1205 {
1206         ex unit, cont, prim;
1207         poly.unitcontprim(x, unit, cont, prim);
1208
1209         // determine proper prime
1210         unsigned int p = 3;
1211         cl_modint_ring R = find_modint_ring(p);
1212         while ( true ) {
1213                 if ( irem(ex_to<numeric>(prim.lcoeff(x)), p) != 0 ) {
1214                         UniPoly modpoly(R, prim, x);
1215                         UniFactorVec sqrfree_ufv;
1216                         squarefree(modpoly, sqrfree_ufv);
1217                         if ( sqrfree_ufv.factors.size() == 1 && sqrfree_ufv.factors.front().exp == 1 ) break;
1218                 }
1219                 p = next_prime(p);
1220                 R = find_modint_ring(p);
1221         }
1222
1223         // do modular factorization
1224         UniPoly modpoly(R, prim, x);
1225         UniPolyVec factors;
1226         factor_modular(modpoly, factors);
1227         if ( factors.size() <= 1 ) {
1228                 // irreducible for sure
1229                 return poly;
1230         }
1231
1232         // lift all factor combinations
1233         stack<ModFactors> tocheck;
1234         ModFactors mf;
1235         mf.poly = prim;
1236         mf.factors = factors;
1237         tocheck.push(mf);
1238         ex result = 1;
1239         while ( tocheck.size() ) {
1240                 const size_t n = tocheck.top().factors.size();
1241                 Partition part(n);
1242                 while ( true ) {
1243                         UniPoly a(R), b(R);
1244                         split(tocheck.top().factors, part, a, b);
1245
1246                         ex answer = hensel_univar(tocheck.top().poly, x, p, a, b);
1247                         if ( answer != lst() ) {
1248                                 if ( part.size_first() == 1 ) {
1249                                         if ( part.size_second() == 1 ) {
1250                                                 result *= answer.op(0) * answer.op(1);
1251                                                 tocheck.pop();
1252                                                 break;
1253                                         }
1254                                         result *= answer.op(0);
1255                                         tocheck.top().poly = answer.op(1);
1256                                         for ( size_t i=0; i<n; ++i ) {
1257                                                 if ( part[i] == 0 ) {
1258                                                         tocheck.top().factors.erase(tocheck.top().factors.begin()+i);
1259                                                         break;
1260                                                 }
1261                                         }
1262                                         break;
1263                                 }
1264                                 else if ( part.size_second() == 1 ) {
1265                                         if ( part.size_first() == 1 ) {
1266                                                 result *= answer.op(0) * answer.op(1);
1267                                                 tocheck.pop();
1268                                                 break;
1269                                         }
1270                                         result *= answer.op(1);
1271                                         tocheck.top().poly = answer.op(0);
1272                                         for ( size_t i=0; i<n; ++i ) {
1273                                                 if ( part[i] == 1 ) {
1274                                                         tocheck.top().factors.erase(tocheck.top().factors.begin()+i);
1275                                                         break;
1276                                                 }
1277                                         }
1278                                         break;
1279                                 }
1280                                 else {
1281                                         UniPolyVec newfactors1(part.size_first(), R), newfactors2(part.size_second(), R);
1282                                         UniPolyVec::iterator i1 = newfactors1.begin(), i2 = newfactors2.begin();
1283                                         for ( size_t i=0; i<n; ++i ) {
1284                                                 if ( part[i] ) {
1285                                                         *i2++ = tocheck.top().factors[i];
1286                                                 }
1287                                                 else {
1288                                                         *i1++ = tocheck.top().factors[i];
1289                                                 }
1290                                         }
1291                                         tocheck.top().factors = newfactors1;
1292                                         tocheck.top().poly = answer.op(0);
1293                                         ModFactors mf;
1294                                         mf.factors = newfactors2;
1295                                         mf.poly = answer.op(1);
1296                                         tocheck.push(mf);
1297                                         break;
1298                                 }
1299                         }
1300                         else {
1301                                 if ( !part.next() ) {
1302                                         result *= tocheck.top().poly;
1303                                         tocheck.pop();
1304                                         break;
1305                                 }
1306                         }
1307                 }
1308         }
1309
1310         return unit * cont * result;
1311 }
1312
1313 struct FindSymbolsMap : public map_function {
1314         exset syms;
1315         ex operator()(const ex& e)
1316         {
1317                 if ( is_a<symbol>(e) ) {
1318                         syms.insert(e);
1319                         return e;
1320                 }
1321                 return e.map(*this);
1322         }
1323 };
1324
1325 struct EvalPoint
1326 {
1327         ex x;
1328         int evalpoint;
1329 };
1330
1331 // forward declaration
1332 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);
1333
1334 UniPolyVec multiterm_eea_lift(const UniPolyVec& a, const ex& x, unsigned int p, unsigned int k)
1335 {
1336         DCOUT(multiterm_eea_lift);
1337         DCOUTVAR(a);
1338         DCOUTVAR(p);
1339         DCOUTVAR(k);
1340
1341         const size_t r = a.size();
1342         DCOUTVAR(r);
1343         cl_modint_ring R = find_modint_ring(expt_pos(cl_I(p),k));
1344         UniPoly fill(R);
1345         UniPolyVec q(r-1, fill);
1346         q[r-2] = a[r-1];
1347         for ( size_t j=r-2; j>=1; --j ) {
1348                 q[j-1] = a[j] * q[j];
1349         }
1350         DCOUTVAR(q);
1351         UniPoly beta(R);
1352         beta.set(0, R->one());
1353         UniPolyVec s;
1354         for ( size_t j=1; j<r; ++j ) {
1355                 DCOUTVAR(j);
1356                 DCOUTVAR(beta);
1357                 vector<ex> mdarg(2);
1358                 mdarg[0] = q[j-1].to_ex(x);
1359                 mdarg[1] = a[j-1].to_ex(x);
1360                 vector<EvalPoint> empty;
1361                 vector<ex> exsigma = multivar_diophant(mdarg, x, beta.to_ex(x), empty, 0, p, k);
1362                 UniPoly sigma1(R, exsigma[0], x);
1363                 UniPoly sigma2(R, exsigma[1], x);
1364                 beta = sigma1;
1365                 s.push_back(sigma2);
1366         }
1367         s.push_back(beta);
1368
1369         DCOUTVAR(s);
1370         DCOUT(END multiterm_eea_lift);
1371         return s;
1372 }
1373
1374 void eea_lift(const UniPoly& a, const UniPoly& b, const ex& x, unsigned int p, unsigned int k, UniPoly& s_, UniPoly& t_)
1375 {
1376         DCOUT(eea_lift);
1377         DCOUTVAR(a);
1378         DCOUTVAR(b);
1379         DCOUTVAR(x);
1380         DCOUTVAR(p);
1381         DCOUTVAR(k);
1382
1383         cl_modint_ring R = find_modint_ring(p);
1384         UniPoly amod(R, a);
1385         UniPoly bmod(R, b);
1386         DCOUTVAR(amod);
1387         DCOUTVAR(bmod);
1388
1389         UniPoly smod(R), tmod(R), g(R);
1390         exteuclid(amod, bmod, g, smod, tmod);
1391         
1392         DCOUTVAR(smod);
1393         DCOUTVAR(tmod);
1394         DCOUTVAR(g);
1395
1396         cl_modint_ring Rpk = find_modint_ring(expt_pos(cl_I(p),k));
1397         UniPoly s(Rpk, smod);
1398         UniPoly t(Rpk, tmod);
1399         DCOUTVAR(s);
1400         DCOUTVAR(t);
1401
1402         cl_I modulus(p);
1403
1404         UniPoly one(Rpk);
1405         one.set(0, Rpk->one());
1406         for ( size_t j=1; j<k; ++j ) {
1407                 UniPoly e = one - a * s - b * t;
1408                 e.divide(modulus);
1409                 UniPoly c(R, e);
1410                 UniPoly sigmabar(R);
1411                 sigmabar = smod * c;
1412                 UniPoly taubar(R);
1413                 taubar = tmod * c;
1414                 UniPoly q(R);
1415                 div(sigmabar, bmod, q);
1416                 UniPoly sigma(R);
1417                 rem(sigmabar, bmod, sigma);
1418                 UniPoly tau(R);
1419                 tau = taubar + q * amod;
1420                 UniPoly sadd(Rpk, sigma);
1421                 cl_MI modmodulus(Rpk, modulus);
1422                 s = s + sadd * modmodulus;
1423                 UniPoly tadd(Rpk, tau);
1424                 t = t + tadd * modmodulus;
1425                 modulus = modulus * p;
1426         }
1427
1428         s_ = s; t_ = t;
1429
1430         DCOUTVAR(s);
1431         DCOUTVAR(t);
1432         DCOUT2(check, a*s + b*t);
1433         DCOUT(END eea_lift);
1434 }
1435
1436 UniPolyVec univar_diophant(const UniPolyVec& a, const ex& x, unsigned int m, unsigned int p, unsigned int k)
1437 {
1438         DCOUT(univar_diophant);
1439         DCOUTVAR(a);
1440         DCOUTVAR(x);
1441         DCOUTVAR(m);
1442         DCOUTVAR(p);
1443         DCOUTVAR(k);
1444
1445         cl_modint_ring R = find_modint_ring(expt_pos(cl_I(p),k));
1446
1447         const size_t r = a.size();
1448         UniPolyVec result;
1449         if ( r > 2 ) {
1450                 UniPolyVec s = multiterm_eea_lift(a, x, p, k);
1451                 for ( size_t j=0; j<r; ++j ) {
1452                         ex phi = expand(pow(x,m)*s[j].to_ex(x));
1453                         UniPoly bmod(R, phi, x);
1454                         UniPoly buf(R);
1455                         rem(bmod, a[j], buf);
1456                         result.push_back(buf);
1457                 }
1458         }
1459         else {
1460                 UniPoly s(R), t(R);
1461                 eea_lift(a[1], a[0], x, p, k, s, t);
1462                 ex phi = expand(pow(x,m)*s.to_ex(x));
1463                 UniPoly bmod(R, phi, x);
1464                 UniPoly buf(R);
1465                 rem(bmod, a[0], buf);
1466                 result.push_back(buf);
1467                 UniPoly q(R);
1468                 div(bmod, a[0], q);
1469                 phi = expand(pow(x,m)*t.to_ex(x));
1470                 UniPoly t1mod(R, phi, x);
1471                 buf = t1mod + q * a[1];
1472                 result.push_back(buf);
1473         }
1474
1475         DCOUTVAR(result);
1476         DCOUT(END univar_diophant);
1477         return result;
1478 }
1479
1480 struct make_modular_map : public map_function {
1481         cl_modint_ring R;
1482         make_modular_map(const cl_modint_ring& R_) : R(R_) { }
1483         ex operator()(const ex& e)
1484         {
1485                 if ( is_a<add>(e) || is_a<mul>(e) ) {
1486                         return e.map(*this);
1487                 }
1488                 else if ( is_a<numeric>(e) ) {
1489                         numeric mod(R->modulus);
1490                         numeric halfmod = (mod-1)/2;
1491                         cl_MI emod = R->canonhom(the<cl_I>(ex_to<numeric>(e).to_cl_N()));
1492                         numeric n(R->retract(emod));
1493                         if ( n > halfmod ) {
1494                                 return n-mod;
1495                         }
1496                         else {
1497                                 return n;
1498                         }
1499                 }
1500                 return e;
1501         }
1502 };
1503
1504 static ex make_modular(const ex& e, const cl_modint_ring& R)
1505 {
1506         make_modular_map map(R);
1507         return map(e);
1508 }
1509
1510 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)
1511 {
1512         vector<ex> a = a_;
1513
1514         DCOUT(multivar_diophant);
1515 #ifdef DEBUGFACTOR
1516         cout << "a ";
1517         for ( size_t i=0; i<a.size(); ++i ) {
1518                 cout << a[i] << " ";
1519         }
1520         cout << endl;
1521 #endif
1522         DCOUTVAR(x);
1523         DCOUTVAR(c);
1524 #ifdef DEBUGFACTOR
1525         cout << "I ";
1526         for ( size_t i=0; i<I.size(); ++i ) {
1527                 cout << I[i].x << "=" << I[i].evalpoint << " ";
1528         }
1529         cout << endl;
1530 #endif
1531         DCOUTVAR(d);
1532         DCOUTVAR(p);
1533         DCOUTVAR(k);
1534
1535         const cl_modint_ring R = find_modint_ring(expt_pos(cl_I(p),k));
1536         const size_t r = a.size();
1537         const size_t nu = I.size() + 1;
1538         DCOUTVAR(r);
1539         DCOUTVAR(nu);
1540
1541         vector<ex> sigma;
1542         if ( nu > 1 ) {
1543                 ex xnu = I.back().x;
1544                 int alphanu = I.back().evalpoint;
1545
1546                 ex A = 1;
1547                 for ( size_t i=0; i<r; ++i ) {
1548                         A *= a[i];
1549                 }
1550                 vector<ex> b(r);
1551                 for ( size_t i=0; i<r; ++i ) {
1552                         b[i] = normal(A / a[i]);
1553                 }
1554
1555                 vector<ex> anew = a;
1556                 for ( size_t i=0; i<r; ++i ) {
1557                         a[i] = a[i].subs(xnu == alphanu);
1558                 }
1559                 ex cnew = c.subs(xnu == alphanu);
1560                 vector<EvalPoint> Inew = I;
1561                 Inew.pop_back();
1562                 vector<ex> sigma = multivar_diophant(anew, x, cnew, Inew, d, p, k);
1563
1564                 ex buf = c;
1565                 for ( size_t i=0; i<r; ++i ) {
1566                         buf -= sigma[i] * b[i];
1567                 }
1568                 ex e = buf;
1569                 e = make_modular(e, R);
1570
1571                 ex monomial = 1;
1572                 for ( size_t m=1; m<=d; ++m ) {
1573                         while ( !e.is_zero() ) {
1574                                 monomial *= (xnu - alphanu);
1575                                 monomial = expand(monomial);
1576                                 ex cm = e.diff(ex_to<symbol>(xnu), m).subs(xnu==alphanu) / factorial(m);
1577                                 if ( !cm.is_zero() ) {
1578                                         vector<ex> delta_s = multivar_diophant(anew, x, cm, Inew, d, p, k);
1579                                         ex buf = e;
1580                                         for ( size_t j=0; j<delta_s.size(); ++j ) {
1581                                                 delta_s[j] *= monomial;
1582                                                 sigma[j] += delta_s[j];
1583                                                 buf -= delta_s[j] * b[j];
1584                                         }
1585                                         e = buf;
1586                                         e = make_modular(e, R);
1587                                 }
1588                         }
1589                 }
1590         }
1591         else {
1592                 UniPolyVec amod;
1593                 for ( size_t i=0; i<a.size(); ++i ) {
1594                         UniPoly up(R, a[i], x);
1595                         amod.push_back(up);
1596                 }
1597
1598                 sigma.insert(sigma.begin(), r, 0);
1599                 size_t nterms;
1600                 ex z;
1601                 if ( is_a<add>(c) ) {
1602                         nterms = c.nops();
1603                         z = c.op(0);
1604                 }
1605                 else {
1606                         nterms = 1;
1607                         z = c;
1608                 }
1609                 DCOUTVAR(nterms);
1610                 for ( size_t i=0; i<nterms; ++i ) {
1611                         DCOUTVAR(z);
1612                         int m = z.degree(x);
1613                         DCOUTVAR(m);
1614                         cl_I cm = the<cl_I>(ex_to<numeric>(z.lcoeff(x)).to_cl_N());
1615                         DCOUTVAR(cm);
1616                         UniPolyVec delta_s = univar_diophant(amod, x, m, p, k);
1617                         cl_MI modcm;
1618                         cl_I poscm = cm;
1619                         while ( poscm < 0 ) {
1620                                 poscm = poscm + expt_pos(cl_I(p),k);
1621                         }
1622                         modcm = cl_MI(R, poscm);
1623                         DCOUTVAR(modcm);
1624                         for ( size_t j=0; j<delta_s.size(); ++j ) {
1625                                 delta_s[j] = delta_s[j] * modcm;
1626                                 sigma[j] = sigma[j] + delta_s[j].to_ex(x);
1627                         }
1628                         DCOUTVAR(delta_s);
1629 #ifdef DEBUGFACTOR
1630                         cout << "STEP " << i << " sigma ";
1631                         for ( size_t p=0; p<sigma.size(); ++p ) {
1632                                 cout << sigma[p] << " ";
1633                         }
1634                         cout << endl;
1635 #endif
1636                         if ( nterms > 1 ) {
1637                                 z = c.op(i+1);
1638                         }
1639                 }
1640         }
1641 #ifdef DEBUGFACTOR
1642         cout << "sigma ";
1643         for ( size_t i=0; i<sigma.size(); ++i ) {
1644                 cout << sigma[i] << " ";
1645         }
1646         cout << endl;
1647 #endif
1648
1649         for ( size_t i=0; i<sigma.size(); ++i ) {
1650                 sigma[i] = make_modular(sigma[i], R);
1651         }
1652
1653 #ifdef DEBUGFACTOR
1654         cout << "sigma ";
1655         for ( size_t i=0; i<sigma.size(); ++i ) {
1656                 cout << sigma[i] << " ";
1657         }
1658         cout << endl;
1659 #endif
1660         DCOUT(END multivar_diophant);
1661         return sigma;
1662 }
1663
1664 #ifdef DEBUGFACTOR
1665 ostream& operator<<(ostream& o, const vector<EvalPoint>& v)
1666 {
1667         for ( size_t i=0; i<v.size(); ++i ) {
1668                 o << "(" << v[i].x << "==" << v[i].evalpoint << ") ";
1669         }
1670         return o;
1671 }
1672 #endif // def DEBUGFACTOR
1673
1674
1675 ex hensel_multivar(const ex& a, const ex& x, const vector<EvalPoint>& I, unsigned int p, const cl_I& l, const UniPolyVec& u, const vector<ex>& lcU)
1676 {
1677         DCOUT(hensel_multivar);
1678         DCOUTVAR(a);
1679         DCOUTVAR(x);
1680         DCOUTVAR(I);
1681         DCOUTVAR(p);
1682         DCOUTVAR(l);
1683         DCOUTVAR(u);
1684         DCOUTVAR(lcU);
1685         const size_t nu = I.size() + 1;
1686         const cl_modint_ring R = find_modint_ring(expt_pos(cl_I(p),l));
1687
1688         DCOUTVAR(nu);
1689         
1690         vector<ex> A(nu);
1691         A[nu-1] = a;
1692
1693         for ( size_t j=nu; j>=2; --j ) {
1694                 ex x = I[j-2].x;
1695                 int alpha = I[j-2].evalpoint;
1696                 A[j-2] = A[j-1].subs(x==alpha);
1697                 A[j-2] = make_modular(A[j-2], R);
1698         }
1699
1700 #ifdef DEBUGFACTOR
1701         cout << "A ";
1702         for ( size_t i=0; i<A.size(); ++i) cout << A[i] << " ";
1703         cout << endl;
1704 #endif
1705
1706         int maxdeg = a.degree(I.front().x);
1707         for ( size_t i=1; i<I.size(); ++i ) {
1708                 int maxdeg2 = a.degree(I[i].x);
1709                 if ( maxdeg2 > maxdeg ) maxdeg = maxdeg2;
1710         }
1711         DCOUTVAR(maxdeg);
1712
1713         const size_t n = u.size();
1714         DCOUTVAR(n);
1715         vector<ex> U(n);
1716         for ( size_t i=0; i<n; ++i ) {
1717                 U[i] = u[i].to_ex(x);
1718         }
1719 #ifdef DEBUGFACTOR
1720         cout << "U ";
1721         for ( size_t i=0; i<U.size(); ++i) cout << U[i] << " ";
1722         cout << endl;
1723 #endif
1724
1725         for ( size_t j=2; j<=nu; ++j ) {
1726                 DCOUTVAR(j);
1727                 vector<ex> U1 = U;
1728                 ex monomial = 1;
1729                 for ( size_t m=0; m<n; ++m) {
1730                         if ( lcU[m] != 1 ) {
1731                                 ex coef = lcU[m];
1732                                 for ( size_t i=j-1; i<nu-1; ++i ) {
1733                                         coef = coef.subs(I[i].x == I[i].evalpoint);
1734                                 }
1735                                 coef = expand(coef);
1736                                 coef = make_modular(coef, R);
1737                                 int deg = U[m].degree(x);
1738                                 U[m] = U[m] - U[m].lcoeff(x) * pow(x,deg) + coef * pow(x,deg);
1739                         }
1740                 }
1741                 ex Uprod = 1;
1742                 for ( size_t i=0; i<n; ++i ) {
1743                         Uprod *= U[i];
1744                 }
1745                 ex e = expand(A[j-1] - Uprod);
1746                 DCOUTVAR(e);
1747
1748                 ex xj = I[j-2].x;
1749                 int alphaj = I[j-2].evalpoint;
1750                 size_t deg = A[j-1].degree(xj);
1751                 DCOUTVAR(deg);
1752                 for ( size_t k=1; k<=deg; ++k ) {
1753                         DCOUTVAR(k);
1754                         if ( !e.is_zero() ) {
1755                                 DCOUTVAR(xj);
1756                                 DCOUTVAR(alphaj);
1757                                 monomial *= (xj - alphaj);
1758                                 monomial = expand(monomial);
1759                                 DCOUTVAR(monomial);
1760                                 ex dif = e.diff(ex_to<symbol>(xj), k);
1761                                 DCOUTVAR(dif);
1762                                 ex c = dif.subs(xj==alphaj) / factorial(k);
1763                                 DCOUTVAR(c);
1764                                 if ( !c.is_zero() ) {
1765                                         vector<EvalPoint> newI = I;
1766                                         newI.pop_back();
1767                                         vector<ex> deltaU = multivar_diophant(U1, x, c, newI, maxdeg, p, cl_I_to_uint(l));
1768                                         for ( size_t i=0; i<n; ++i ) {
1769                                                 DCOUTVAR(i);
1770                                                 DCOUTVAR(deltaU[i]);
1771                                                 deltaU[i] *= monomial;
1772                                                 U[i] += deltaU[i];
1773                                                 U[i] = make_modular(U[i], R);
1774                                         }
1775                                         ex Uprod = 1;
1776                                         for ( size_t i=0; i<n; ++i ) {
1777                                                 Uprod *= U[i];
1778                                         }
1779                                         e = expand(A[j-1] - Uprod);
1780                                         e = make_modular(e, R);
1781                                         DCOUTVAR(e);
1782                                 }
1783                                 else {
1784                                         break;
1785                                 }
1786                         }
1787                 }
1788         }
1789
1790         ex acand = 1;
1791         for ( size_t i=0; i<U.size(); ++i ) {
1792                 acand *= U[i];
1793         }
1794         DCOUTVAR(acand);
1795         if ( expand(a-acand).is_zero() ) {
1796                 lst res;
1797                 for ( size_t i=0; i<U.size(); ++i ) {
1798                         res.append(U[i]);
1799                 }
1800                 DCOUTVAR(res);
1801                 DCOUT(END hensel_multivar);
1802                 return res;
1803         }
1804         else {
1805                 lst res;
1806                 DCOUTVAR(res);
1807                 DCOUT(END hensel_multivar);
1808                 return lst();
1809         }
1810 }
1811
1812 static ex put_factors_into_lst(const ex& e)
1813 {
1814         DCOUT(put_factors_into_lst);
1815         DCOUTVAR(e);
1816
1817         lst result;
1818
1819         if ( is_a<numeric>(e) ) {
1820                 result.append(e);
1821                 DCOUT(END put_factors_into_lst);
1822                 DCOUTVAR(result);
1823                 return result;
1824         }
1825         if ( is_a<power>(e) ) {
1826                 result.append(1);
1827                 result.append(e.op(0));
1828                 result.append(e.op(1));
1829                 DCOUT(END put_factors_into_lst);
1830                 DCOUTVAR(result);
1831                 return result;
1832         }
1833         if ( is_a<symbol>(e) ) {
1834                 result.append(1);
1835                 result.append(e);
1836                 result.append(1);
1837                 DCOUT(END put_factors_into_lst);
1838                 DCOUTVAR(result);
1839                 return result;
1840         }
1841         if ( is_a<mul>(e) ) {
1842                 ex nfac = 1;
1843                 for ( size_t i=0; i<e.nops(); ++i ) {
1844                         ex op = e.op(i);
1845                         if ( is_a<numeric>(op) ) {
1846                                 nfac = op;
1847                         }
1848                         if ( is_a<power>(op) ) {
1849                                 result.append(op.op(0));
1850                                 result.append(op.op(1));
1851                         }
1852                         if ( is_a<symbol>(op) || is_a<add>(op) ) {
1853                                 result.append(op);
1854                                 result.append(1);
1855                         }
1856                 }
1857                 result.prepend(nfac);
1858                 DCOUT(END put_factors_into_lst);
1859                 DCOUTVAR(result);
1860                 return result;
1861         }
1862         throw runtime_error("put_factors_into_lst: bad term.");
1863 }
1864
1865 static bool checkdivisors(const lst& f, vector<numeric>& d)
1866 {
1867         const int k = f.nops()-2;
1868         numeric q, r;
1869         d[0] = ex_to<numeric>(f.op(0) * f.op(f.nops()-1));
1870         for ( int i=1; i<=k; ++i ) {
1871                 q = ex_to<numeric>(abs(f.op(i-1)));
1872                 for ( int j=i-1; j>=0; --j ) {
1873                         r = d[j];
1874                         do {
1875                                 r = gcd(r, q);
1876                                 q = q/r;
1877                         } while ( r != 1 );
1878                         if ( q == 1 ) {
1879                                 return true;
1880                         }
1881                 }
1882                 d[i] = q;
1883         }
1884         return false;
1885 }
1886
1887 static void generate_set(const ex& u, const ex& vn, const exset& syms, const ex& f, const numeric& modulus, vector<numeric>& a, vector<numeric>& d)
1888 {
1889         const ex& x = *syms.begin();
1890         bool trying = true;
1891         do {
1892                 ex u0 = u;
1893                 ex vna = vn;
1894                 ex vnatry;
1895                 exset::const_iterator s = syms.begin();
1896                 ++s;
1897                 for ( size_t i=0; i<a.size(); ++i ) {
1898                         do {
1899                                 a[i] = mod(numeric(rand()), 2*modulus) - modulus;
1900                                 vnatry = vna.subs(*s == a[i]);
1901                         } while ( vnatry == 0 );
1902                         vna = vnatry;
1903                         u0 = u0.subs(*s == a[i]);
1904                 }
1905                 if ( gcd(u0,u0.diff(ex_to<symbol>(x))) != 1 ) {
1906                         continue;
1907                 }
1908                 if ( is_a<numeric>(vn) ) {
1909                         d = a;
1910                         trying = false;
1911                 }
1912                 else {
1913                         lst fnum;
1914                         lst::const_iterator i = ex_to<lst>(f).begin();
1915                         fnum.append(*i++);
1916                         while ( i!=ex_to<lst>(f).end() ) {
1917                                 ex fs = *i;
1918                                 s = syms.begin();
1919                                 ++s;
1920                                 for ( size_t j=0; j<a.size(); ++j ) {
1921                                         fs = fs.subs(*s == a[j]);
1922                                 }
1923                                 fnum.append(fs);
1924                                 ++i; ++i;
1925                         }
1926                         ex con = u0.content(x);
1927                         fnum.append(con);
1928                         trying = checkdivisors(fnum, d);
1929                 }
1930         } while ( trying );
1931 }
1932
1933 #ifdef DEBUGFACTOR
1934 ostream& operator<<(ostream& o, const vector<numeric>& v)
1935 {
1936         for ( size_t i=0; i<v.size(); ++i ) {
1937                 o << v[i] << " ";
1938         }
1939         return o;
1940 }
1941 #endif // def DEBUGFACTOR
1942
1943 static ex factor_multivariate(const ex& poly, const exset& syms)
1944 {
1945         DCOUT(factor_multivariate);
1946         DCOUTVAR(poly);
1947
1948         exset::const_iterator s;
1949         const ex& x = *syms.begin();
1950         DCOUTVAR(x);
1951
1952         /* make polynomial primitive */
1953         ex p = poly.expand().collect(x);
1954         DCOUTVAR(p);
1955         ex cont = p.lcoeff(x);
1956         for ( numeric i=p.degree(x)-1; i>=p.ldegree(x); --i ) {
1957                 cont = gcd(cont, p.coeff(x,ex_to<numeric>(i).to_int()));
1958                 if ( cont == 1 ) break;
1959         }
1960         DCOUTVAR(cont);
1961         ex pp = expand(normal(p / cont));
1962         DCOUTVAR(pp);
1963         if ( !is_a<numeric>(cont) ) {
1964                 return factor(cont) * factor(pp);
1965         }
1966
1967         /* factor leading coefficient */
1968         pp = pp.collect(x);
1969         ex vn = pp.lcoeff(x);
1970         pp = pp.expand();
1971         ex vnlst;
1972         if ( is_a<numeric>(vn) ) {
1973                 vnlst = lst(vn);
1974         }
1975         else {
1976                 ex vnfactors = factor(vn);
1977                 vnlst = put_factors_into_lst(vnfactors);
1978         }
1979         DCOUTVAR(vnlst);
1980
1981         const numeric maxtrials = 3;
1982         numeric modulus = (vnlst.nops()-1 > 3) ? vnlst.nops()-1 : 3;
1983         numeric minimalr = -1;
1984         vector<numeric> a(syms.size()-1);
1985         vector<numeric> d(syms.size()-1);
1986
1987         while ( true ) {
1988                 numeric trialcount = 0;
1989                 ex u, delta;
1990                 unsigned int prime;
1991                 UniPolyVec uvec;
1992                 while ( trialcount < maxtrials ) {
1993                         uvec.clear();
1994                         generate_set(pp, vn, syms, vnlst, modulus, a, d);
1995                         DCOUTVAR(a);
1996                         DCOUTVAR(d);
1997                         u = pp;
1998                         s = syms.begin();
1999                         ++s;
2000                         for ( size_t i=0; i<a.size(); ++i ) {
2001                                 u = u.subs(*s == a[i]);
2002                                 ++s;
2003                         }
2004                         delta = u.content(x);
2005
2006                         // determine proper prime
2007                         prime = 3;
2008                         cl_modint_ring R = find_modint_ring(prime);
2009                         while ( true ) {
2010                                 if ( irem(ex_to<numeric>(u.lcoeff(x)), prime) != 0 ) {
2011                                         UniPoly modpoly(R, u, x);
2012                                         UniFactorVec sqrfree_ufv;
2013                                         squarefree(modpoly, sqrfree_ufv);
2014                                         if ( sqrfree_ufv.factors.size() == 1 && sqrfree_ufv.factors.front().exp == 1 ) break;
2015                                 }
2016                                 prime = next_prime(prime);
2017                                 R = find_modint_ring(prime);
2018                         }
2019
2020                         UniPoly umod(R, u, x);
2021                         DCOUTVAR(u);
2022                         factor_modular(umod, uvec);
2023                         DCOUTVAR(uvec);
2024
2025                         if ( uvec.size() == 1 ) {
2026                                 DCOUTVAR(poly);
2027                                 DCOUT(END factor_multivariate);
2028                                 return poly;
2029                         }
2030
2031                         if ( minimalr < 0 ) {
2032                                 minimalr = uvec.size();
2033                         }
2034                         else if ( minimalr == uvec.size() ) {
2035                                 ++trialcount;
2036                                 ++modulus;
2037                         }
2038                         else if ( minimalr > uvec.size() ) {
2039                                 minimalr = uvec.size();
2040                                 trialcount = 0;
2041                         }
2042                         DCOUTVAR(trialcount);
2043                         DCOUTVAR(minimalr);
2044                         if ( minimalr == 0 ) {
2045                                 DCOUTVAR(poly);
2046                                 DCOUT(END factor_multivariate);
2047                                 return poly;
2048                         }
2049                 }
2050
2051                 vector<ex> C;
2052                 if ( vnlst.nops() == 1 ) {
2053                         C.resize(uvec.size(), 1);
2054                 }
2055                 else {
2056
2057                         vector<numeric> ftilde((vnlst.nops()-1)/2);
2058                         for ( size_t i=0; i<ftilde.size(); ++i ) {
2059                                 ex ft = vnlst.op(i*2+1);
2060                                 s = syms.begin();
2061                                 ++s;
2062                                 for ( size_t j=0; j<a.size(); ++j ) {
2063                                         ft = ft.subs(*s == a[j]);
2064                                         ++s;
2065                                 }
2066                                 ftilde[i] = ex_to<numeric>(ft);
2067                         }
2068                         DCOUTVAR(ftilde);
2069
2070                         vector<ex> D;
2071                         vector<bool> fflag(ftilde.size(), false);
2072                         for ( size_t i=0; i<uvec.size(); ++i ) {
2073                                 ex ui = uvec[i].to_ex(x);
2074                                 ex Di = 1;
2075                                 numeric coeff = ex_to<numeric>(ui.lcoeff(x));
2076                                 for ( size_t j=0; j<ftilde.size(); ++j ) {
2077                                         if ( numeric(coeff / ftilde[j]).is_integer() ) {
2078                                                 coeff = coeff / ftilde[j];
2079                                                 Di *= ftilde[j];
2080                                                 fflag[j] = true;
2081                                                 --j;
2082                                         }
2083                                 }
2084                                 D.push_back(Di.expand());
2085                         }
2086                         for ( size_t i=0; i<fflag.size(); ++i ) {
2087                                 if ( !fflag[i] ) {
2088                                         --minimalr;
2089                                         continue;
2090                                 }
2091                         }
2092                         DCOUTVAR(D);
2093
2094                         C.resize(D.size());
2095                         if ( delta == 1 ) {
2096                                 for ( size_t i=0; i<D.size(); ++i ) {
2097                                         ex Dtilde = D[i];
2098                                         s = syms.begin();
2099                                         ++s;
2100                                         for ( size_t j=0; j<a.size(); ++j ) {
2101                                                 Dtilde = Dtilde.subs(*s == a[j]);
2102                                                 ++s;
2103                                         }
2104                                         ex Ci = D[i] * (uvec[i].to_ex(x).lcoeff(x) / Dtilde);
2105                                         C.push_back(Ci);
2106                                 }
2107                         }
2108                         else {
2109                                 for ( size_t i=0; i<D.size(); ++i ) {
2110                                         ex Dtilde = D[i];
2111                                         s = syms.begin();
2112                                         ++s;
2113                                         for ( size_t j=0; j<a.size(); ++j ) {
2114                                                 Dtilde = Dtilde.subs(*s == a[j]);
2115                                                 ++s;
2116                                         }
2117                                         ex ui = uvec[i].to_ex(x);
2118                                         ex Ci;
2119                                         while ( true ) {
2120                                                 ex d = gcd(ui.lcoeff(x), Dtilde);
2121                                                 Ci = D[i] * ( ui.lcoeff(x) / d );
2122                                                 ui = ui * ( Dtilde[i] / d );
2123                                                 delta = delta / ( Dtilde[i] / d );
2124                                                 if ( delta == 1 ) break;
2125                                                 ui = delta * ui;
2126                                                 Ci = delta * Ci;
2127                                                 pp = pp * pow(delta, D.size()-1);
2128                                         }
2129                                 }
2130                         }
2131
2132                 }
2133
2134                 EvalPoint ep;
2135                 vector<EvalPoint> epv;
2136                 s = syms.begin();
2137                 ++s;
2138                 for ( size_t i=0; i<a.size(); ++i ) {
2139                         ep.x = *s++;
2140                         ep.evalpoint = a[i].to_int();
2141                         epv.push_back(ep);
2142                 }
2143
2144                 // calc bound B
2145                 ex maxcoeff;
2146                 for ( int i=u.degree(x); i>=u.ldegree(x); --i ) {
2147                         maxcoeff += pow(abs(u.coeff(x, i)),2);
2148                 }
2149                 cl_I normmc = ceiling1(the<cl_R>(cln::sqrt(ex_to<numeric>(maxcoeff).to_cl_N())));
2150                 unsigned int maxdegree = 0;
2151                 for ( size_t i=0; i<uvec.size(); ++i ) {
2152                         if ( uvec[i].degree() > maxdegree ) {
2153                                 maxdegree = uvec[i].degree();
2154                         }
2155                 }
2156                 cl_I B = normmc * expt_pos(cl_I(2), maxdegree);
2157                 cl_I l = 1;
2158                 cl_I pl = prime;
2159                 while ( pl < B ) {
2160                         l += 1;
2161                         pl = pl * prime;
2162                 }
2163
2164                 ex res = hensel_multivar(pp, x, epv, prime, l, uvec, C);
2165                 if ( res != lst() ) {
2166                         ex result = cont;
2167                         for ( size_t i=0; i<res.nops(); ++i ) {
2168                                 result *= res.op(i).content(x) * res.op(i).unit(x);
2169                                 result *= res.op(i).primpart(x);
2170                         }
2171                         DCOUTVAR(result);
2172                         DCOUT(END factor_multivariate);
2173                         return result;
2174                 }
2175         }
2176 }
2177
2178 static ex factor_sqrfree(const ex& poly)
2179 {
2180         // determine all symbols in poly
2181         FindSymbolsMap findsymbols;
2182         findsymbols(poly);
2183         if ( findsymbols.syms.size() == 0 ) {
2184                 return poly;
2185         }
2186
2187         if ( findsymbols.syms.size() == 1 ) {
2188                 // univariate case
2189                 const ex& x = *(findsymbols.syms.begin());
2190                 if ( poly.ldegree(x) > 0 ) {
2191                         int ld = poly.ldegree(x);
2192                         ex res = factor_univariate(expand(poly/pow(x, ld)), x);
2193                         return res * pow(x,ld);
2194                 }
2195                 else {
2196                         ex res = factor_univariate(poly, x);
2197                         return res;
2198                 }
2199         }
2200
2201         // multivariate case
2202         ex res = factor_multivariate(poly, findsymbols.syms);
2203         return res;
2204 }
2205
2206 } // anonymous namespace
2207
2208 ex factor(const ex& poly)
2209 {
2210         // determine all symbols in poly
2211         FindSymbolsMap findsymbols;
2212         findsymbols(poly);
2213         if ( findsymbols.syms.size() == 0 ) {
2214                 return poly;
2215         }
2216         lst syms;
2217         exset::const_iterator i=findsymbols.syms.begin(), end=findsymbols.syms.end();
2218         for ( ; i!=end; ++i ) {
2219                 syms.append(*i);
2220         }
2221
2222         // make poly square free
2223         ex sfpoly = sqrfree(poly, syms);
2224
2225         // factorize the square free components
2226         if ( is_a<power>(sfpoly) ) {
2227                 // case: (polynomial)^exponent
2228                 const ex& base = sfpoly.op(0);
2229                 if ( !is_a<add>(base) ) {
2230                         // simple case: (monomial)^exponent
2231                         return sfpoly;
2232                 }
2233                 ex f = factor_sqrfree(base);
2234                 return pow(f, sfpoly.op(1));
2235         }
2236         if ( is_a<mul>(sfpoly) ) {
2237                 ex res = 1;
2238                 for ( size_t i=0; i<sfpoly.nops(); ++i ) {
2239                         const ex& t = sfpoly.op(i);
2240                         if ( is_a<power>(t) ) {
2241                                 const ex& base = t.op(0);
2242                                 if ( !is_a<add>(base) ) {
2243                                         res *= t;
2244                                 }
2245                                 else {
2246                                         ex f = factor_sqrfree(base);
2247                                         res *= pow(f, t.op(1));
2248                                 }
2249                         }
2250                         else if ( is_a<add>(t) ) {
2251                                 ex f = factor_sqrfree(t);
2252                                 res *= f;
2253                         }
2254                         else {
2255                                 res *= t;
2256                         }
2257                 }
2258                 return res;
2259         }
2260         if ( is_a<symbol>(sfpoly) ) {
2261                 return poly;
2262         }
2263         // case: (polynomial)
2264         ex f = factor_sqrfree(sfpoly);
2265         return f;
2266 }
2267
2268 } // namespace GiNaC