Added internal code for multivariate factorization.
[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                         int coeff = ex_to<numeric>(poly.coeff(x,i)).to_int();
128                         if ( 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         unsigned int maxdegree = (u1_.degree() > w1_.degree()) ? u1_.degree() : w1_.degree();
1052         unsigned int B = cl_I_to_uint(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         unsigned int gamma_ui = ex_to<numeric>(abs(gamma)).to_int();
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         unsigned int modulus = p;
1081
1082         // step 4
1083         while ( !e.is_zero() && modulus < 2*B*gamma_ui ) {
1084                 ex c = e / modulus;
1085                 phi = expand(s.to_ex(x)*c);
1086                 UniPoly sigmatilde(R, phi, x);
1087                 phi = expand(t.to_ex(x)*c);
1088                 UniPoly tautilde(R, phi, x);
1089                 UniPoly q(R), r(R);
1090                 div(sigmatilde, w1, q);
1091                 rem(sigmatilde, w1, r);
1092                 UniPoly sigma = r;
1093                 phi = expand(tautilde.to_ex(x) + q.to_ex(x) * u1.to_ex(x));
1094                 UniPoly tau(R, phi, x);
1095                 u = expand(u + tau.to_ex(x) * modulus);
1096                 w = expand(w + sigma.to_ex(x) * modulus);
1097                 e = expand(a - u * w);
1098                 modulus = modulus * p;
1099         }
1100
1101         // step 5
1102         if ( e.is_zero() ) {
1103                 ex delta = u.content(x);
1104                 u = u / delta;
1105                 w = w / gamma * delta;
1106                 return lst(u, w);
1107         }
1108         else {
1109                 return lst();
1110         }
1111 }
1112
1113 static unsigned int next_prime(unsigned int p)
1114 {
1115         static vector<unsigned int> primes;
1116         if ( primes.size() == 0 ) {
1117                 primes.push_back(3); primes.push_back(5); primes.push_back(7);
1118         }
1119         vector<unsigned int>::const_iterator it = primes.begin();
1120         if ( p >= primes.back() ) {
1121                 unsigned int candidate = primes.back() + 2;
1122                 while ( true ) {
1123                         size_t n = primes.size()/2;
1124                         for ( size_t i=0; i<n; ++i ) {
1125                                 if ( candidate % primes[i] ) continue;
1126                                 candidate += 2;
1127                                 i=-1;
1128                         }
1129                         primes.push_back(candidate);
1130                         if ( candidate > p ) break;
1131                 }
1132                 return candidate;
1133         }
1134         vector<unsigned int>::const_iterator end = primes.end();
1135         for ( ; it!=end; ++it ) {
1136                 if ( *it > p ) {
1137                         return *it;
1138                 }
1139         }
1140         throw logic_error("next_prime: should not reach this point!");
1141 }
1142
1143 class Partition
1144 {
1145 public:
1146         Partition(size_t n_) : n(n_)
1147         {
1148                 k.resize(n, 1);
1149                 k[0] = 0;
1150                 sum = n-1;
1151         }
1152         int operator[](size_t i) const { return k[i]; }
1153         size_t size() const { return n; }
1154         size_t size_first() const { return n-sum; }
1155         size_t size_second() const { return sum; }
1156 #ifdef DEBUGFACTOR
1157         void get() const
1158         {
1159                 for ( size_t i=0; i<k.size(); ++i ) {
1160                         cout << k[i] << " ";
1161                 }
1162                 cout << endl;
1163         }
1164 #endif
1165         bool next()
1166         {
1167                 for ( size_t i=n-1; i>=1; --i ) {
1168                         if ( k[i] ) {
1169                                 --k[i];
1170                                 --sum;
1171                                 return sum > 0;
1172                         }
1173                         ++k[i];
1174                         ++sum;
1175                 }
1176                 return false;
1177         }
1178 private:
1179         size_t n, sum;
1180         vector<int> k;
1181 };
1182
1183 static void split(const UniPolyVec& factors, const Partition& part, UniPoly& a, UniPoly& b)
1184 {
1185         a.set(0, a.R->one());
1186         b.set(0, a.R->one());
1187         for ( size_t i=0; i<part.size(); ++i ) {
1188                 if ( part[i] ) {
1189                         b = b * factors[i];
1190                 }
1191                 else {
1192                         a = a * factors[i];
1193                 }
1194         }
1195 }
1196
1197 struct ModFactors
1198 {
1199         ex poly;
1200         UniPolyVec factors;
1201 };
1202
1203 static ex factor_univariate(const ex& poly, const ex& x)
1204 {
1205         ex unit, cont, prim;
1206         poly.unitcontprim(x, unit, cont, prim);
1207
1208         // determine proper prime
1209         unsigned int p = 3;
1210         cl_modint_ring R = find_modint_ring(p);
1211         while ( true ) {
1212                 if ( irem(ex_to<numeric>(prim.lcoeff(x)), p) != 0 ) {
1213                         UniPoly modpoly(R, prim, x);
1214                         UniFactorVec sqrfree_ufv;
1215                         squarefree(modpoly, sqrfree_ufv);
1216                         if ( sqrfree_ufv.factors.size() == 1 && sqrfree_ufv.factors.front().exp == 1 ) break;
1217                 }
1218                 p = next_prime(p);
1219                 R = find_modint_ring(p);
1220         }
1221
1222         // do modular factorization
1223         UniPoly modpoly(R, prim, x);
1224         UniPolyVec factors;
1225         factor_modular(modpoly, factors);
1226         if ( factors.size() <= 1 ) {
1227                 // irreducible for sure
1228                 return poly;
1229         }
1230
1231         // lift all factor combinations
1232         stack<ModFactors> tocheck;
1233         ModFactors mf;
1234         mf.poly = prim;
1235         mf.factors = factors;
1236         tocheck.push(mf);
1237         ex result = 1;
1238         while ( tocheck.size() ) {
1239                 const size_t n = tocheck.top().factors.size();
1240                 Partition part(n);
1241                 while ( true ) {
1242                         UniPoly a(R), b(R);
1243                         split(tocheck.top().factors, part, a, b);
1244
1245                         ex answer = hensel_univar(tocheck.top().poly, x, p, a, b);
1246                         if ( answer != lst() ) {
1247                                 if ( part.size_first() == 1 ) {
1248                                         if ( part.size_second() == 1 ) {
1249                                                 result *= answer.op(0) * answer.op(1);
1250                                                 tocheck.pop();
1251                                                 break;
1252                                         }
1253                                         result *= answer.op(0);
1254                                         tocheck.top().poly = answer.op(1);
1255                                         for ( size_t i=0; i<n; ++i ) {
1256                                                 if ( part[i] == 0 ) {
1257                                                         tocheck.top().factors.erase(tocheck.top().factors.begin()+i);
1258                                                         break;
1259                                                 }
1260                                         }
1261                                         break;
1262                                 }
1263                                 else if ( part.size_second() == 1 ) {
1264                                         if ( part.size_first() == 1 ) {
1265                                                 result *= answer.op(0) * answer.op(1);
1266                                                 tocheck.pop();
1267                                                 break;
1268                                         }
1269                                         result *= answer.op(1);
1270                                         tocheck.top().poly = answer.op(0);
1271                                         for ( size_t i=0; i<n; ++i ) {
1272                                                 if ( part[i] == 1 ) {
1273                                                         tocheck.top().factors.erase(tocheck.top().factors.begin()+i);
1274                                                         break;
1275                                                 }
1276                                         }
1277                                         break;
1278                                 }
1279                                 else {
1280                                         UniPolyVec newfactors1(part.size_first(), R), newfactors2(part.size_second(), R);
1281                                         UniPolyVec::iterator i1 = newfactors1.begin(), i2 = newfactors2.begin();
1282                                         for ( size_t i=0; i<n; ++i ) {
1283                                                 if ( part[i] ) {
1284                                                         *i2++ = tocheck.top().factors[i];
1285                                                 }
1286                                                 else {
1287                                                         *i1++ = tocheck.top().factors[i];
1288                                                 }
1289                                         }
1290                                         tocheck.top().factors = newfactors1;
1291                                         tocheck.top().poly = answer.op(0);
1292                                         ModFactors mf;
1293                                         mf.factors = newfactors2;
1294                                         mf.poly = answer.op(1);
1295                                         tocheck.push(mf);
1296                                         break;
1297                                 }
1298                         }
1299                         else {
1300                                 if ( !part.next() ) {
1301                                         result *= tocheck.top().poly;
1302                                         tocheck.pop();
1303                                         break;
1304                                 }
1305                         }
1306                 }
1307         }
1308
1309         return unit * cont * result;
1310 }
1311
1312 struct FindSymbolsMap : public map_function {
1313         exset syms;
1314         ex operator()(const ex& e)
1315         {
1316                 if ( is_a<symbol>(e) ) {
1317                         syms.insert(e);
1318                         return e;
1319                 }
1320                 return e.map(*this);
1321         }
1322 };
1323
1324 struct EvalPoint
1325 {
1326         ex x;
1327         int evalpoint;
1328 };
1329
1330 // forward declaration
1331 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);
1332
1333 UniPolyVec multiterm_eea_lift(const UniPolyVec& a, const ex& x, unsigned int p, unsigned int k)
1334 {
1335         DCOUT(multiterm_eea_lift);
1336         DCOUTVAR(a);
1337         DCOUTVAR(p);
1338         DCOUTVAR(k);
1339
1340         const size_t r = a.size();
1341         DCOUTVAR(r);
1342         cl_modint_ring R = find_modint_ring(expt_pos(cl_I(p),k));
1343         UniPoly fill(R);
1344         UniPolyVec q(r-1, fill);
1345         q[r-2] = a[r-1];
1346         for ( size_t j=r-2; j>=1; --j ) {
1347                 q[j-1] = a[j] * q[j];
1348         }
1349         DCOUTVAR(q);
1350         UniPoly beta(R);
1351         beta.set(0, R->one());
1352         UniPolyVec s;
1353         for ( size_t j=1; j<r; ++j ) {
1354                 DCOUTVAR(j);
1355                 DCOUTVAR(beta);
1356                 vector<ex> mdarg(2);
1357                 mdarg[0] = q[j-1].to_ex(x);
1358                 mdarg[1] = a[j-1].to_ex(x);
1359                 vector<EvalPoint> empty;
1360                 vector<ex> exsigma = multivar_diophant(mdarg, x, beta.to_ex(x), empty, 0, p, k);
1361                 UniPoly sigma1(R, exsigma[0], x);
1362                 UniPoly sigma2(R, exsigma[1], x);
1363                 beta = sigma1;
1364                 s.push_back(sigma2);
1365         }
1366         s.push_back(beta);
1367
1368         DCOUTVAR(s);
1369         DCOUT(END multiterm_eea_lift);
1370         return s;
1371 }
1372
1373 void eea_lift(const UniPoly& a, const UniPoly& b, const ex& x, unsigned int p, unsigned int k, UniPoly& s_, UniPoly& t_)
1374 {
1375         DCOUT(eea_lift);
1376         DCOUTVAR(a);
1377         DCOUTVAR(b);
1378         DCOUTVAR(x);
1379         DCOUTVAR(p);
1380         DCOUTVAR(k);
1381
1382         cl_modint_ring R = find_modint_ring(p);
1383         UniPoly amod(R, a);
1384         UniPoly bmod(R, b);
1385         DCOUTVAR(amod);
1386         DCOUTVAR(bmod);
1387
1388         UniPoly smod(R), tmod(R), g(R);
1389         exteuclid(amod, bmod, g, smod, tmod);
1390         
1391         DCOUTVAR(smod);
1392         DCOUTVAR(tmod);
1393         DCOUTVAR(g);
1394
1395         cl_modint_ring Rpk = find_modint_ring(expt_pos(cl_I(p),k));
1396         UniPoly s(Rpk, smod);
1397         UniPoly t(Rpk, tmod);
1398         DCOUTVAR(s);
1399         DCOUTVAR(t);
1400
1401         cl_I modulus(p);
1402
1403         UniPoly one(Rpk);
1404         one.set(0, Rpk->one());
1405         for ( size_t j=1; j<k; ++j ) {
1406                 UniPoly e = one - a * s - b * t;
1407                 e.divide(modulus);
1408                 UniPoly c(R, e);
1409                 UniPoly sigmabar(R);
1410                 sigmabar = smod * c;
1411                 UniPoly taubar(R);
1412                 taubar = tmod * c;
1413                 UniPoly q(R);
1414                 div(sigmabar, bmod, q);
1415                 UniPoly sigma(R);
1416                 rem(sigmabar, bmod, sigma);
1417                 UniPoly tau(R);
1418                 tau = taubar + q * amod;
1419                 UniPoly sadd(Rpk, sigma);
1420                 cl_MI modmodulus(Rpk, modulus);
1421                 s = s + sadd * modmodulus;
1422                 UniPoly tadd(Rpk, tau);
1423                 t = t + tadd * modmodulus;
1424                 modulus = modulus * p;
1425         }
1426
1427         s_ = s; t_ = t;
1428
1429         DCOUTVAR(s);
1430         DCOUTVAR(t);
1431         DCOUT2(check, a*s + b*t);
1432         DCOUT(END eea_lift);
1433 }
1434
1435 UniPolyVec univar_diophant(const UniPolyVec& a, const ex& x, unsigned int m, unsigned int p, unsigned int k)
1436 {
1437         DCOUT(univar_diophant);
1438         DCOUTVAR(a);
1439         DCOUTVAR(x);
1440         DCOUTVAR(m);
1441         DCOUTVAR(p);
1442         DCOUTVAR(k);
1443
1444         cl_modint_ring R = find_modint_ring(expt_pos(cl_I(p),k));
1445
1446         const size_t r = a.size();
1447         UniPolyVec result;
1448         if ( r > 2 ) {
1449                 UniPolyVec s = multiterm_eea_lift(a, x, p, k);
1450                 for ( size_t j=0; j<r; ++j ) {
1451                         ex phi = expand(pow(x,m)*s[j].to_ex(x));
1452                         UniPoly bmod(R, phi, x);
1453                         UniPoly buf(R);
1454                         rem(bmod, a[j], buf);
1455                         result.push_back(buf);
1456                 }
1457         }
1458         else {
1459                 UniPoly s(R), t(R);
1460                 eea_lift(a[1], a[0], x, p, k, s, t);
1461                 ex phi = expand(pow(x,m)*s.to_ex(x));
1462                 UniPoly bmod(R, phi, x);
1463                 UniPoly buf(R);
1464                 rem(bmod, a[0], buf);
1465                 result.push_back(buf);
1466                 UniPoly q(R);
1467                 div(bmod, a[0], q);
1468                 phi = expand(pow(x,m)*t.to_ex(x));
1469                 UniPoly t1mod(R, phi, x);
1470                 buf = t1mod + q * a[1];
1471                 result.push_back(buf);
1472         }
1473
1474         DCOUTVAR(result);
1475         DCOUT(END univar_diophant);
1476         return result;
1477 }
1478
1479 struct make_modular_map : public map_function {
1480         cl_modint_ring R;
1481         make_modular_map(const cl_modint_ring& R_) : R(R_) { }
1482         ex operator()(const ex& e)
1483         {
1484                 if ( is_a<add>(e) || is_a<mul>(e) ) {
1485                         return e.map(*this);
1486                 }
1487                 else if ( is_a<numeric>(e) ) {
1488                         numeric mod(R->modulus);
1489                         numeric halfmod = (mod-1)/2;
1490                         cl_MI emod = R->canonhom(the<cl_I>(ex_to<numeric>(e).to_cl_N()));
1491                         numeric n(R->retract(emod));
1492                         if ( n > halfmod ) {
1493                                 return n-mod;
1494                         }
1495                         else {
1496                                 return n;
1497                         }
1498                 }
1499                 return e;
1500         }
1501 };
1502
1503 static ex make_modular(const ex& e, const cl_modint_ring& R)
1504 {
1505         make_modular_map map(R);
1506         return map(e);
1507 }
1508
1509 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)
1510 {
1511         vector<ex> a = a_;
1512
1513         DCOUT(multivar_diophant);
1514 #ifdef DEBUGFACTOR
1515         cout << "a ";
1516         for ( size_t i=0; i<a.size(); ++i ) {
1517                 cout << a[i] << " ";
1518         }
1519         cout << endl;
1520 #endif
1521         DCOUTVAR(x);
1522         DCOUTVAR(c);
1523 #ifdef DEBUGFACTOR
1524         cout << "I ";
1525         for ( size_t i=0; i<I.size(); ++i ) {
1526                 cout << I[i].x << "=" << I[i].evalpoint << " ";
1527         }
1528         cout << endl;
1529 #endif
1530         DCOUTVAR(d);
1531         DCOUTVAR(p);
1532         DCOUTVAR(k);
1533
1534         const cl_modint_ring R = find_modint_ring(expt_pos(cl_I(p),k));
1535         const size_t r = a.size();
1536         const size_t nu = I.size() + 1;
1537         DCOUTVAR(r);
1538         DCOUTVAR(nu);
1539
1540         vector<ex> sigma;
1541         if ( nu > 1 ) {
1542                 ex xnu = I.back().x;
1543                 int alphanu = I.back().evalpoint;
1544
1545                 ex A = 1;
1546                 for ( size_t i=0; i<r; ++i ) {
1547                         A *= a[i];
1548                 }
1549                 vector<ex> b(r);
1550                 for ( size_t i=0; i<r; ++i ) {
1551                         b[i] = normal(A / a[i]);
1552                 }
1553
1554                 vector<ex> anew = a;
1555                 for ( size_t i=0; i<r; ++i ) {
1556                         a[i] = a[i].subs(xnu == alphanu);
1557                 }
1558                 ex cnew = c.subs(xnu == alphanu);
1559                 vector<EvalPoint> Inew = I;
1560                 Inew.pop_back();
1561                 vector<ex> sigma = multivar_diophant(anew, x, cnew, Inew, d, p, k);
1562
1563                 ex buf = c;
1564                 for ( size_t i=0; i<r; ++i ) {
1565                         buf -= sigma[i] * b[i];
1566                 }
1567                 ex e = buf;
1568                 e = make_modular(e, R);
1569
1570                 ex monomial = 1;
1571                 for ( size_t m=1; m<=d; ++m ) {
1572                         while ( !e.is_zero() ) {
1573                                 monomial *= (xnu - alphanu);
1574                                 monomial = expand(monomial);
1575                                 ex cm = e.diff(ex_to<symbol>(xnu), m).subs(xnu==alphanu) / factorial(m);
1576                                 if ( !cm.is_zero() ) {
1577                                         vector<ex> delta_s = multivar_diophant(anew, x, cm, Inew, d, p, k);
1578                                         ex buf = e;
1579                                         for ( size_t j=0; j<delta_s.size(); ++j ) {
1580                                                 delta_s[j] *= monomial;
1581                                                 sigma[j] += delta_s[j];
1582                                                 buf -= delta_s[j] * b[j];
1583                                         }
1584                                         e = buf;
1585                                         e = make_modular(e, R);
1586                                 }
1587                         }
1588                 }
1589         }
1590         else {
1591                 UniPolyVec amod;
1592                 for ( size_t i=0; i<a.size(); ++i ) {
1593                         UniPoly up(R, a[i], x);
1594                         amod.push_back(up);
1595                 }
1596
1597                 sigma.insert(sigma.begin(), r, 0);
1598                 size_t nterms;
1599                 ex z;
1600                 if ( is_a<add>(c) ) {
1601                         nterms = c.nops();
1602                         z = c.op(0);
1603                 }
1604                 else {
1605                         nterms = 1;
1606                         z = c;
1607                 }
1608                 DCOUTVAR(nterms);
1609                 for ( size_t i=0; i<nterms; ++i ) {
1610                         DCOUTVAR(z);
1611                         int m = z.degree(x);
1612                         DCOUTVAR(m);
1613                         cl_I cm = the<cl_I>(ex_to<numeric>(z.lcoeff(x)).to_cl_N());
1614                         DCOUTVAR(cm);
1615                         UniPolyVec delta_s = univar_diophant(amod, x, m, p, k);
1616                         cl_MI modcm;
1617                         cl_I poscm = cm;
1618                         while ( poscm < 0 ) {
1619                                 poscm = poscm + expt_pos(cl_I(p),k);
1620                         }
1621                         modcm = cl_MI(R, poscm);
1622                         DCOUTVAR(modcm);
1623                         for ( size_t j=0; j<delta_s.size(); ++j ) {
1624                                 delta_s[j] = delta_s[j] * modcm;
1625                                 sigma[j] = sigma[j] + delta_s[j].to_ex(x);
1626                         }
1627                         DCOUTVAR(delta_s);
1628 #ifdef DEBUGFACTOR
1629                         cout << "STEP " << i << " sigma ";
1630                         for ( size_t p=0; p<sigma.size(); ++p ) {
1631                                 cout << sigma[p] << " ";
1632                         }
1633                         cout << endl;
1634 #endif
1635                         if ( nterms > 1 ) {
1636                                 z = c.op(i+1);
1637                         }
1638                 }
1639         }
1640 #ifdef DEBUGFACTOR
1641         cout << "sigma ";
1642         for ( size_t i=0; i<sigma.size(); ++i ) {
1643                 cout << sigma[i] << " ";
1644         }
1645         cout << endl;
1646 #endif
1647
1648         for ( size_t i=0; i<sigma.size(); ++i ) {
1649                 sigma[i] = make_modular(sigma[i], R);
1650         }
1651
1652 #ifdef DEBUGFACTOR
1653         cout << "sigma ";
1654         for ( size_t i=0; i<sigma.size(); ++i ) {
1655                 cout << sigma[i] << " ";
1656         }
1657         cout << endl;
1658 #endif
1659         DCOUT(END multivar_diophant);
1660         return sigma;
1661 }
1662
1663 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)
1664 {
1665         DCOUT(hensel_multivar);
1666         DCOUTVAR(a);
1667         DCOUTVAR(x);
1668         DCOUTVAR(p);
1669         DCOUTVAR(l);
1670         DCOUTVAR(u);
1671         const size_t nu = I.size() + 1;
1672         const cl_modint_ring R = find_modint_ring(expt_pos(cl_I(p),l));
1673
1674         DCOUTVAR(nu);
1675         
1676         vector<ex> A(nu);
1677         A[nu-1] = a;
1678
1679         for ( size_t j=nu; j>=2; --j ) {
1680                 ex x = I[j-2].x;
1681                 int alpha = I[j-2].evalpoint;
1682                 A[j-2] = A[j-1].subs(x==alpha);
1683                 A[j-2] = make_modular(A[j-2], R);
1684         }
1685
1686 #ifdef DEBUGFACTOR
1687         cout << "A ";
1688         for ( size_t i=0; i<A.size(); ++i) cout << A[i] << " ";
1689         cout << endl;
1690 #endif
1691
1692         int maxdeg = a.degree(I.front().x);
1693         for ( size_t i=1; i<I.size(); ++i ) {
1694                 int maxdeg2 = a.degree(I[i].x);
1695                 if ( maxdeg2 > maxdeg ) maxdeg = maxdeg2;
1696         }
1697         DCOUTVAR(maxdeg);
1698
1699         const size_t n = u.size();
1700         DCOUTVAR(n);
1701         vector<ex> U(n);
1702         for ( size_t i=0; i<n; ++i ) {
1703                 U[i] = u[i].to_ex(x);
1704         }
1705 #ifdef DEBUGFACTOR
1706         cout << "U ";
1707         for ( size_t i=0; i<U.size(); ++i) cout << U[i] << " ";
1708         cout << endl;
1709 #endif
1710
1711         for ( size_t j=2; j<=nu; ++j ) {
1712                 DCOUTVAR(j);
1713                 vector<ex> U1 = U;
1714                 ex monomial = 1;
1715                 for ( size_t m=0; m<n; ++m) {
1716                         if ( lcU[m] != 1 ) {
1717                                 ex coef = lcU[m];
1718                                 for ( size_t i=j-1; i<nu-1; ++i ) {
1719                                         coef = coef.subs(I[i].x == I[i].evalpoint);
1720                                 }
1721                                 coef = expand(coef);
1722                                 coef = make_modular(coef, R);
1723                                 int deg = U[m].degree(x);
1724                                 U[m] = U[m] - U[m].lcoeff(x) * pow(x,deg) + coef * pow(x,deg);
1725                         }
1726                 }
1727                 ex Uprod = 1;
1728                 for ( size_t i=0; i<n; ++i ) {
1729                         Uprod *= U[i];
1730                 }
1731                 ex e = expand(A[j-1] - Uprod);
1732                 DCOUTVAR(e);
1733
1734                 ex xj = I[j-2].x;
1735                 int alphaj = I[j-2].evalpoint;
1736                 size_t deg = A[j-1].degree(xj);
1737                 DCOUTVAR(deg);
1738                 for ( size_t k=1; k<=deg; ++k ) {
1739                         DCOUTVAR(k);
1740                         if ( !e.is_zero() ) {
1741                                 DCOUTVAR(xj);
1742                                 DCOUTVAR(alphaj);
1743                                 monomial *= (xj - alphaj);
1744                                 monomial = expand(monomial);
1745                                 DCOUTVAR(monomial);
1746                                 ex dif = e.diff(ex_to<symbol>(xj), k);
1747                                 DCOUTVAR(dif);
1748                                 ex c = dif.subs(xj==alphaj) / factorial(k);
1749                                 DCOUTVAR(c);
1750                                 if ( !c.is_zero() ) {
1751                                         vector<EvalPoint> newI = I;
1752                                         newI.pop_back();
1753                                         vector<ex> deltaU = multivar_diophant(U1, x, c, newI, maxdeg, p, cl_I_to_uint(l));
1754                                         for ( size_t i=0; i<n; ++i ) {
1755                                                 DCOUTVAR(i);
1756                                                 DCOUTVAR(deltaU[i]);
1757                                                 deltaU[i] *= monomial;
1758                                                 U[i] += deltaU[i];
1759                                                 U[i] = make_modular(U[i], R);
1760                                         }
1761                                         ex Uprod = 1;
1762                                         for ( size_t i=0; i<n; ++i ) {
1763                                                 Uprod *= U[i];
1764                                         }
1765                                         e = expand(A[j-1] - Uprod);
1766                                         e = make_modular(e, R);
1767                                         DCOUTVAR(e);
1768                                 }
1769                                 else {
1770                                         break;
1771                                 }
1772                         }
1773                 }
1774         }
1775
1776         ex acand = 1;
1777         for ( size_t i=0; i<U.size(); ++i ) {
1778                 acand *= U[i];
1779         }
1780         DCOUTVAR(acand);
1781         if ( expand(a-acand).is_zero() ) {
1782                 lst res;
1783                 for ( size_t i=0; i<U.size(); ++i ) {
1784                         res.append(U[i]);
1785                 }
1786                 return res;
1787         }
1788         else {
1789                 return lst();
1790         }
1791 }
1792
1793 static ex factor_multivariate(const ex& poly, const ex& x)
1794 {
1795         // TODO
1796         return 666;
1797 }
1798
1799 static ex factor_sqrfree(const ex& poly)
1800 {
1801         // determine all symbols in poly
1802         FindSymbolsMap findsymbols;
1803         findsymbols(poly);
1804         if ( findsymbols.syms.size() == 0 ) {
1805                 return poly;
1806         }
1807
1808         if ( findsymbols.syms.size() == 1 ) {
1809                 const ex& x = *(findsymbols.syms.begin());
1810                 if ( poly.ldegree(x) > 0 ) {
1811                         int ld = poly.ldegree(x);
1812                         ex res = factor_univariate(expand(poly/pow(x, ld)), x);
1813                         return res * pow(x,ld);
1814                 }
1815                 else {
1816                         ex res = factor_univariate(poly, x);
1817                         return res;
1818                 }
1819         }
1820
1821         // multivariate case not yet implemented!
1822         throw runtime_error("multivariate case not yet implemented!");
1823 }
1824
1825 } // anonymous namespace
1826
1827 ex factor(const ex& poly)
1828 {
1829         // determine all symbols in poly
1830         FindSymbolsMap findsymbols;
1831         findsymbols(poly);
1832         if ( findsymbols.syms.size() == 0 ) {
1833                 return poly;
1834         }
1835         lst syms;
1836         exset::const_iterator i=findsymbols.syms.begin(), end=findsymbols.syms.end();
1837         for ( ; i!=end; ++i ) {
1838                 syms.append(*i);
1839         }
1840
1841         // make poly square free
1842         ex sfpoly = sqrfree(poly, syms);
1843
1844         // factorize the square free components
1845         if ( is_a<power>(sfpoly) ) {
1846                 // case: (polynomial)^exponent
1847                 const ex& base = sfpoly.op(0);
1848                 if ( !is_a<add>(base) ) {
1849                         // simple case: (monomial)^exponent
1850                         return sfpoly;
1851                 }
1852                 ex f = factor_sqrfree(base);
1853                 return pow(f, sfpoly.op(1));
1854         }
1855         if ( is_a<mul>(sfpoly) ) {
1856                 ex res = 1;
1857                 for ( size_t i=0; i<sfpoly.nops(); ++i ) {
1858                         const ex& t = sfpoly.op(i);
1859                         if ( is_a<power>(t) ) {
1860                                 const ex& base = t.op(0);
1861                                 if ( !is_a<add>(base) ) {
1862                                         res *= t;
1863                                 }
1864                                 else {
1865                                         ex f = factor_sqrfree(base);
1866                                         res *= pow(f, t.op(1));
1867                                 }
1868                         }
1869                         else if ( is_a<add>(t) ) {
1870                                 ex f = factor_sqrfree(t);
1871                                 res *= f;
1872                         }
1873                         else {
1874                                 res *= t;
1875                         }
1876                 }
1877                 return res;
1878         }
1879         if ( is_a<symbol>(sfpoly) ) {
1880                 return poly;
1881         }
1882         // case: (polynomial)
1883         ex f = factor_sqrfree(sfpoly);
1884         return f;
1885 }
1886
1887 } // namespace GiNaC