-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcuerpos_finitos_robusto.py
More file actions
1430 lines (1148 loc) · 47 KB
/
cuerpos_finitos_robusto.py
File metadata and controls
1430 lines (1148 loc) · 47 KB
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
import random, re
def primos(n): #devolvemos números primos menores o iguales que n
if n < 2:
return []
criba = [True] * (n + 1) #criba[i] nos dirá si i es primo o no
criba[0] = criba[1] = False
for i in range(2, int(n**0.5) + 1):
if criba[i]:
for j in range(i*i, n + 1, i):
criba[j] = False
return [i for i, es_primo in enumerate(criba) if es_primo]
def descompone(n): #descompone n en factores primos
factores = []
lprimos = primos(n)
i = 0
while n > 1:
if(n % lprimos[i] == 0):
factores.append((lprimos[i], 1))
n //= lprimos[i]
while(n % lprimos[i] == 0):
factores[-1] = (lprimos[i], factores[-1][1] + 1)
n //= lprimos[i]
i += 1
return factores
class ElemFp:
p = 5 #valor por defecto
def __init__(self, value):
if not isinstance(value, int):
raise ValueError(f"El valor introducido: {value}, no es un entero")
self.value = value % self.__class__.p
def __repr__(self):
return f"{self.value!r}"
def __str__(self):
return str(self.value)
@classmethod
def zero(cls):
return cls(0)
@classmethod
def one(cls):
return cls(1)
def __add__(self,other):
if not isinstance(other, self.__class__):
raise TypeError("Solo se puede sumar con otro Fp")
return self.__class__((self.value+other.value)%self.__class__.p)
def __neg__(self):
return self.__class__(-self.value % self.__class__.p)
def __sub__(self, other):
return self + (-other)
def __mul__(self, other):
if not isinstance(other, self.__class__):
return NotImplemented
return self.__class__((self.value * other.value) % self.__class__.p)
def __pow__(self, k):
if not isinstance(k, int):
raise TypeError("Exponente debe ser entero")
p = self.__class__.p
if self.value == 0:
if k < 0:
raise ZeroDivisionError("No se puede calcular el inverso de 0")
elif k == 0:
return self.__class__(1)
else: # k > 0
return self.__class__(0)
if k == 0:
return self.__class__(1)
k_eff = k % (p - 1)
return self.__class__(pow(self.value, k_eff, p))
def __truediv__(self, other):
if not isinstance(other,self.__class__):
raise TypeError("Solo se puede dividir entre otro Fp")
return self*other**-1
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.value == other.value
class ElemPol:
clase_cuerpo = ElemFp #por defecto
var = 'x'
@classmethod
def _trim_right_zeros(cls, t):
t = tuple(t) # asegurar que es tupla
i = len(t)
while i > 0 and t[i-1] == cls.clase_cuerpo.zero():
i -= 1
return t[:i]
def __init__(self, coefs):
for c in coefs:
if not isinstance(c, self.__class__.clase_cuerpo):
raise ValueError(f"El elemento {c} no pertenece al cuerpo {self.__class__.clase_cuerpo}")
self.coefs = self._trim_right_zeros(coefs)
def __repr__(self):
return f"{self.coefs!r}"
@classmethod
def pol_to_str(cls, pol, var):
terms = []
if issubclass(cls.clase_cuerpo, ElemFp):
c1 = ''
c2 = ''
else:
c1 = '('
c2 = ')'
for i, coef in enumerate(pol):
if coef == cls.clase_cuerpo.zero():
continue
# Decide la parte de la variable
if i == 0:
term = f"{coef}"
elif i == 1:
if coef == cls.clase_cuerpo.one():
term = f"{var}"
else:
term = f"{c1}{coef}{c2}{var}"
else:
if coef == cls.clase_cuerpo.one():
term = f"{var}^{i}"
else:
term = f"{c1}{coef}{c2}{var}^{i}"
terms.append(term)
if not terms:
return "0" #quiza cambiar por zero()
# Unión de términos con +, excepto el primero si tiene signo
result = terms[0]
for t in terms[1:]:
result += " + " + t
return result
def __str__(self):
return self.__class__.pol_to_str(self.coefs, self.__class__.var)
@classmethod
def zero(cls):
return cls(())
@classmethod
def one(cls):
return cls((cls.clase_cuerpo.one(),))
def grado(self):
return len(self.coefs) - 1 #grado de nulo -1
def __neg__(self):
return self.__class__(tuple(-c for c in self.coefs))
def __add__(self, other):
if not isinstance(other, self.__class__):
raise TypeError("Solo se puede sumar con otro polinomio en el mismo cuerpo")
max_len = max(len(self.coefs), len(other.coefs))
coefs = []
for i in range(max_len):
a = self.coefs[i] if i < len(self.coefs) else self.__class__.clase_cuerpo.zero()
b = other.coefs[i] if i < len(other.coefs) else self.__class__.clase_cuerpo.zero()
coefs.append(a + b)
return self.__class__(self._trim_right_zeros(tuple(coefs)))
def __sub__(self, other):
return self + (-other)
def __mul__(self, other):
if isinstance(other, self.__class__):
coefs = [self.__class__.clase_cuerpo.zero()] * (len(self.coefs) + len(other.coefs) - 1)
for i, a in enumerate(self.coefs):
for j, b in enumerate(other.coefs):
coefs[i+j] = coefs[i+j] + (a * b)
return self.__class__(self._trim_right_zeros(tuple(coefs)))
elif isinstance(other, self.__class__.clase_cuerpo):
# pol * escalar
return other*self
else:
raise TypeError("Multiplicación no soportada")
def __truediv__(self, other):
if not isinstance(other, self.__class__):
raise TypeError("Solo se puede dividir con otro polinomio en el mismo cuerpo")
if other == self.__class__.zero():
raise ZeroDivisionError("División por el polinomio 0")
A = list(self.coefs)
B = list(other.coefs)
m, n = len(A)-1, len(B)-1
Q = [self.__class__.clase_cuerpo.zero()] * (m - n + 1 if m >= n else 0)
while len(A) >= len(B):
# coeficiente líder
coef = A[-1] / B[-1]
d = len(A) - len(B)
Q[d] = coef
# resta coef*B*x^d
for i in range(len(B)):
A[i+d] = A[i+d] - coef * B[i]
A = list(self._trim_right_zeros(A))
return self.__class__(tuple(Q)), self.__class__(tuple(A))
def __floordiv__(self, other):
q, _ = self/other
return q
def __mod__(self, other):
_, r = self/other
return r
def __pow__(self, k, a = None):
if not isinstance(k, int):
raise TypeError("El exponente debe ser un entero")
if k < 0:
raise ValueError("No está definida la potencia negativa en polinomios")
result = self.__class__.one()
base = self if a is None else self % a
while k > 0:
if k & 1:
result = result * base
if a is not None:
result = result % a
base = base * base
if a is not None:
base = base % a
k >>= 1
return result
def __rmul__(self, other):
# Permite: escalar * pol
if isinstance(other, self.__class__.clase_cuerpo):
if other == self.__class__.clase_cuerpo.zero():
return self.__class__.zero()
return self.__class__(self._trim_right_zeros(tuple(c * other for c in self.coefs)))
raise TypeError("Solo se puede multiplicar por un escalar del mismo cuerpo")
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.coefs == other.coefs
@classmethod
def gcd_ext(cls, a, b):
"""
Devuelve (g, x, y) tales que g = a*x + b*y,
donde g = gcd(a, b) y g es mónico.
"""
if not isinstance(a, cls) or not isinstance(b, cls):
raise TypeError("gcd_ext solo está definido entre polinomios del mismo tipo")
zero = cls.zero()
one = cls.one()
# Inicialización
r0, r1 = a, b
s0, s1 = one, zero
t0, t1 = zero, one
# Algoritmo de Euclides extendido
while r1 != zero:
q, r = r0 / r1
r0, r1 = r1, r
s0, s1 = s1, s0 - q * s1
t0, t1 = t1, t0 - q * t1
# Hacer g mónico
if r0 != zero:
lead_inv = r0.coefs[-1] ** -1
r0 = lead_inv * r0
s0 = lead_inv * s0
t0 = lead_inv * t0
return r0, s0, t0
@classmethod
def gcd(cls, a, b):
g, _, _ = cls.gcd_ext(a, b)
return g
@classmethod
def inv_mod(cls, a, b):
"""
Devuelve x tal que a*x ≡ 1 (mod b)
Lanza ValueError si a y b no son coprimos.
"""
g, x, _ = cls.gcd_ext(a, b)
one = cls.one()
if g != one:
raise ValueError("El inverso modular no existe: gcd(a, b) ≠ 1")
return x % b
def derivada(self):
return self.__class__(tuple(self.clase_cuerpo(i%self.__class__.clase_cuerpo.p)*c for i, c in enumerate(self.coefs[1:], start=1))) #se hace modulo para asi en fq tratar con escalares reales, no polinomios asociados
class ElemFq:
"""
Representa un único elemento del cuerpo F_q.
"""
clase_pol = None
g = None
var = None
p = None
def __init__(self, value_pol):
if isinstance(value_pol, self.__class__.clase_pol):
self.value = value_pol % self.__class__.g
else:
raise TypeError(f"No se acepta el tipo {type(value_pol)} para construir ElemFq")
"""
elif isinstance(value_pol, int):
self.value = self.__class__.clase_pol(self.__class__.clase_pol.clase_cuerpo(value_pol))
"""
def __add__(self, other):
if not isinstance(other, self.__class__):
raise TypeError("No se puede operar con un elemento de otro cuerpo")
resultado_pol = (self.value + other.value) % self.__class__.g
return self.__class__(resultado_pol)
def __neg__(self):
resultado_pol = -self.value % self.__class__.g
return self.__class__(resultado_pol)
def __sub__(self, other):
return self + (-other)
def __mul__(self, other):
if not isinstance(other, self.__class__):
return NotImplemented
resultado_pol = (self.value * other.value) % self.__class__.g
return self.__class__(resultado_pol)
def __pow__(self, k):
if k >= 0:
resultado_pol = pow(self.value, k, self.__class__.g)
else:
resultado_pol = pow(self.__class__.clase_pol.inv_mod(self.value, self.__class__.g), -k, self.__class__.g)
return self.__class__(resultado_pol)
def __truediv__(self, other):
inv_other = self.__class__(self.__class__.clase_pol.inv_mod(other.value, self.__class__.g))
return self * inv_other
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.value == other.value #está todo siempre módulo g
def __repr__(self):
return f"ElemFq({self.value!r})"
def __str__(self):
return self.__class__.clase_pol.pol_to_str(self.value.coefs, self.__class__.var)
@classmethod
def zero(cls):
return cls(cls.clase_pol.zero())
@classmethod
def one(cls):
return cls(cls.clase_pol.one())
class cuerpo_fp:
def __init__(self, p): # construye el cuerpo de p elementos Fp = Z/pZ
if(p not in primos(p)):
raise ValueError(f"El número {p} no es primo")
self.p = p
class ElemFpP(ElemFp): #con esto impedimos que se puedan operar con elementos fabricados por distintos cuerpo_fp
pass
ElemFpP.p = p
ElemFpP.__name__ = f"F{p}"
self.elem_class = ElemFpP
def cero(self): # devuelve el elemento 0
return self.elem_class.zero()
def uno(self): # devuelve el elemento 1
return self.elem_class.one()
def elem_de_int(self, n): # fabrica el elemento dado por la clase de n
return self.elem_class(n)
def elem_de_str(self, s): # fabrica el elemento a partir de un string (parser)
try:
return self.elem_class(int(s.strip()))
except ValueError:
raise ValueError(f"No se puede convertir '{s}' en un entero")
def conv_a_int(self, a): # devuelve un entero entre 0 y p-1
if not isinstance(a, self.elem_class):
raise TypeError(f"No es un F{self.p} fabricado por este cuerpo")
return a.value
def conv_a_str(self, a): # pretty-printer
if not isinstance(a, self.elem_class):
raise TypeError(f"No es un F{self.p} fabricado por este cuerpo")
return str(a)
def suma(self, a, b): # a+b
if not isinstance(a, self.elem_class):
raise TypeError(f"No es un F{self.p} fabricado por este cuerpo")
return a + b
def inv_adit(self, a): # -a
if not isinstance(a, self.elem_class):
raise TypeError(f"No es un F{self.p} fabricado por este cuerpo")
return -a
def mult(self, a, b): # a*b
if not isinstance(a, self.elem_class):
raise TypeError(f"No es un F{self.p} fabricado por este cuerpo")
return a * b
def pot(self, a, k): # a^k (k entero)
if not isinstance(a, self.elem_class):
raise TypeError(f"No es un F{self.p} fabricado por este cuerpo")
return a ** k
def inv_mult(self, a): # a^(-1)
if not isinstance(a, self.elem_class):
raise TypeError(f"No es un F{self.p} fabricado por este cuerpo")
if a.value == 0:
raise ZeroDivisionError("No existe el inverso multiplicativo de 0")
return a ** -1
def es_cero(self, a): # a == 0
if not isinstance(a, self.elem_class):
raise TypeError(f"No es un F{self.p} fabricado por este cuerpo")
return a == self.cero()
def es_uno(self, a): # a == 1
if not isinstance(a, self.elem_class):
raise TypeError(f"No es un F{self.p} fabricado por este cuerpo")
return a == self.uno()
def es_igual(self, a, b): # a == b
if not isinstance(a, self.elem_class):
raise TypeError(f"No es un F{self.p} fabricado por este cuerpo")
return a == b
def aleatorio(self): # fabrica un elemento aleatorio con prob uniforme
return self.elem_de_int(random.randint(0, self.p - 1))
def tabla_suma(self): # devuelve la matriz de pxp (lista de listas) de la suma
return [[self.conv_a_int(self.elem_de_int(i) + self.elem_de_int(j)) for j in range(self.p)] for i in range(self.p)]
def tabla_mult(self): # devuelve la matriz de pxp (lista de listas) de la mult
return [[self.conv_a_int(self.elem_de_int(i) * self.elem_de_int(j)) for j in range(self.p)] for i in range(self.p)]
def tabla_inv_adit(self): # devuelve una lista de long p con los inv_adit
return [self.conv_a_int(-self.elem_de_int(i)) for i in range(self.p)]
def tabla_inv_mult(self): # devuelve una lista de long p con los inv_mult (en el índice 0 pone un '*')
return ['*'] + [self.conv_a_int(self.inv_mult(self.elem_de_int(i))) for i in range(1, self.p)]
def cuadrado_latino(self, a): # cuadrado latino a*i+j (con a != 0)
if isinstance(a, int):
a = self.elem_de_int(a)
if self.es_cero(a):
raise ValueError("a debe ser distinto de cero para cuadrado latino")
return [[self.conv_a_int(a * self.elem_de_int(i) + self.elem_de_int(j)) for j in range(self.p)] for i in range(self.p)]
class anillo_fp_x:
def __init__(self, fp, var='x'): # construye el anillo Fp[var]
if isinstance(fp, cuerpo_fp):
self.fp = fp
elif isinstance(fp, int):
#por si usuario pasa como fp el primo a usar
self.fp = cuerpo_fp(fp)
else:
raise TypeError("No se acepta fp")
if not isinstance(var, str):
raise TypeError("var debe ser un string")
self.var = var
# Creamos una subclase local de ElemPol ligada a este cuerpo
class Pol(ElemPol):
clase_cuerpo = self.fp.elem_class
var = self.var
Pol.__name__ = f"{self.fp.elem_class}[{self.var}]"
self.elem_class = Pol
self.p = self.fp.p
def cero(self): # 0
return self.elem_class.zero()
def uno(self): # 1
return self.elem_class.one()
def elem_de_tuple(self, a): # fabrica un polinomio a partir de la tupla (a0, a1, ...), ai debe haber sido fabricado por fp!
return self.elem_class(a)
def elem_de_int(self, a): # fabrica un polinomio a partir de los dígitos de a en base p
if not isinstance(a, int):
raise ValueError("Debe ser un entero")
coefs = []
n = a
while n > 0:
coefs.append(self.fp.elem_de_int(n % self.fp.p))
n //= self.fp.p
return self.elem_class(tuple(coefs))
def elem_de_str(self, s): # fabrica un polinomio a partir de un string (parser), hecho por IA
terms = re.findall(r'([+-]?[^+-]+)', s.replace(" ",""))
coeffs_dict = {}
max_deg = 0
for term in terms:
if self.var in term:
if '*' in term:
coef_part, x_part = term.split('*')
else:
match = re.match(r'([+-]?\d*)(%s(\^\d+)?)' % re.escape(self.var), term)
if match:
coef_part, x_part, _ = match.groups()
else:
raise ValueError(f"Término inválido: {term}")
deg = int(x_part.split('^')[1]) if '^' in x_part else 1
coef = 1 if coef_part in ('','+') else -1 if coef_part=='-' else int(coef_part)
else:
deg = 0
coef = int(term)
coeffs_dict[deg] = coeffs_dict.get(deg,0) + coef
max_deg = max(max_deg, deg)
length = max_deg+1
coeffs = [0]*length
for deg, coef in coeffs_dict.items():
coeffs[deg] = self.fp.elem_de_int(coef)
return self.elem_de_tuple(coeffs)
def conv_a_tuple(self, a): # devuelve la tupla de coeficientes
if not isinstance(a, self.elem_class):
raise TypeError("Objeto no fabricado por este anillo")
return a.coefs
def conv_a_int(self, a): # devuelve el entero correspondiente al polinomio
if not isinstance(a, self.elem_class):
raise TypeError("Objeto no fabricado por este anillo")
n = 0
aux = 1
for c in a.coefs:
n += self.fp.conv_a_int(c) * aux
aux *= self.fp.p
return n
def conv_a_str(self, a): # pretty-printer
if not isinstance(a, self.elem_class):
raise TypeError("Objeto no fabricado por este anillo")
return str(a)
def suma(self, a, b): # a+b
if not isinstance(a, self.elem_class):
raise TypeError("Objeto no fabricado por este anillo")
return a + b
def inv_adit(self, a): # -a
if not isinstance(a, self.elem_class):
raise TypeError("Objeto no fabricado por este anillo")
return -a
def mult(self, a, b): # a*b
if not isinstance(a, self.elem_class):
raise TypeError("Objeto no fabricado por este anillo")
return a * b
def mult_por_escalar(self, a, e): # a*e (con e en Z/pZ)
if not isinstance(a, self.elem_class):
raise TypeError("Objeto no fabricado por este anillo")
if not isinstance(e, self.fp.elem_class):
raise TypeError("Escalar no compatible")
return e * a
def divmod(self, a, b): # devuelve q,r tales que a=bq+r y deg(r)<deg(b)
if not isinstance(a, self.elem_class):
raise TypeError("Objeto no fabricado por este anillo")
return a / b
def div(self, a, b): # q
if not isinstance(a, self.elem_class):
raise TypeError("Objeto no fabricado por este anillo")
return a // b
def mod(self, a, b): # r
if not isinstance(a, self.elem_class):
raise TypeError("Objeto no fabricado por este anillo")
return a % b
def grado(self, a): # deg(a)
if not isinstance(a, self.elem_class):
raise TypeError("Objeto no fabricado por este anillo")
return a.grado()
def gcd(self, a, b): # devuelve g = gcd(a,b) mónico
if not isinstance(a, self.elem_class):
raise TypeError("Objeto no fabricado por este anillo")
return self.elem_class.gcd(a, b)
def gcd_ext(self, a, b): # devuelve g,x,y tales que g=ax+by, g=gcd(a,b) mónico
if not isinstance(a, self.elem_class):
raise TypeError("Objeto no fabricado por este anillo")
return self.elem_class.gcd_ext(a, b)
def inv_mod(self, a, b): # devuelve x tal que ax = 1 mod b
if not isinstance(a, self.elem_class):
raise TypeError("Objeto no fabricado por este anillo")
return self.elem_class.inv_mod(a, b)
def pot_mod(self, a, k, b): # a^k mod b
if not isinstance(a, self.elem_class):
raise TypeError("Objeto no fabricado por este anillo")
return a.__pow__(k, b)
def es_cero(self, a): # a == 0
if not isinstance(a, self.elem_class):
raise TypeError("Objeto no fabricado por este anillo")
return a == self.cero()
def es_uno(self, a): # a == 1
if not isinstance(a, self.elem_class):
raise TypeError("Objeto no fabricado por este anillo")
return a == self.uno()
def es_igual(self, a, b): # a == b
if not isinstance(a, self.elem_class):
raise TypeError("Objeto no fabricado por este anillo")
return a == b
def derivada(self, a):
if not isinstance(a, self.elem_class):
raise TypeError("Objeto no fabricado por este anillo")
return a.derivada()
"""
def sfd(self, a):
if self.es_cero(a):
return []
df = self.derivada(f)
g = self.gcd(f, df)
w = f // g
i = 1
factores = []
while not self.es_cero(w):
y = self.gcd(w, g)
fi = w // y
if not self.es_uno(fi):
factores.append((fi, i))
w = y
g = g // y
i += 1
return factores
"""
def sfd(self, f): #para monicos, de grado > 0
if self.es_cero(f):
return []
L = []
s = 1
p = self.fp.p
while True:
j = 1
df = self.derivada(f)
g = self.div(f, self.gcd(f, df)) # g = f / gcd(f, D(f))
while not self.es_uno(g):
f = self.div(f, g)
h = self.gcd(f, g)
m = self.div(g, h)
if not self.es_uno(m):
L.append((m, j * s))
g = h
j += 1
# Si f aún no es 1, significa que es una p-ésima potencia
if not self.es_uno(f):
# Calculamos la raíz p-ésima:
# basta con tomar los coeficientes de índice múltiplo de p
tupla_f = self.conv_a_tuple(f)
coefs = [tupla_f[i] for i in range(0, len(tupla_f), p)]
f = self.elem_de_tuple(tuple(coefs))
s *= p
else:
break
return L
def ddf(self, f): #para monicos, grado > 0, square-free
if self.es_cero(f):
return []
L = []
pol_x = self.elem_de_int(self.p)
h = self.mod(pol_x, f)
p = self.fp.p
k = 0
while not self.es_uno(f):
h = self.pot_mod(h, p, f)
k += 1
g = self.gcd(self.suma(h, self.inv_adit(pol_x)), f)
if not self.es_uno(g):
L.append((g, k))
f = self.div(f, g)
h = self.mod(h, f)
return L
def Mk(self, alpha, k, g):
p = self.fp.p
if p == 2:
# caso p=2: suma de potencias de 2
res = self.cero()
for j in range(k):
res = self.suma(res, self.pot_mod(alpha, 2**j, g))
return res
else:
# caso p>2
exp = (p**k - 1) // 2
return self.suma(self.pot_mod(alpha, exp, g), self.inv_adit(self.uno()))
def edf(self, f , k): #para monicos, grado > 0, producto de irreducibles de grado k
h = [f]
r = self.grado(f)//k
while len(h) < r:
h1 = []
for g in h:
alpha = self.elem_de_int(random.randint(0, self.p ** self.grado(g)-1))
mk_alpha = self.Mk(alpha, k, g)
d = self.gcd(mk_alpha, g)
if self.es_uno(d) or self.es_igual(d, g):
h1.append(g)
else:
h1.extend([d, self.div(g, d)])
h = h1
return h
def es_irreducible(self, f): # test de irreducibilidad de Rabin
n = self.grado(f)
if n == 0 or n == -1: #caso polinomio nulo y ctes
return False
if n == 1:
return True
p = self.fp.p
pol_x = self.elem_de_int(self.p) #ya esta modulo f, por grado mayor
pol_x_pn = self.pot_mod(pol_x, p ** n, f)
if not self.es_igual(pol_x_pn, pol_x):
return False
for d,_ in descompone(n):
q = p ** (n // d)
pol_x_pq = self.pot_mod(pol_x, q, f)
g = self.gcd(pol_x_pq - pol_x, f)
if not self.es_uno(g):
return False
return True
def factorizar(self, f): # factorización de Cantor-Zassenhaus
factores_finales = []
for g, m in self.sfd(f):
for h, k in self.ddf(g):
for t in self.edf(h, k):
factores_finales.append((t, m))
return factores_finales
class cuerpo_fq:
def __init__(self, fp, g, var='a'): # construye el cuerpo Fp[var]/<g(var)>, fp es el cuerpo, g tupla de elementos de fp
if isinstance(fp, cuerpo_fp):
self.fp = anillo_fp_x(fp, var)
self.g = self.fp.elem_de_tuple(g)
else:
raise TypeError("No se acepta fp, debe ser un cuerpo")
if not self.fp.es_irreducible(self.g):
raise ValueError("g debe ser un polinomio irreducible")
self.var = var
self.q = self.fp.p ** self.g.grado()
self.p = self.fp.p
class sElemFq(ElemFq):
clase_pol = self.fp.elem_class
g = self.g
var = self.var
p = self.p
sElemFq.__name__ = f"F{self.q}"
self.elem_class = sElemFq
def cero(self): # 0
return self.elem_class.zero()
def uno(self): # 1
return self.elem_class.one()
def elem_de_tuple(self, coefs): # fabrica elemento a partir de tupla de coeficientes de cuerpo_fp
return self.elem_class(self.fp.elem_de_tuple(coefs))
def elem_de_int(self, n): # fabrica elemento a partir de entero
return self.elem_class(self.fp.elem_de_int(n)) #asumimos n representa polinomio de Fp[x], luego para n > q habrá que reducirlo módulo g. Otra opción es hacer n%=q y entonces representará otra cosa
#para n < q ambas se comportan igual
def elem_de_str(self, s): # fabrica elemento parseando string
return self.elem_class(self.fp.elem_de_str(s))
def conv_a_tuple(self, a): # devuelve tupla de coeficientes sin ceros "extra"
if not isinstance(a, self.elem_class):
raise TypeError("Objeto no fabricado por el cuerpo")
return self.fp.conv_a_tuple(a.value)
def conv_a_int(self, a): # devuelve el entero correspondiente
if not isinstance(a, self.elem_class):
raise TypeError("Objeto no fabricado por el cuerpo")
return self.fp.conv_a_int(a.value)
def conv_a_str(self, a): # pretty-printer
if not isinstance(a, self.elem_class):
raise TypeError("Objeto no fabricado por el cuerpo")
return str(a)
def suma(self, a, b): # a+b
if not isinstance(a, self.elem_class):
raise TypeError("Objeto no fabricado por el cuerpo")
return a+b
def inv_adit(self, a): # -a
if not isinstance(a, self.elem_class):
raise TypeError("Objeto no fabricado por el cuerpo")
return -a
def mult(self, a, b): # a*b
if not isinstance(a, self.elem_class):
raise TypeError("Objeto no fabricado por el cuerpo")
return a*b
def pot(self, a, k): # a^k (k entero)
if not isinstance(a, self.elem_class):
raise TypeError("Objeto no fabricado por el cuerpo")
return a**k
def inv_mult(self, a): # a^(-1)
if not isinstance(a, self.elem_class):
raise TypeError("Objeto no fabricado por el cuerpo")
return a**(-1)
def es_cero(self, a): # a == 0
if not isinstance(a, self.elem_class):
raise TypeError("Objeto no fabricado por el cuerpo")
return a == self.cero()
def es_uno(self, a): # a == 1
if not isinstance(a, self.elem_class):
raise TypeError("Objeto no fabricado por el cuerpo")
return a == self.uno()
def es_igual(self, a, b): # a == b, en todos los métodos elementos que se pasan ya están módulo g, han tenido que ser fabricados.
if not isinstance(a, self.elem_class):
raise TypeError("Objeto no fabricado por el cuerpo")
return a == b
def aleatorio(self): # devuelve un elemento aleatorio con prob uniforme
return self.elem_de_int(random.randint(0, self.q - 1))
def tabla_suma(self): # matriz de qxq correspondiente a la suma (con la notación int)
elems = [self.elem_de_int(i) for i in range(self.q)]
return [[self.conv_a_int(self.suma(a,b)) for b in elems] for a in elems]
def tabla_mult(self): # matriz de qxq correspondiente a la mult (con la notación int)
elems = [self.elem_de_int(i) for i in range(self.q)]
return [[self.conv_a_int(self.mult(a,b)) for b in elems] for a in elems]
def tabla_inv_adit(self): # lista de inv_adit (con la notación int)
elems = [self.elem_de_int(i) for i in range(self.q)]
return [self.conv_a_int(self.inv_adit(a)) for a in elems]
def tabla_inv_mult(self): # lista de inv_mult (con la notación int)
elems = [self.elem_de_int(i) for i in range(self.q)]
res = ['*'] # índice 0 no tiene inverso
for a in elems[1:]:
try:
res.append(self.conv_a_int(self.inv_mult(a)))
except ValueError:
res.append(None)
return res
def cuadrado_latino(self, a): # cuadrado latino para a != 0 (con notación int)
if isinstance(a, int):
a = self.elem_de_int(a)
if self.es_cero(a):
raise ValueError("a debe ser distinto de cero")
elems = [self.elem_de_int(i) for i in range(self.q)]
return [[self.conv_a_int(self.suma(self.mult(a, elems[i]), elems[j])) for j in range(self.q)] for i in range(self.q)]
class anillo_fq_x: #copia de anillo_fp_x
def __init__(self, fq, var='x'): # # Fq[var], var debe ser distinta que la de fq
if isinstance(fq, cuerpo_fq):
self.fq = fq
else:
raise TypeError("No se acepta fq")
if var == fq.var:
raise ValueError("var debe ser distinta de la de fq")
self.var = var
# Creamos una subclase local de ElemPol ligada a este cuerpo
class Pol(ElemPol):
clase_cuerpo = fq.elem_class
var = self.var
Pol.__name__ = f"{fq.elem_class}[{self.var}]"
self.elem_class = Pol
self.q = self.fq.q
self.p = self.fq.p
def cero(self): # 0
return self.elem_class.zero()
def uno(self): # 1
return self.elem_class.one()
def elem_de_tuple(self, a): # fabrica un polinomio a partir de la tupla (a0, a1, ...)
return self.elem_class(a)
def elem_de_int(self, a): # fabrica un polinomio a partir de los dígitos de a en base q
if not isinstance(a, int):
raise ValueError("Debe ser un entero")
coefs = []
n = a
while n > 0:
coefs.append(self.fq.elem_de_int(n % self.q))
n //= self.q
return self.elem_class(tuple(coefs))
def _eval_coef_expr(self, expr_str):
"""
Función de arranque para el nuevo parser.
Crea una instancia de _CoefParser y ejecuta el parseo.
"""
# 1. Tokenizer: Convierte el string en una lista de tokens.
# Ej: "a^2 + 3" -> ['a', '^', '2', '+', '3']
tokens = re.findall(r'(\d+|[a-zA-Z]+|[+\-*/^()])', expr_str)
# 2. Creamos y ejecutamos el parser.
parser = self._CoefParser(tokens, self.fq)
return parser.parse()
class _CoefParser:
"""
Clase interna que implementa un parser recursivo descendente
para las expresiones de los coeficientes.