-
-
Notifications
You must be signed in to change notification settings - Fork 396
/
finite_field_base.pyx
1883 lines (1530 loc) · 63.5 KB
/
finite_field_base.pyx
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
"""
Base Classes for Finite Fields
TESTS::
sage: K.<a> = NumberField(x^2 + 1)
sage: F = K.factor(3)[0][0].residue_field()
sage: loads(dumps(F)) == F
True
AUTHORS:
- Adrien Brochard, David Roe, Jeroen Demeyer, Julian Rueth, Niles Johnson,
Peter Bruin, Travis Scrimshaw, Xavier Caruso: initial version
"""
#*****************************************************************************
# Copyright (C) 2009 David Roe <roed@math.harvard.edu>
# Copyright (C) 2010 Niles Johnson <nilesj@gmail.com>
# Copyright (C) 2011 Jeroen Demeyer <jdemeyer@cage.ugent.be>
# Copyright (C) 2012 Adrien Brochard <aaa.brochard@gmail.com>
# Copyright (C) 2012 Travis Scrimshaw <tscrim@ucdavis.edu>
# Copyright (C) 2012 Xavier Caruso <xavier.caruso@normalesup.org>
# Copyright (C) 2013 Peter Bruin <P.Bruin@warwick.ac.uk>
# Copyright (C) 2014 Julian Rueth <julian.rueth@fsfe.org>
#
# Distributed under the terms of the GNU General Public License (GPL)
# as published by the Free Software Foundation; either version 2 of
# the License, or (at your option) any later version.
# http://www.gnu.org/licenses/
#*****************************************************************************
from __future__ import absolute_import
cimport cython
from cysignals.signals cimport sig_check
from cpython.array cimport array
from sage.categories.finite_fields import FiniteFields
from sage.structure.parent cimport Parent
from sage.misc.persist import register_unpickle_override
from sage.misc.cachefunc import cached_method
from sage.misc.prandom import randrange
from sage.rings.integer cimport Integer
from sage.misc.superseded import deprecation
# Copied from sage.misc.fast_methods, used in __hash__() below.
cdef int SIZEOF_VOID_P_SHIFT = 8*sizeof(void *) - 4
cdef class FiniteField(Field):
"""
Abstract base class for finite fields.
TESTS::
sage: GF(997).is_finite()
True
"""
def __init__(self, base, names, normalize, category=None):
"""
Initialize ``self``.
EXAMPLES::
sage: K = GF(7); K
Finite Field of size 7
sage: loads(K.dumps()) == K
True
sage: GF(7^10, 'a')
Finite Field in a of size 7^10
sage: K = GF(7^10, 'a'); K
Finite Field in a of size 7^10
sage: loads(K.dumps()) == K
True
"""
if category is None:
category = FiniteFields()
Field.__init__(self, base, names, normalize, category)
# The methods __hash__ and __richcmp__ below were copied from
# sage.misc.fast_methods.WithEqualityById; we cannot inherit from
# this since Cython does not support multiple inheritance.
def __hash__(self):
"""
The hash provided by this class coincides with that of ``<type 'object'>``.
TESTS::
sage: F.<a> = FiniteField(2^3)
sage: hash(F) == hash(F)
True
sage: hash(F) == object.__hash__(F)
True
"""
# This is the default hash function in Python's object.c:
cdef long x
cdef size_t y = <size_t><void *>self
y = (y >> 4) | (y << SIZEOF_VOID_P_SHIFT)
x = <long>y
if x==-1:
x = -2
return x
def __richcmp__(self, other, int m):
"""
Compare ``self`` with ``other``.
Finite fields compare equal if and only if they are identical.
In particular, they are not equal unless they have the same
cardinality, modulus, variable name and implementation.
EXAMPLES::
sage: x = polygen(GF(3))
sage: F = FiniteField(3^2, 'c', modulus=x^2+1)
sage: F == F
True
sage: F == FiniteField(3^3, 'c')
False
sage: F == FiniteField(3^2, 'c', modulus=x^2+x+2)
False
sage: F == FiniteField(3^2, 'd')
False
sage: F == FiniteField(3^2, 'c', impl='pari_ffelt')
False
"""
if self is other:
if m == 2: # ==
return True
elif m == 3: # !=
return False
else:
# <= or >= or NotImplemented
return m==1 or m==5 or NotImplemented
else:
if m == 2:
return False
elif m == 3:
return True
else:
return NotImplemented
def is_perfect(self):
r"""
Return whether this field is perfect, i.e., every element has a `p`-th
root. Always returns ``True`` since finite fields are perfect.
EXAMPLES::
sage: GF(2).is_perfect()
True
"""
return True
def __repr__(self):
"""
String representation of this finite field.
EXAMPLES::
sage: k = GF(127)
sage: k # indirect doctest
Finite Field of size 127
sage: k.<b> = GF(2^8)
sage: k
Finite Field in b of size 2^8
sage: k.<c> = GF(2^20)
sage: k
Finite Field in c of size 2^20
sage: k.<d> = GF(7^20)
sage: k
Finite Field in d of size 7^20
"""
if self.degree()>1:
return "Finite Field in %s of size %s^%s"%(self.variable_name(),self.characteristic(),self.degree())
else:
return "Finite Field of size %s"%(self.characteristic())
def _latex_(self):
r"""
Returns a string denoting the name of the field in LaTeX.
The :func:`~sage.misc.latex.latex` function calls the
``_latex_`` attribute when available.
EXAMPLES:
The ``latex`` command parses the string::
sage: GF(81, 'a')._latex_()
'\\Bold{F}_{3^{4}}'
sage: latex(GF(81, 'a'))
\Bold{F}_{3^{4}}
sage: GF(3)._latex_()
'\\Bold{F}_{3}'
sage: latex(GF(3))
\Bold{F}_{3}
"""
if self.degree() > 1:
e = "^{%s}"%self.degree()
else:
e = ""
return "\\Bold{F}_{%s%s}"%(self.characteristic(), e)
def _gap_init_(self):
"""
Return string that initializes the GAP version of
this finite field.
EXAMPLES::
sage: GF(9,'a')._gap_init_()
'GF(9)'
"""
return 'GF(%s)'%self.order()
def _magma_init_(self, magma):
"""
Return string representation of ``self`` that Magma can
understand.
EXAMPLES::
sage: GF(97,'a')._magma_init_(magma) # optional - magma
'GF(97)'
sage: GF(9,'a')._magma_init_(magma) # optional - magma
'SageCreateWithNames(ext<GF(3)|_sage_[...]![GF(3)!2,GF(3)!2,GF(3)!1]>,["a"])'
sage: magma(GF(9,'a')) # optional - magma
Finite field of size 3^2
sage: magma(GF(9,'a')).1 # optional - magma
a
"""
if self.degree() == 1:
return 'GF(%s)'%self.order()
B = self.base_ring()
p = self.polynomial()
s = "ext<%s|%s>"%(B._magma_init_(magma),p._magma_init_(magma))
return magma._with_names(s, self.variable_names())
def _macaulay2_init_(self):
"""
Returns the string representation of ``self`` that Macaulay2 can
understand.
EXAMPLES::
sage: GF(97,'a')._macaulay2_init_()
'GF(97,Variable=>symbol x)'
sage: macaulay2(GF(97, 'a')) # optional - macaulay2
GF 97
sage: macaulay2(GF(49, 'a')) # optional - macaulay2
GF 49
TESTS:
The variable name is preserved (:trac:`28566`)::
sage: K = macaulay2(GF(49, 'b')) # optional - macaulay2
sage: K.gens() # optional - macaulay2
{b}
sage: K._sage_() # optional - macaulay2
Finite Field in b of size 7^2
"""
return "GF(%s,Variable=>symbol %s)" % (self.order(),
self.variable_name())
def _sage_input_(self, sib, coerced):
r"""
Produce an expression which will reproduce this value when evaluated.
EXAMPLES::
sage: sage_input(GF(5), verify=True)
# Verified
GF(5)
sage: sage_input(GF(32, 'a'), verify=True)
# Verified
R.<x> = GF(2)[]
GF(2^5, 'a', x^5 + x^2 + 1)
sage: K = GF(125, 'b')
sage: sage_input((K, K), verify=True)
# Verified
R.<x> = GF(5)[]
GF_5_3 = GF(5^3, 'b', x^3 + 3*x + 3)
(GF_5_3, GF_5_3)
sage: from sage.misc.sage_input import SageInputBuilder
sage: GF(81, 'a')._sage_input_(SageInputBuilder(), False)
{call: {atomic:GF}({binop:** {atomic:3} {atomic:4}}, {atomic:'a'}, {binop:+ {binop:+ {binop:** {gen:x {constr_parent: {subscr: {call: {atomic:GF}({atomic:3})}[{atomic:'x'}]} with gens: ('x',)}} {atomic:4}} {binop:* {atomic:2} {binop:** {gen:x {constr_parent: {subscr: {call: {atomic:GF}({atomic:3})}[{atomic:'x'}]} with gens: ('x',)}} {atomic:3}}}} {atomic:2}})}
"""
if self.degree() == 1:
v = sib.name('GF')(sib.int(self.characteristic()))
name = 'GF_%d' % self.characteristic()
else:
v = sib.name('GF')(sib.int(self.characteristic()) ** sib.int(self.degree()),
self.variable_name(),
self.modulus())
name = 'GF_%d_%d' % (self.characteristic(), self.degree())
sib.cache(self, v, name)
return v
@cython.boundscheck(False)
@cython.wraparound(False)
def __iter__(self):
"""
Iterate over all elements of this finite field.
EXAMPLES::
sage: k.<a> = FiniteField(9, impl="pari")
sage: list(k)
[0, 1, 2, a, a + 1, a + 2, 2*a, 2*a + 1, 2*a + 2]
Partial iteration of a very large finite field::
sage: p = next_prime(2^64)
sage: k.<a> = FiniteField(p^2, impl="pari")
sage: it = iter(k); it
<generator object at ...>
sage: [next(it) for i in range(10)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
TESTS:
Check that the generic implementation works in all cases::
sage: L = []
sage: from sage.rings.finite_rings.finite_field_base import FiniteField
sage: for impl in ("givaro", "pari", "ntl"):
....: k = GF(8, impl=impl, names="z")
....: print(list(FiniteField.__iter__(k)))
[0, 1, z, z + 1, z^2, z^2 + 1, z^2 + z, z^2 + z + 1]
[0, 1, z, z + 1, z^2, z^2 + 1, z^2 + z, z^2 + z + 1]
[0, 1, z, z + 1, z^2, z^2 + 1, z^2 + z, z^2 + z + 1]
"""
cdef Py_ssize_t n = self.degree()
cdef unsigned long lim # maximum value for coefficients
try:
lim = (<unsigned long>self.characteristic()) - 1
except OverflowError:
# If the characteristic is too large to represent in an
# "unsigned long", it is reasonable to assume that we won't
# be able to iterate over all elements. Typically n >= 2,
# so that would mean >= 2^64 elements on a 32-bit system.
# Just in case that we iterate to the end anyway, we raise
# an exception at the end.
lim = <unsigned long>(-1)
elt = self.zero()
one = self.one()
x = self.gen()
# coeffs[] is an array of coefficients of the current finite
# field element (as unsigned longs)
#
# Stack represents an element
# sum_{i=0}^{n-1} coeffs[i] x^i
# as follows:
# stack[k] = sum_{i=k}^{n-1} coeffs[i] x^(i-k)
#
# This satisfies the recursion
# stack[k-1] = x * stack[k] + coeffs[k-1]
#
# Finally, elt is a shortcut for stack[k]
#
cdef list stack = [elt] * n
cdef array coeffsarr = array('L', [0] * n)
cdef unsigned long* coeffs = coeffsarr.data.as_ulongs
yield elt # zero
cdef Py_ssize_t k = 0
while k < n:
# Find coefficients of next element
coeff = coeffs[k]
if coeff >= lim:
# We cannot increase coeffs[k], so we wrap around to 0
# and try to increase the next coefficient
coeffs[k] = 0
k += 1
continue
coeffs[k] = coeff + 1
# Now compute and yield the finite field element
sig_check()
elt = stack[k] + one
stack[k] = elt
# Fix lower elements of stack, until k == 0
while k > 0:
elt *= x
k -= 1
stack[k] = elt
yield elt
if lim == <unsigned long>(-1):
raise NotImplementedError("iterating over all elements of a large finite field is not supported")
def _is_valid_homomorphism_(self, codomain, im_gens, base_map=None):
"""
Return ``True`` if the map from self to codomain sending
``self.0`` to the unique element of ``im_gens`` is a valid field
homomorphism. Otherwise, return ``False``.
EXAMPLES::
Between prime fields::
sage: k0 = FiniteField(73, modulus='primitive')
sage: k1 = FiniteField(73)
sage: k0._is_valid_homomorphism_(k1, (k1(5),) )
True
sage: k1._is_valid_homomorphism_(k0, (k0(1),) )
True
Now for extension fields::
sage: k.<a> = FiniteField(73^2)
sage: K.<b> = FiniteField(73^3)
sage: L.<c> = FiniteField(73^4)
sage: k0._is_valid_homomorphism_(k, (k(5),) )
True
sage: k.hom([c]) # indirect doctest
Traceback (most recent call last):
...
TypeError: images do not define a valid homomorphism
sage: k.hom([c^(73*73+1)])
Ring morphism:
From: Finite Field in a of size 73^2
To: Finite Field in c of size 73^4
Defn: a |--> 7*c^3 + 13*c^2 + 65*c + 71
sage: k.hom([b])
Traceback (most recent call last):
...
TypeError: images do not define a valid homomorphism
"""
#if self.characteristic() != codomain.characteristic():
# raise ValueError("no map from %s to %s" % (self, codomain))
# When the base is not just Fp, we want to ensure that there's a
# coercion map from the base rather than just checking the characteristic
if base_map is None and not codomain.has_coerce_map_from(self.base_ring()):
return False
if len(im_gens) != 1:
raise ValueError("only one generator for finite fields")
f = self.modulus()
if base_map is not None:
f = f.map_coefficients(base_map)
return f(im_gens[0]).is_zero()
def _Hom_(self, codomain, category=None):
"""
Return the set of homomorphisms from ``self`` to ``codomain``
in ``category``.
This function is implicitly called by the ``Hom`` method or
function.
EXAMPLES::
sage: K.<a> = GF(25); K
Finite Field in a of size 5^2
sage: K.Hom(K) # indirect doctest
Automorphism group of Finite Field in a of size 5^2
"""
from sage.rings.finite_rings.homset import FiniteFieldHomset
if category.is_subcategory(FiniteFields()):
return FiniteFieldHomset(self, codomain, category)
return super(FiniteField, self)._Hom_(codomain, category)
def _squarefree_decomposition_univariate_polynomial(self, f):
"""
Return the square-free decomposition of this polynomial. This is a
partial factorization into square-free, coprime polynomials.
This is a helper method for
:meth:`sage.rings.polynomial.squarefree_decomposition`.
INPUT:
- ``f`` -- a univariate non-zero polynomial over this field
ALGORITHM; [Coh1993]_, algorithm 3.4.2 which is basically the algorithm in
[Yun1976]_ with special treatment for powers divisible by `p`.
EXAMPLES::
sage: K.<a> = GF(3^2)
sage: R.<x> = K[]
sage: f = x^243+2*x^81+x^9+1
sage: f.squarefree_decomposition()
(x^27 + 2*x^9 + x + 1)^9
sage: f = x^243+a*x^27+1
sage: f.squarefree_decomposition()
(x^9 + (2*a + 1)*x + 1)^27
TESTS::
sage: for K in [GF(2^18,'a'), GF(3^2,'a'), GF(47^3,'a')]:
....: R.<x> = K[]
....: if K.characteristic() < 5: m = 4
....: else: m = 1
....: for _ in range(m):
....: f = (R.random_element(4)^3*R.random_element(m)^(m+1))(x^6)
....: F = f.squarefree_decomposition()
....: assert F.prod() == f
....: for i in range(len(F)):
....: assert gcd(F[i][0], F[i][0].derivative()) == 1
....: for j in range(len(F)):
....: if i == j: continue
....: assert gcd(F[i][0], F[j][0]) == 1
....:
"""
from sage.structure.factorization import Factorization
if f.degree() == 0:
return Factorization([], unit=f[0])
factors = []
p = self.characteristic()
unit = f.leading_coefficient()
T0 = f.monic()
e = 1
if T0.degree() > 0:
der = T0.derivative()
while der.is_zero():
T0 = T0.parent()([T0[p*i].pth_root() for i in range(T0.degree()//p + 1)])
if T0 == 1:
raise RuntimeError
der = T0.derivative()
e = e*p
T = T0.gcd(der)
V = T0 // T
k = 0
while T0.degree() > 0:
k += 1
if p.divides(k):
T = T // V
k += 1
W = V.gcd(T)
if W.degree() < V.degree():
factors.append((V // W, e*k))
V = W
T = T // V
if V.degree() == 0:
if T.degree() == 0:
break
# T is of the form sum_{i=0}^n t_i X^{pi}
T0 = T0.parent()([T[p*i].pth_root() for i in range(T.degree()//p + 1)])
der = T0.derivative()
e = p*e
while der.is_zero():
T0 = T0.parent()([T0[p*i].pth_root() for i in range(T0.degree()//p + 1)])
der = T0.derivative()
e = p*e
T = T0.gcd(der)
V = T0 // T
k = 0
else:
T = T//V
return Factorization(factors, unit=unit, sort=False)
def gen(self):
r"""
Return a generator of this field (over its prime field). As this is an
abstract base class, this just raises a ``NotImplementedError``.
EXAMPLES::
sage: K = GF(17)
sage: sage.rings.finite_rings.finite_field_base.FiniteField.gen(K)
Traceback (most recent call last):
...
NotImplementedError
"""
raise NotImplementedError
def zeta_order(self):
"""
Return the order of the distinguished root of unity in ``self``.
EXAMPLES::
sage: GF(9,'a').zeta_order()
8
sage: GF(9,'a').zeta()
a
sage: GF(9,'a').zeta().multiplicative_order()
8
"""
return self.order() - 1
def zeta(self, n=None):
"""
Return an element of multiplicative order ``n`` in this finite
field. If there is no such element, raise ``ValueError``.
.. WARNING::
In general, this returns an arbitrary element of the correct
order. There are no compatibility guarantees:
``F.zeta(9)^3`` may not be equal to ``F.zeta(3)``.
EXAMPLES::
sage: k = GF(7)
sage: k.zeta()
3
sage: k.zeta().multiplicative_order()
6
sage: k.zeta(3)
2
sage: k.zeta(3).multiplicative_order()
3
sage: k = GF(49, 'a')
sage: k.zeta().multiplicative_order()
48
sage: k.zeta(6)
3
sage: k.zeta(5)
Traceback (most recent call last):
...
ValueError: no 5th root of unity in Finite Field in a of size 7^2
Even more examples::
sage: GF(9,'a').zeta_order()
8
sage: GF(9,'a').zeta()
a
sage: GF(9,'a').zeta(4)
a + 1
sage: GF(9,'a').zeta()^2
a + 1
This works even in very large finite fields, provided that ``n``
can be factored (see :trac:`25203`)::
sage: k.<a> = GF(2^2000)
sage: p = 8877945148742945001146041439025147034098690503591013177336356694416517527310181938001
sage: z = k.zeta(p)
sage: z
a^1999 + a^1996 + a^1995 + a^1994 + ... + a^7 + a^5 + a^4 + 1
sage: z ^ p
1
"""
if n is None:
return self.multiplicative_generator()
n = Integer(n)
grouporder = self.order() - 1
co_order = grouporder // n
if co_order * n != grouporder:
raise ValueError("no {}th root of unity in {}".format(n, self))
# If the co_order is small or we know a multiplicative
# generator, use a multiplicative generator
mg = self.multiplicative_generator
if mg.cache is not None or co_order <= 500000:
return mg() ** co_order
return self._element_of_factored_order(n.factor())
@cached_method
def multiplicative_generator(self):
"""
Return a primitive element of this finite field, i.e. a
generator of the multiplicative group.
You can use :meth:`multiplicative_generator()` or
:meth:`primitive_element()`, these mean the same thing.
.. WARNING::
This generator might change from one version of Sage to another.
EXAMPLES::
sage: k = GF(997)
sage: k.multiplicative_generator()
7
sage: k.<a> = GF(11^3)
sage: k.primitive_element()
a
sage: k.<b> = GF(19^32)
sage: k.multiplicative_generator()
b + 4
TESTS:
Check that large characteristics work (:trac:`11946`)::
sage: p = 10^20 + 39
sage: x = polygen(GF(p))
sage: K.<a> = GF(p^2, modulus=x^2+1)
sage: K.multiplicative_generator()
a + 12
"""
if self.degree() == 1:
from sage.arith.all import primitive_root
return self(primitive_root(self.order()))
F, = self.factored_unit_order()
return self._element_of_factored_order(F)
primitive_element = multiplicative_generator
def _element_of_factored_order(self, F):
"""
Return an element of ``self`` of order ``n`` where ``n`` is
given in factored form.
INPUT:
- ``F`` -- the factorization of the required order. The order
must be a divisor of ``self.order() - 1`` but this is not
checked.
EXAMPLES::
sage: k.<a> = GF(16, modulus=cyclotomic_polynomial(5))
sage: k._element_of_factored_order(factor(15))
a^2 + a + 1
sage: k._element_of_factored_order(factor(5))
a^3
sage: k._element_of_factored_order(factor(3))
a^3 + a^2 + 1
sage: k._element_of_factored_order(factor(30))
Traceback (most recent call last):
...
AssertionError: no element found
"""
n = Integer(1)
cdef list primes = []
for p, e in F:
primes.append(p)
n *= p ** e
N = self.order() - 1
c = N // n
# We check whether (x + g)^c has the required order, where
# x runs through the finite field.
# This has the advantage that g is the first element we try,
# so if that was a chosen to be a multiplicative generator,
# we are done immediately. Second, the PARI finite field
# iterator gives all the constant elements first, so we try
# (g+(constant))^c before anything else.
g = self.gen(0)
for x in self:
a = (g + x) ** c
if not a:
continue
if all(a ** (n // p) != 1 for p in primes):
return a
raise AssertionError("no element found")
def ngens(self):
"""
The number of generators of the finite field. Always 1.
EXAMPLES::
sage: k = FiniteField(3^4, 'b')
sage: k.ngens()
1
"""
return 1
def is_field(self, proof = True):
"""
Returns whether or not the finite field is a field, i.e.,
always returns ``True``.
EXAMPLES::
sage: k.<a> = FiniteField(3^4)
sage: k.is_field()
True
"""
return True
def order(self):
"""
Return the order of this finite field.
EXAMPLES::
sage: GF(997).order()
997
"""
return self.characteristic()**self.degree()
# cached because constructing the Factorization is slow;
# see trac #11628.
@cached_method
def factored_order(self):
"""
Returns the factored order of this field. For compatibility with
:mod:`~sage.rings.finite_rings.integer_mod_ring`.
EXAMPLES::
sage: GF(7^2,'a').factored_order()
7^2
"""
from sage.structure.factorization import Factorization
return Factorization([(self.characteristic(), self.degree())])
@cached_method
def factored_unit_order(self):
"""
Returns the factorization of ``self.order()-1``, as a 1-tuple.
The format is for compatibility with
:mod:`~sage.rings.finite_rings.integer_mod_ring`.
EXAMPLES::
sage: GF(7^2,'a').factored_unit_order()
(2^4 * 3,)
"""
F = (self.order() - 1).factor()
return (F,)
def cardinality(self):
"""
Return the cardinality of ``self``.
Same as :meth:`order`.
EXAMPLES::
sage: GF(997).cardinality()
997
"""
return self.order()
__len__ = cardinality
def is_prime_field(self):
"""
Return ``True`` if ``self`` is a prime field, i.e., has degree 1.
EXAMPLES::
sage: GF(3^7, 'a').is_prime_field()
False
sage: GF(3, 'a').is_prime_field()
True
"""
return self.degree()==1
def modulus(self):
r"""
Return the minimal polynomial of the generator of ``self`` over
the prime finite field.
The minimal polynomial of an element `a` in a field is the
unique monic irreducible polynomial of smallest degree with
coefficients in the base field that has `a` as a root. In
finite field extensions, `\GF{p^n}`, the base field is `\GF{p}`.
OUTPUT:
- a monic polynomial over `\GF{p}` in the variable `x`.
EXAMPLES::
sage: F.<a> = GF(7^2); F
Finite Field in a of size 7^2
sage: F.polynomial_ring()
Univariate Polynomial Ring in a over Finite Field of size 7
sage: f = F.modulus(); f
x^2 + 6*x + 3
sage: f(a)
0
Although `f` is irreducible over the base field, we can double-check
whether or not `f` factors in `F` as follows. The command
``F['x'](f)`` coerces `f` as a polynomial with coefficients in `F`.
(Instead of a polynomial with coefficients over the base field.)
::
sage: f.factor()
x^2 + 6*x + 3
sage: F['x'](f).factor()
(x + a + 6) * (x + 6*a)
Here is an example with a degree 3 extension::
sage: G.<b> = GF(7^3); G
Finite Field in b of size 7^3
sage: g = G.modulus(); g
x^3 + 6*x^2 + 4
sage: g.degree(); G.degree()
3
3
For prime fields, this returns `x - 1` unless a custom modulus
was given when constructing this field::
sage: k = GF(199)
sage: k.modulus()
x + 198
sage: var('x')
x
sage: k = GF(199, modulus=x+1)
sage: k.modulus()
x + 1
The given modulus is always made monic::
sage: k.<a> = GF(7^2, modulus=2*x^2-3, impl="pari_ffelt")
sage: k.modulus()
x^2 + 2
TESTS:
We test the various finite field implementations::
sage: GF(2, impl="modn").modulus()
x + 1
sage: GF(2, impl="givaro").modulus()
x + 1
sage: GF(2, impl="ntl").modulus()
x + 1
sage: GF(2, impl="modn", modulus=x).modulus()
x
sage: GF(2, impl="givaro", modulus=x).modulus()
x
sage: GF(2, impl="ntl", modulus=x).modulus()
x
sage: GF(13^2, 'a', impl="givaro", modulus=x^2+2).modulus()
x^2 + 2
sage: GF(13^2, 'a', impl="pari_ffelt", modulus=x^2+2).modulus()
x^2 + 2
"""
# Normally, this is set by the constructor of the implementation
try:
return self._modulus
except AttributeError:
pass
from sage.rings.all import PolynomialRing
from .finite_field_constructor import GF
R = PolynomialRing(GF(self.characteristic()), 'x')
self._modulus = R((-1,1)) # Polynomial x - 1
return self._modulus
def polynomial(self, name=None):
"""
Return the minimal polynomial of the generator of ``self`` over
the prime finite field.
INPUT:
- ``name`` -- a variable name to use for the polynomial. By
default, use the name given when constructing this field.
OUTPUT:
- a monic polynomial over `\GF{p}` in the variable ``name``.
.. SEEALSO::
Except for the ``name`` argument, this is identical to the
:meth:`modulus` method.
EXAMPLES::
sage: k.<a> = FiniteField(9)
sage: k.polynomial('x')
x^2 + 2*x + 2
sage: k.polynomial()
a^2 + 2*a + 2
sage: F = FiniteField(9, 'a', impl='pari_ffelt')
sage: F.polynomial()
a^2 + 2*a + 2
sage: F = FiniteField(7^20, 'a', impl='pari_ffelt')
sage: f = F.polynomial(); f
a^20 + a^12 + 6*a^11 + 2*a^10 + 5*a^9 + 2*a^8 + 3*a^7 + a^6 + 3*a^5 + 3*a^3 + a + 3
sage: f(F.gen())
0
sage: k.<a> = GF(2^20, impl='ntl')
sage: k.polynomial()
a^20 + a^10 + a^9 + a^7 + a^6 + a^5 + a^4 + a + 1
sage: k.polynomial('FOO')
FOO^20 + FOO^10 + FOO^9 + FOO^7 + FOO^6 + FOO^5 + FOO^4 + FOO + 1
sage: a^20
a^10 + a^9 + a^7 + a^6 + a^5 + a^4 + a + 1