/
modulargcd.py
2277 lines (1704 loc) · 57.3 KB
/
modulargcd.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from sympy.core.symbol import Dummy
from sympy.ntheory import nextprime
from sympy.ntheory.modular import crt
from sympy.polys.domains import PolynomialRing
from sympy.polys.galoistools import (
gf_gcd, gf_from_dict, gf_gcdex, gf_div, gf_lcm)
from sympy.polys.polyerrors import ModularGCDFailed
from mpmath import sqrt
import random
def _trivial_gcd(f, g):
"""
Compute the GCD of two polynomials in trivial cases, i.e. when one
or both polynomials are zero.
"""
ring = f.ring
if not (f or g):
return ring.zero, ring.zero, ring.zero
elif not f:
if g.LC < ring.domain.zero:
return -g, ring.zero, -ring.one
else:
return g, ring.zero, ring.one
elif not g:
if f.LC < ring.domain.zero:
return -f, -ring.one, ring.zero
else:
return f, ring.one, ring.zero
return None
def _gf_gcd(fp, gp, p):
r"""
Compute the GCD of two univariate polynomials in `\mathbb{Z}_p[x]`.
"""
dom = fp.ring.domain
while gp:
rem = fp
deg = gp.degree()
lcinv = dom.invert(gp.LC, p)
while True:
degrem = rem.degree()
if degrem < deg:
break
rem = (rem - gp.mul_monom((degrem - deg,)).mul_ground(lcinv * rem.LC)).trunc_ground(p)
fp = gp
gp = rem
return fp.mul_ground(dom.invert(fp.LC, p)).trunc_ground(p)
def _degree_bound_univariate(f, g):
r"""
Compute an upper bound for the degree of the GCD of two univariate
integer polynomials `f` and `g`.
The function chooses a suitable prime `p` and computes the GCD of
`f` and `g` in `\mathbb{Z}_p[x]`. The choice of `p` guarantees that
the degree in `\mathbb{Z}_p[x]` is greater than or equal to the degree
in `\mathbb{Z}[x]`.
Parameters
==========
f : PolyElement
univariate integer polynomial
g : PolyElement
univariate integer polynomial
"""
gamma = f.ring.domain.gcd(f.LC, g.LC)
p = 1
p = nextprime(p)
while gamma % p == 0:
p = nextprime(p)
fp = f.trunc_ground(p)
gp = g.trunc_ground(p)
hp = _gf_gcd(fp, gp, p)
deghp = hp.degree()
return deghp
def _chinese_remainder_reconstruction_univariate(hp, hq, p, q):
r"""
Construct a polynomial `h_{pq}` in `\mathbb{Z}_{p q}[x]` such that
.. math ::
h_{pq} = h_p \; \mathrm{mod} \, p
h_{pq} = h_q \; \mathrm{mod} \, q
for relatively prime integers `p` and `q` and polynomials
`h_p` and `h_q` in `\mathbb{Z}_p[x]` and `\mathbb{Z}_q[x]`
respectively.
The coefficients of the polynomial `h_{pq}` are computed with the
Chinese Remainder Theorem. The symmetric representation in
`\mathbb{Z}_p[x]`, `\mathbb{Z}_q[x]` and `\mathbb{Z}_{p q}[x]` is used.
It is assumed that `h_p` and `h_q` have the same degree.
Parameters
==========
hp : PolyElement
univariate integer polynomial with coefficients in `\mathbb{Z}_p`
hq : PolyElement
univariate integer polynomial with coefficients in `\mathbb{Z}_q`
p : Integer
modulus of `h_p`, relatively prime to `q`
q : Integer
modulus of `h_q`, relatively prime to `p`
Examples
========
>>> from sympy.polys.modulargcd import _chinese_remainder_reconstruction_univariate
>>> from sympy.polys import ring, ZZ
>>> R, x = ring("x", ZZ)
>>> p = 3
>>> q = 5
>>> hp = -x**3 - 1
>>> hq = 2*x**3 - 2*x**2 + x
>>> hpq = _chinese_remainder_reconstruction_univariate(hp, hq, p, q)
>>> hpq
2*x**3 + 3*x**2 + 6*x + 5
>>> hpq.trunc_ground(p) == hp
True
>>> hpq.trunc_ground(q) == hq
True
"""
n = hp.degree()
x = hp.ring.gens[0]
hpq = hp.ring.zero
for i in range(n+1):
hpq[(i,)] = crt([p, q], [hp.coeff(x**i), hq.coeff(x**i)], symmetric=True)[0]
hpq.strip_zero()
return hpq
def modgcd_univariate(f, g):
r"""
Computes the GCD of two polynomials in `\mathbb{Z}[x]` using a modular
algorithm.
The algorithm computes the GCD of two univariate integer polynomials
`f` and `g` by computing the GCD in `\mathbb{Z}_p[x]` for suitable
primes `p` and then reconstructing the coefficients with the Chinese
Remainder Theorem. Trial division is only made for candidates which
are very likely the desired GCD.
Parameters
==========
f : PolyElement
univariate integer polynomial
g : PolyElement
univariate integer polynomial
Returns
=======
h : PolyElement
GCD of the polynomials `f` and `g`
cff : PolyElement
cofactor of `f`, i.e. `\frac{f}{h}`
cfg : PolyElement
cofactor of `g`, i.e. `\frac{g}{h}`
Examples
========
>>> from sympy.polys.modulargcd import modgcd_univariate
>>> from sympy.polys import ring, ZZ
>>> R, x = ring("x", ZZ)
>>> f = x**5 - 1
>>> g = x - 1
>>> h, cff, cfg = modgcd_univariate(f, g)
>>> h, cff, cfg
(x - 1, x**4 + x**3 + x**2 + x + 1, 1)
>>> cff * h == f
True
>>> cfg * h == g
True
>>> f = 6*x**2 - 6
>>> g = 2*x**2 + 4*x + 2
>>> h, cff, cfg = modgcd_univariate(f, g)
>>> h, cff, cfg
(2*x + 2, 3*x - 3, x + 1)
>>> cff * h == f
True
>>> cfg * h == g
True
References
==========
1. [Monagan00]_
"""
assert f.ring == g.ring and f.ring.domain.is_ZZ
result = _trivial_gcd(f, g)
if result is not None:
return result
ring = f.ring
cf, f = f.primitive()
cg, g = g.primitive()
ch = ring.domain.gcd(cf, cg)
bound = _degree_bound_univariate(f, g)
if bound == 0:
return ring(ch), f.mul_ground(cf // ch), g.mul_ground(cg // ch)
gamma = ring.domain.gcd(f.LC, g.LC)
m = 1
p = 1
while True:
p = nextprime(p)
while gamma % p == 0:
p = nextprime(p)
fp = f.trunc_ground(p)
gp = g.trunc_ground(p)
hp = _gf_gcd(fp, gp, p)
deghp = hp.degree()
if deghp > bound:
continue
elif deghp < bound:
m = 1
bound = deghp
continue
hp = hp.mul_ground(gamma).trunc_ground(p)
if m == 1:
m = p
hlastm = hp
continue
hm = _chinese_remainder_reconstruction_univariate(hp, hlastm, p, m)
m *= p
if not hm == hlastm:
hlastm = hm
continue
h = hm.quo_ground(hm.content())
fquo, frem = f.div(h)
gquo, grem = g.div(h)
if not frem and not grem:
if h.LC < 0:
ch = -ch
h = h.mul_ground(ch)
cff = fquo.mul_ground(cf // ch)
cfg = gquo.mul_ground(cg // ch)
return h, cff, cfg
def _primitive(f, p):
r"""
Compute the content and the primitive part of a polynomial in
`\mathbb{Z}_p[x_0, \ldots, x_{k-2}, y] \cong \mathbb{Z}_p[y][x_0, \ldots, x_{k-2}]`.
Parameters
==========
f : PolyElement
integer polynomial in `\mathbb{Z}_p[x0, \ldots, x{k-2}, y]`
p : Integer
modulus of `f`
Returns
=======
contf : PolyElement
integer polynomial in `\mathbb{Z}_p[y]`, content of `f`
ppf : PolyElement
primitive part of `f`, i.e. `\frac{f}{contf}`
Examples
========
>>> from sympy.polys.modulargcd import _primitive
>>> from sympy.polys import ring, ZZ
>>> R, x, y = ring("x, y", ZZ)
>>> p = 3
>>> f = x**2*y**2 + x**2*y - y**2 - y
>>> _primitive(f, p)
(y**2 + y, x**2 - 1)
>>> R, x, y, z = ring("x, y, z", ZZ)
>>> f = x*y*z - y**2*z**2
>>> _primitive(f, p)
(z, x*y - y**2*z)
"""
ring = f.ring
dom = ring.domain
k = ring.ngens
coeffs = {}
for monom, coeff in f.iterterms():
if monom[:-1] not in coeffs:
coeffs[monom[:-1]] = {}
coeffs[monom[:-1]][monom[-1]] = coeff
cont = []
for coeff in iter(coeffs.values()):
cont = gf_gcd(cont, gf_from_dict(coeff, p, dom), p, dom)
yring = ring.clone(symbols=ring.symbols[k-1])
contf = yring.from_dense(cont).trunc_ground(p)
return contf, f.quo(contf.set_ring(ring))
def _deg(f):
r"""
Compute the degree of a multivariate polynomial
`f \in K[x_0, \ldots, x_{k-2}, y] \cong K[y][x_0, \ldots, x_{k-2}]`.
Parameters
==========
f : PolyElement
polynomial in `K[x_0, \ldots, x_{k-2}, y]`
Returns
=======
degf : Integer tuple
degree of `f` in `x_0, \ldots, x_{k-2}`
Examples
========
>>> from sympy.polys.modulargcd import _deg
>>> from sympy.polys import ring, ZZ
>>> R, x, y = ring("x, y", ZZ)
>>> f = x**2*y**2 + x**2*y - 1
>>> _deg(f)
(2,)
>>> R, x, y, z = ring("x, y, z", ZZ)
>>> f = x**2*y**2 + x**2*y - 1
>>> _deg(f)
(2, 2)
>>> f = x*y*z - y**2*z**2
>>> _deg(f)
(1, 1)
"""
k = f.ring.ngens
degf = (0,) * (k-1)
for monom in f.itermonoms():
if monom[:-1] > degf:
degf = monom[:-1]
return degf
def _LC(f):
r"""
Compute the leading coefficient of a multivariate polynomial
`f \in K[x_0, \ldots, x_{k-2}, y] \cong K[y][x_0, \ldots, x_{k-2}]`.
Parameters
==========
f : PolyElement
polynomial in `K[x_0, \ldots, x_{k-2}, y]`
Returns
=======
lcf : PolyElement
polynomial in `K[y]`, leading coefficient of `f`
Examples
========
>>> from sympy.polys.modulargcd import _LC
>>> from sympy.polys import ring, ZZ
>>> R, x, y = ring("x, y", ZZ)
>>> f = x**2*y**2 + x**2*y - 1
>>> _LC(f)
y**2 + y
>>> R, x, y, z = ring("x, y, z", ZZ)
>>> f = x**2*y**2 + x**2*y - 1
>>> _LC(f)
1
>>> f = x*y*z - y**2*z**2
>>> _LC(f)
z
"""
ring = f.ring
k = ring.ngens
yring = ring.clone(symbols=ring.symbols[k-1])
y = yring.gens[0]
degf = _deg(f)
lcf = yring.zero
for monom, coeff in f.iterterms():
if monom[:-1] == degf:
lcf += coeff*y**monom[-1]
return lcf
def _swap(f, i):
"""
Make the variable `x_i` the leading one in a multivariate polynomial `f`.
"""
ring = f.ring
fswap = ring.zero
for monom, coeff in f.iterterms():
monomswap = (monom[i],) + monom[:i] + monom[i+1:]
fswap[monomswap] = coeff
return fswap
def _degree_bound_bivariate(f, g):
r"""
Compute upper degree bounds for the GCD of two bivariate
integer polynomials `f` and `g`.
The GCD is viewed as a polynomial in `\mathbb{Z}[y][x]` and the
function returns an upper bound for its degree and one for the degree
of its content. This is done by choosing a suitable prime `p` and
computing the GCD of the contents of `f \; \mathrm{mod} \, p` and
`g \; \mathrm{mod} \, p`. The choice of `p` guarantees that the degree
of the content in `\mathbb{Z}_p[y]` is greater than or equal to the
degree in `\mathbb{Z}[y]`. To obtain the degree bound in the variable
`x`, the polynomials are evaluated at `y = a` for a suitable
`a \in \mathbb{Z}_p` and then their GCD in `\mathbb{Z}_p[x]` is
computed. If no such `a` exists, i.e. the degree in `\mathbb{Z}_p[x]`
is always smaller than the one in `\mathbb{Z}[y][x]`, then the bound is
set to the minimum of the degrees of `f` and `g` in `x`.
Parameters
==========
f : PolyElement
bivariate integer polynomial
g : PolyElement
bivariate integer polynomial
Returns
=======
xbound : Integer
upper bound for the degree of the GCD of the polynomials `f` and
`g` in the variable `x`
ycontbound : Integer
upper bound for the degree of the content of the GCD of the
polynomials `f` and `g` in the variable `y`
References
==========
1. [Monagan00]_
"""
ring = f.ring
gamma1 = ring.domain.gcd(f.LC, g.LC)
gamma2 = ring.domain.gcd(_swap(f, 1).LC, _swap(g, 1).LC)
badprimes = gamma1 * gamma2
p = 1
p = nextprime(p)
while badprimes % p == 0:
p = nextprime(p)
fp = f.trunc_ground(p)
gp = g.trunc_ground(p)
contfp, fp = _primitive(fp, p)
contgp, gp = _primitive(gp, p)
conthp = _gf_gcd(contfp, contgp, p) # polynomial in Z_p[y]
ycontbound = conthp.degree()
# polynomial in Z_p[y]
delta = _gf_gcd(_LC(fp), _LC(gp), p)
for a in range(p):
if not delta.evaluate(0, a) % p:
continue
fpa = fp.evaluate(1, a).trunc_ground(p)
gpa = gp.evaluate(1, a).trunc_ground(p)
hpa = _gf_gcd(fpa, gpa, p)
xbound = hpa.degree()
return xbound, ycontbound
return min(fp.degree(), gp.degree()), ycontbound
def _chinese_remainder_reconstruction_multivariate(hp, hq, p, q):
r"""
Construct a polynomial `h_{pq}` in
`\mathbb{Z}_{p q}[x_0, \ldots, x_{k-1}]` such that
.. math ::
h_{pq} = h_p \; \mathrm{mod} \, p
h_{pq} = h_q \; \mathrm{mod} \, q
for relatively prime integers `p` and `q` and polynomials
`h_p` and `h_q` in `\mathbb{Z}_p[x_0, \ldots, x_{k-1}]` and
`\mathbb{Z}_q[x_0, \ldots, x_{k-1}]` respectively.
The coefficients of the polynomial `h_{pq}` are computed with the
Chinese Remainder Theorem. The symmetric representation in
`\mathbb{Z}_p[x_0, \ldots, x_{k-1}]`,
`\mathbb{Z}_q[x_0, \ldots, x_{k-1}]` and
`\mathbb{Z}_{p q}[x_0, \ldots, x_{k-1}]` is used.
Parameters
==========
hp : PolyElement
multivariate integer polynomial with coefficients in `\mathbb{Z}_p`
hq : PolyElement
multivariate integer polynomial with coefficients in `\mathbb{Z}_q`
p : Integer
modulus of `h_p`, relatively prime to `q`
q : Integer
modulus of `h_q`, relatively prime to `p`
Examples
========
>>> from sympy.polys.modulargcd import _chinese_remainder_reconstruction_multivariate
>>> from sympy.polys import ring, ZZ
>>> R, x, y = ring("x, y", ZZ)
>>> p = 3
>>> q = 5
>>> hp = x**3*y - x**2 - 1
>>> hq = -x**3*y - 2*x*y**2 + 2
>>> hpq = _chinese_remainder_reconstruction_multivariate(hp, hq, p, q)
>>> hpq
4*x**3*y + 5*x**2 + 3*x*y**2 + 2
>>> hpq.trunc_ground(p) == hp
True
>>> hpq.trunc_ground(q) == hq
True
>>> R, x, y, z = ring("x, y, z", ZZ)
>>> p = 6
>>> q = 5
>>> hp = 3*x**4 - y**3*z + z
>>> hq = -2*x**4 + z
>>> hpq = _chinese_remainder_reconstruction_multivariate(hp, hq, p, q)
>>> hpq
3*x**4 + 5*y**3*z + z
>>> hpq.trunc_ground(p) == hp
True
>>> hpq.trunc_ground(q) == hq
True
"""
hpmonoms = set(hp.monoms())
hqmonoms = set(hq.monoms())
monoms = hpmonoms.intersection(hqmonoms)
hpmonoms.difference_update(monoms)
hqmonoms.difference_update(monoms)
zero = hp.ring.domain.zero
hpq = hp.ring.zero
if isinstance(hp.ring.domain, PolynomialRing):
crt_ = _chinese_remainder_reconstruction_multivariate
else:
def crt_(cp, cq, p, q):
return crt([p, q], [cp, cq], symmetric=True)[0]
for monom in monoms:
hpq[monom] = crt_(hp[monom], hq[monom], p, q)
for monom in hpmonoms:
hpq[monom] = crt_(hp[monom], zero, p, q)
for monom in hqmonoms:
hpq[monom] = crt_(zero, hq[monom], p, q)
return hpq
def _interpolate_multivariate(evalpoints, hpeval, ring, i, p, ground=False):
r"""
Reconstruct a polynomial `h_p` in `\mathbb{Z}_p[x_0, \ldots, x_{k-1}]`
from a list of evaluation points in `\mathbb{Z}_p` and a list of
polynomials in
`\mathbb{Z}_p[x_0, \ldots, x_{i-1}, x_{i+1}, \ldots, x_{k-1}]`, which
are the images of `h_p` evaluated in the variable `x_i`.
It is also possible to reconstruct a parameter of the ground domain,
i.e. if `h_p` is a polynomial over `\mathbb{Z}_p[x_0, \ldots, x_{k-1}]`.
In this case, one has to set ``ground=True``.
Parameters
==========
evalpoints : list of Integer objects
list of evaluation points in `\mathbb{Z}_p`
hpeval : list of PolyElement objects
list of polynomials in (resp. over)
`\mathbb{Z}_p[x_0, \ldots, x_{i-1}, x_{i+1}, \ldots, x_{k-1}]`,
images of `h_p` evaluated in the variable `x_i`
ring : PolyRing
`h_p` will be an element of this ring
i : Integer
index of the variable which has to be reconstructed
p : Integer
prime number, modulus of `h_p`
ground : Boolean
indicates whether `x_i` is in the ground domain, default is
``False``
Returns
=======
hp : PolyElement
interpolated polynomial in (resp. over)
`\mathbb{Z}_p[x_0, \ldots, x_{k-1}]`
"""
hp = ring.zero
if ground:
domain = ring.domain.domain
y = ring.domain.gens[i]
else:
domain = ring.domain
y = ring.gens[i]
for a, hpa in zip(evalpoints, hpeval):
numer = ring.one
denom = domain.one
for b in evalpoints:
if b == a:
continue
numer *= y - b
denom *= a - b
denom = domain.invert(denom, p)
coeff = numer.mul_ground(denom)
hp += hpa.set_ring(ring) * coeff
return hp.trunc_ground(p)
def modgcd_bivariate(f, g):
r"""
Computes the GCD of two polynomials in `\mathbb{Z}[x, y]` using a
modular algorithm.
The algorithm computes the GCD of two bivariate integer polynomials
`f` and `g` by calculating the GCD in `\mathbb{Z}_p[x, y]` for
suitable primes `p` and then reconstructing the coefficients with the
Chinese Remainder Theorem. To compute the bivariate GCD over
`\mathbb{Z}_p`, the polynomials `f \; \mathrm{mod} \, p` and
`g \; \mathrm{mod} \, p` are evaluated at `y = a` for certain
`a \in \mathbb{Z}_p` and then their univariate GCD in `\mathbb{Z}_p[x]`
is computed. Interpolating those yields the bivariate GCD in
`\mathbb{Z}_p[x, y]`. To verify the result in `\mathbb{Z}[x, y]`, trial
division is done, but only for candidates which are very likely the
desired GCD.
Parameters
==========
f : PolyElement
bivariate integer polynomial
g : PolyElement
bivariate integer polynomial
Returns
=======
h : PolyElement
GCD of the polynomials `f` and `g`
cff : PolyElement
cofactor of `f`, i.e. `\frac{f}{h}`
cfg : PolyElement
cofactor of `g`, i.e. `\frac{g}{h}`
Examples
========
>>> from sympy.polys.modulargcd import modgcd_bivariate
>>> from sympy.polys import ring, ZZ
>>> R, x, y = ring("x, y", ZZ)
>>> f = x**2 - y**2
>>> g = x**2 + 2*x*y + y**2
>>> h, cff, cfg = modgcd_bivariate(f, g)
>>> h, cff, cfg
(x + y, x - y, x + y)
>>> cff * h == f
True
>>> cfg * h == g
True
>>> f = x**2*y - x**2 - 4*y + 4
>>> g = x + 2
>>> h, cff, cfg = modgcd_bivariate(f, g)
>>> h, cff, cfg
(x + 2, x*y - x - 2*y + 2, 1)
>>> cff * h == f
True
>>> cfg * h == g
True
References
==========
1. [Monagan00]_
"""
assert f.ring == g.ring and f.ring.domain.is_ZZ
result = _trivial_gcd(f, g)
if result is not None:
return result
ring = f.ring
cf, f = f.primitive()
cg, g = g.primitive()
ch = ring.domain.gcd(cf, cg)
xbound, ycontbound = _degree_bound_bivariate(f, g)
if xbound == ycontbound == 0:
return ring(ch), f.mul_ground(cf // ch), g.mul_ground(cg // ch)
fswap = _swap(f, 1)
gswap = _swap(g, 1)
degyf = fswap.degree()
degyg = gswap.degree()
ybound, xcontbound = _degree_bound_bivariate(fswap, gswap)
if ybound == xcontbound == 0:
return ring(ch), f.mul_ground(cf // ch), g.mul_ground(cg // ch)
# TODO: to improve performance, choose the main variable here
gamma1 = ring.domain.gcd(f.LC, g.LC)
gamma2 = ring.domain.gcd(fswap.LC, gswap.LC)
badprimes = gamma1 * gamma2
m = 1
p = 1
while True:
p = nextprime(p)
while badprimes % p == 0:
p = nextprime(p)
fp = f.trunc_ground(p)
gp = g.trunc_ground(p)
contfp, fp = _primitive(fp, p)
contgp, gp = _primitive(gp, p)
conthp = _gf_gcd(contfp, contgp, p) # monic polynomial in Z_p[y]
degconthp = conthp.degree()
if degconthp > ycontbound:
continue
elif degconthp < ycontbound:
m = 1
ycontbound = degconthp
continue
# polynomial in Z_p[y]
delta = _gf_gcd(_LC(fp), _LC(gp), p)
degcontfp = contfp.degree()
degcontgp = contgp.degree()
degdelta = delta.degree()
N = min(degyf - degcontfp, degyg - degcontgp,
ybound - ycontbound + degdelta) + 1
if p < N:
continue
n = 0
evalpoints = []
hpeval = []
unlucky = False
for a in range(p):
deltaa = delta.evaluate(0, a)
if not deltaa % p:
continue
fpa = fp.evaluate(1, a).trunc_ground(p)
gpa = gp.evaluate(1, a).trunc_ground(p)
hpa = _gf_gcd(fpa, gpa, p) # monic polynomial in Z_p[x]
deghpa = hpa.degree()
if deghpa > xbound:
continue
elif deghpa < xbound:
m = 1
xbound = deghpa
unlucky = True
break
hpa = hpa.mul_ground(deltaa).trunc_ground(p)
evalpoints.append(a)
hpeval.append(hpa)
n += 1
if n == N:
break
if unlucky:
continue
if n < N:
continue
hp = _interpolate_multivariate(evalpoints, hpeval, ring, 1, p)
hp = _primitive(hp, p)[1]
hp = hp * conthp.set_ring(ring)
degyhp = hp.degree(1)
if degyhp > ybound:
continue
if degyhp < ybound:
m = 1
ybound = degyhp
continue
hp = hp.mul_ground(gamma1).trunc_ground(p)
if m == 1:
m = p
hlastm = hp
continue
hm = _chinese_remainder_reconstruction_multivariate(hp, hlastm, p, m)
m *= p
if not hm == hlastm:
hlastm = hm
continue
h = hm.quo_ground(hm.content())
fquo, frem = f.div(h)
gquo, grem = g.div(h)
if not frem and not grem:
if h.LC < 0:
ch = -ch
h = h.mul_ground(ch)
cff = fquo.mul_ground(cf // ch)
cfg = gquo.mul_ground(cg // ch)
return h, cff, cfg
def _modgcd_multivariate_p(f, g, p, degbound, contbound):
r"""
Compute the GCD of two polynomials in
`\mathbb{Z}_p[x_0, \ldots, x_{k-1}]`.
The algorithm reduces the problem step by step by evaluating the
polynomials `f` and `g` at `x_{k-1} = a` for suitable
`a \in \mathbb{Z}_p` and then calls itself recursively to compute the GCD
in `\mathbb{Z}_p[x_0, \ldots, x_{k-2}]`. If these recursive calls are
successful for enough evaluation points, the GCD in `k` variables is
interpolated, otherwise the algorithm returns ``None``. Every time a GCD
or a content is computed, their degrees are compared with the bounds. If
a degree greater then the bound is encountered, then the current call
returns ``None`` and a new evaluation point has to be chosen. If at some
point the degree is smaller, the correspondent bound is updated and the
algorithm fails.
Parameters
==========
f : PolyElement
multivariate integer polynomial with coefficients in `\mathbb{Z}_p`
g : PolyElement
multivariate integer polynomial with coefficients in `\mathbb{Z}_p`
p : Integer
prime number, modulus of `f` and `g`
degbound : list of Integer objects
``degbound[i]`` is an upper bound for the degree of the GCD of `f`
and `g` in the variable `x_i`
contbound : list of Integer objects
``contbound[i]`` is an upper bound for the degree of the content of
the GCD in `\mathbb{Z}_p[x_i][x_0, \ldots, x_{i-1}]`,
``contbound[0]`` is not used can therefore be chosen
arbitrarily.
Returns
=======
h : PolyElement
GCD of the polynomials `f` and `g` or ``None``
References
==========
1. [Monagan00]_
2. [Brown71]_
"""
ring = f.ring
k = ring.ngens
if k == 1:
h = _gf_gcd(f, g, p).trunc_ground(p)
degh = h.degree()
if degh > degbound[0]:
return None
if degh < degbound[0]:
degbound[0] = degh
raise ModularGCDFailed
return h
degyf = f.degree(k-1)
degyg = g.degree(k-1)
contf, f = _primitive(f, p)
contg, g = _primitive(g, p)
conth = _gf_gcd(contf, contg, p) # polynomial in Z_p[y]
degcontf = contf.degree()
degcontg = contg.degree()
degconth = conth.degree()
if degconth > contbound[k-1]:
return None
if degconth < contbound[k-1]:
contbound[k-1] = degconth
raise ModularGCDFailed
lcf = _LC(f)
lcg = _LC(g)
delta = _gf_gcd(lcf, lcg, p) # polynomial in Z_p[y]
evaltest = delta
for i in range(k-1):
evaltest *= _gf_gcd(_LC(_swap(f, i)), _LC(_swap(g, i)), p)
degdelta = delta.degree()