-
-
Notifications
You must be signed in to change notification settings - Fork 528
/
Copy pathelement_givaro.pyx
1760 lines (1397 loc) · 52.5 KB
/
element_givaro.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
# distutils: libraries = givaro gmp m
# distutils: language = c++
r"""
Givaro Field Elements
Sage includes the Givaro finite field library, for highly optimized
arithmetic in finite fields.
.. NOTE::
The arithmetic is performed by the Givaro C++ library which uses
Zech logs internally to represent finite field elements. This
implementation is the default finite extension field implementation
in Sage for the cardinality less than `2^{16}`, as it is a lot
faster than the PARI implementation. Some functionality in this
class however is implemented using PARI.
EXAMPLES::
sage: k = GF(5); type(k)
<class 'sage.rings.finite_rings.finite_field_prime_modn.FiniteField_prime_modn_with_category'>
sage: k = GF(5^2,'c'); type(k)
<class 'sage.rings.finite_rings.finite_field_givaro.FiniteField_givaro_with_category'>
sage: k = GF(2^16,'c'); type(k)
<class 'sage.rings.finite_rings.finite_field_ntl_gf2e.FiniteField_ntl_gf2e_with_category'>
sage: k = GF(3^16,'c'); type(k)
<class 'sage.rings.finite_rings.finite_field_pari_ffelt.FiniteField_pari_ffelt_with_category'>
sage: n = previous_prime_power(2^16 - 1)
sage: while is_prime(n):
....: n = previous_prime_power(n)
sage: factor(n)
251^2
sage: k = GF(n,'c'); type(k)
<class 'sage.rings.finite_rings.finite_field_givaro.FiniteField_givaro_with_category'>
AUTHORS:
- Martin Albrecht <malb@informatik.uni-bremen.de> (2006-06-05)
- William Stein (2006-12-07): editing, lots of docs, etc.
- Robert Bradshaw (2007-05-23): is_square/sqrt, pow.
"""
# ****************************************************************************
# Copyright (C) 2006 William Stein <wstein@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
# https://www.gnu.org/licenses/
# ****************************************************************************
from cysignals.signals cimport sig_on, sig_off
from cypari2.paridecl cimport *
from sage.misc.randstate cimport randstate, current_randstate
from sage.rings.finite_rings.finite_field_base cimport FiniteField
from sage.rings.ring cimport Ring
from .element_pari_ffelt cimport FiniteFieldElement_pari_ffelt
from sage.structure.richcmp cimport richcmp
from sage.structure.element cimport Element, ModuleElement, RingElement
import operator
import sage.arith.all
import sage.rings.finite_rings.finite_field_constructor as finite_field
import sage.interfaces.gap
from sage.libs.pari.all import pari
from cypari2.gen cimport Gen
from cypari2.stack cimport clear_stack
from sage.structure.parent cimport Parent
cdef object is_IntegerMod
cdef object Integer
cdef object Rational
cdef object ConwayPolynomials
cdef object conway_polynomial
cdef object MPolynomial
cdef object Polynomial
cdef object FreeModuleElement
cdef void late_import():
"""
Late import of modules
"""
global is_IntegerMod, \
Integer, \
Rational, \
ConwayPolynomials, \
conway_polynomial, \
MPolynomial, \
Polynomial, \
FreeModuleElement
if is_IntegerMod is not None:
return
import sage.rings.finite_rings.integer_mod
is_IntegerMod = sage.rings.finite_rings.integer_mod.is_IntegerMod
import sage.rings.integer
Integer = sage.rings.integer.Integer
import sage.rings.rational
Rational = sage.rings.rational.Rational
import sage.databases.conway
ConwayPolynomials = sage.databases.conway.ConwayPolynomials
import sage.rings.finite_rings.finite_field_constructor
conway_polynomial = sage.rings.finite_rings.conway_polynomials.conway_polynomial
import sage.rings.polynomial.multi_polynomial_element
MPolynomial = sage.rings.polynomial.multi_polynomial_element.MPolynomial
import sage.rings.polynomial.polynomial_element
Polynomial = sage.rings.polynomial.polynomial_element.Polynomial
import sage.modules.free_module_element
FreeModuleElement = sage.modules.free_module_element.FreeModuleElement
cdef class Cache_givaro(Cache_base):
def __init__(self, parent, unsigned int p, unsigned int k, modulus, repr="poly", cache=False):
"""
Finite Field.
These are implemented using Zech logs and the
cardinality must be less than `2^{16}`. By default Conway polynomials
are used as minimal polynomial.
INPUT:
- ``q`` -- `p^n` (must be prime power)
- ``name`` -- variable used for poly_repr (default: ``'a'``)
- ``modulus`` -- a polynomial to use as modulus.
- ``repr`` -- (default: 'poly') controls the way elements are printed
to the user:
- 'log': repr is :meth:`~FiniteField_givaroElement.log_repr()`
- 'int': repr is :meth:`~FiniteField_givaroElement.int_repr()`
- 'poly': repr is :meth:`~FiniteField_givaroElement.poly_repr()`
- ``cache`` -- (default: ``False``) if ``True`` a cache of all
elements of this field is created. Thus, arithmetic does not
create new elements which speeds calculations up. Also, if many
elements are needed during a calculation this cache reduces the
memory requirement as at most :meth:`order()` elements are created.
OUTPUT:
Givaro finite field with characteristic `p` and cardinality `p^n`.
EXAMPLES:
By default Conway polynomials are used::
sage: k.<a> = GF(2**8)
sage: -a ^ k.degree()
a^4 + a^3 + a^2 + 1
sage: f = k.modulus(); f
x^8 + x^4 + x^3 + x^2 + 1
You may enforce a modulus::
sage: P.<x> = PolynomialRing(GF(2))
sage: f = x^8 + x^4 + x^3 + x + 1 # Rijndael polynomial
sage: k.<a> = GF(2^8, modulus=f)
sage: k.modulus()
x^8 + x^4 + x^3 + x + 1
sage: a^(2^8)
a
You may enforce a random modulus::
sage: k = GF(3**5, 'a', modulus='random')
sage: k.modulus() # random polynomial
x^5 + 2*x^4 + 2*x^3 + x^2 + 2
For binary fields, you may ask for a minimal weight polynomial::
sage: k = GF(2**10, 'a', modulus='minimal_weight')
sage: k.modulus()
x^10 + x^3 + 1
"""
# we are calling late_import here because this constructor is
# called at least once before any arithmetic is performed.
late_import()
cdef intvec cPoly
self.parent = <Parent?> parent
if repr=='poly':
self.repr = 0
elif repr=='log':
self.repr = 1
elif repr=='int':
self.repr = 2
else:
raise RuntimeError
if k == 1:
sig_on()
self.objectptr = gfq_factorypk(p, k)
else:
# Givaro does not support this when k == 1
for coeff in modulus:
cPoly.push_back(<int>coeff)
sig_on()
self.objectptr = gfq_factorypkp(p, k, cPoly)
self._zero_element = make_FiniteField_givaroElement(self, self.objectptr.zero)
self._one_element = make_FiniteField_givaroElement(self, self.objectptr.one)
sig_off()
parent._zero_element = self._zero_element
parent._one_element = self._one_element
if cache:
self._array = self.gen_array()
self._has_array = True
cdef gen_array(self):
"""
Generates an array/list/tuple containing all elements of ``self``
indexed by their power with respect to the internal generator.
"""
cdef int i
array = list()
for i in range(self.order_c()):
array.append(make_FiniteField_givaroElement(self, i))
return tuple(array)
def __dealloc__(self):
"""
Free the memory occupied by this Givaro finite field.
"""
delete(self.objectptr)
cpdef int characteristic(self):
"""
Return the characteristic of this field.
EXAMPLES::
sage: p = GF(19^3,'a')._cache.characteristic(); p
19
"""
return self.objectptr.characteristic()
def order(self):
"""
Return the order of this field.
EXAMPLES::
sage: K.<a> = GF(9)
sage: K._cache.order()
9
"""
return Integer(self.order_c())
cpdef int order_c(self):
"""
Return the order of this field.
EXAMPLES::
sage: K.<a> = GF(9)
sage: K._cache.order_c()
9
"""
return self.objectptr.cardinality()
cpdef int exponent(self):
r"""
Return the degree of this field over `\GF{p}`.
EXAMPLES::
sage: K.<a> = GF(9); K._cache.exponent()
2
"""
return self.objectptr.exponent()
def random_element(self, *args, **kwds):
"""
Return a random element of ``self``.
EXAMPLES::
sage: k = GF(23**3, 'a')
sage: e = k._cache.random_element()
sage: e.parent() is k
True
sage: type(e)
<class 'sage.rings.finite_rings.element_givaro.FiniteField_givaroElement'>
sage: P.<x> = PowerSeriesRing(GF(3^3, 'a'))
sage: P.random_element(5).parent() is P
True
"""
cdef int seed = current_randstate().c_random()
cdef int res
cdef GivRandom generator = GivRandomSeeded(seed)
self.objectptr.random(generator, res)
return make_FiniteField_givaroElement(self, res)
cpdef FiniteField_givaroElement element_from_data(self, e):
"""
Coerces several data types to ``self``.
INPUT:
- ``e`` -- data to coerce in.
EXAMPLES::
sage: k = GF(3^8, 'a')
sage: type(k)
<class 'sage.rings.finite_rings.finite_field_givaro.FiniteField_givaro_with_category'>
sage: e = k.vector_space(map=False).gen(1); e
(0, 1, 0, 0, 0, 0, 0, 0)
sage: k(e) #indirect doctest
a
TESTS:
Check coercion of large integers::
sage: k(-5^13)
1
sage: k(2^31)
2
sage: k(int(10^19))
1
sage: k(2^63)
2
sage: k(2^100)
1
sage: k(int(2^100))
1
sage: k(-2^100)
2
Check coercion of incompatible fields::
sage: x=GF(7).random_element()
sage: k(x)
Traceback (most recent call last):
...
TypeError: unable to coerce from a finite field other than the prime subfield
For more examples, see
``finite_field_givaro.FiniteField_givaro._element_constructor_``
"""
cdef int res
cdef int g
cdef int x
cdef int e_int
cdef FiniteField_givaroElement to_add
########
if isinstance(e, FiniteField_givaroElement):
if e.parent() is self.parent:
return e
if e.parent() == self.parent:
return make_FiniteField_givaroElement(self, (<FiniteField_givaroElement>e).element)
if e.parent() is self.parent.prime_subfield() or e.parent() == self.parent.prime_subfield():
res = self.int_to_log(int(e))
else:
raise TypeError("unable to coerce from a finite field other than the prime subfield")
elif isinstance(e, (int, Integer, long)) or is_IntegerMod(e):
try:
e_int = e % self.characteristic()
self.objectptr.initi(res, e_int)
except ArithmeticError:
raise TypeError("unable to coerce from a finite field other than the prime subfield")
elif e is None:
e_int = 0
self.objectptr.initi(res, e_int)
elif isinstance(e, float):
e_int = int(e) % self.characteristic()
self.objectptr.initd(res, e_int)
elif isinstance(e, str):
return self.parent(eval(e.replace("^", "**"),
self.parent.gens_dict()))
elif isinstance(e, FreeModuleElement):
if self.parent.vector_space(map=False) != e.parent():
raise TypeError("e.parent must match self.vector_space")
ret = self._zero_element
for i in range(len(e)):
e_int = e[i] % self.characteristic()
self.objectptr.initi(res, e_int)
to_add = make_FiniteField_givaroElement(self, res)
ret = ret + to_add * self.parent.gen()**i
return ret
elif isinstance(e, MPolynomial):
if e.is_constant():
return self.parent(e.constant_coefficient())
else:
raise TypeError("no coercion defined")
elif isinstance(e, Polynomial):
if e.is_constant():
return self.parent(e.constant_coefficient())
else:
return e.change_ring(self.parent)(self.parent.gen())
elif isinstance(e, Rational):
num = e.numer()
den = e.denom()
return self.parent(num) / self.parent(den)
elif isinstance(e, Gen):
pass # handle this in next if clause
elif isinstance(e, FiniteFieldElement_pari_ffelt):
# Reduce to pari
e = e.__pari__()
elif sage.interfaces.gap.is_GapElement(e):
from sage.interfaces.gap import gfq_gap_to_sage
return gfq_gap_to_sage(e, self.parent)
elif isinstance(e, list):
if len(e) > self.exponent():
# could reduce here...
raise ValueError("list is too long")
ret = self._zero_element
for i in range(len(e)):
e_int = e[i] % self.characteristic()
self.objectptr.initi(res, e_int)
to_add = make_FiniteField_givaroElement(self, res)
ret = ret + to_add * self.parent.gen()**i
return ret
else:
raise TypeError("unable to coerce %r" % type(e))
cdef GEN t
cdef long c
if isinstance(e, Gen):
sig_on()
t = (<Gen>e).g
if typ(t) == t_FFELT:
t = FF_to_FpXQ(t)
else:
t = liftall_shallow(t)
if typ(t) == t_INT:
res = self.int_to_log(itos(t))
clear_stack()
elif typ(t) == t_POL:
res = self._zero_element
g = self.objectptr.indeterminate()
x = self.objectptr.one
for i in range(degpol(t) + 1):
c = gtolong(gel(t, i + 2))
self.objectptr.axpyin(res, self.int_to_log(c), x)
self.objectptr.mulin(x, g)
clear_stack()
else:
clear_stack()
raise TypeError(f"unable to convert PARI {e.type()} to {self.parent}")
return make_FiniteField_givaroElement(self, res)
cpdef FiniteField_givaroElement gen(self):
"""
Return a generator of the field.
EXAMPLES::
sage: K.<a> = GF(625)
sage: K._cache.gen()
a
"""
cdef int g
if self.objectptr.exponent() == 1:
self.objectptr.initi(g, -self.parent.modulus()[0])
else:
g = self.objectptr.indeterminate()
return make_FiniteField_givaroElement(self, g)
cpdef int log_to_int(self, int n) except -1:
r"""
Given an integer `n` this method returns `i` where `i`
satisfies `g^n = i` where `g` is the generator of ``self``; the
result is interpreted as an integer.
INPUT:
- ``n`` -- log representation of a finite field element
OUTPUT:
integer representation of a finite field element.
EXAMPLES::
sage: k = GF(2**8, 'a')
sage: k._cache.log_to_int(4)
16
sage: k._cache.log_to_int(20)
180
"""
if n < 0:
raise IndexError("Cannot serve negative exponent %d" % n)
elif n >= self.order_c():
raise IndexError("n=%d must be < self.order()" % n)
cdef int r
sig_on()
self.objectptr.convert(r, n)
sig_off()
return r
cpdef int int_to_log(self, int n) except -1:
r"""
Given an integer `n` this method returns `i` where `i` satisfies
`g^i = n \mod p` where `g` is the generator and `p` is the
characteristic of ``self``.
INPUT:
- ``n`` -- integer representation of an finite field element
OUTPUT:
log representation of ``n``
EXAMPLES::
sage: k = GF(7**3, 'a')
sage: k._cache.int_to_log(4)
228
sage: k._cache.int_to_log(3)
57
sage: k.gen()^57
3
"""
cdef int r
sig_on()
self.objectptr.initi(r, n)
sig_off()
return r
cpdef FiniteField_givaroElement fetch_int(self, number):
r"""
Given an integer ``n`` return a finite field element in ``self``
which equals ``n`` under the condition that :meth:`gen()` is set to
:meth:`characteristic()`.
EXAMPLES::
sage: k.<a> = GF(2^8)
sage: k._cache.fetch_int(8)
a^3
sage: e = k._cache.fetch_int(151); e
a^7 + a^4 + a^2 + a + 1
sage: 2^7 + 2^4 + 2^2 + 2 + 1
151
"""
cdef int n = number
if n < 0 or n > self.order_c():
raise TypeError("n must be between 0 and self.order()")
cdef int ret = self.int_to_log(n)
return make_FiniteField_givaroElement(self, ret)
def _element_repr(self, FiniteField_givaroElement e):
"""
Wrapper for log, int, and poly representations.
EXAMPLES::
sage: k.<a> = GF(3^4); k
Finite Field in a of size 3^4
sage: k._cache._element_repr(a^20)
'2*a^3 + 2*a^2 + 2'
sage: k = FiniteField(3^4,'a', impl='givaro', repr='int')
sage: a = k.gen()
sage: k._cache._element_repr(a^20)
'74'
sage: k = FiniteField(3^4,'a', impl='givaro', repr='log')
sage: a = k.gen()
sage: k._cache._element_repr(a^20)
'20'
"""
if self.repr==0:
return self._element_poly_repr(e)
elif self.repr==1:
return self._element_log_repr(e)
else:
return self._element_int_repr(e)
def _element_log_repr(self, FiniteField_givaroElement e):
"""
Return ``str(i)`` where ``self`` is ``gen^i`` with ``gen``
being the *internal* multiplicative generator of this finite
field.
EXAMPLES::
sage: k.<a> = GF(3^4); k
Finite Field in a of size 3^4
sage: k._cache._element_log_repr(a^20)
'20'
sage: k._cache._element_log_repr(a)
'1'
"""
return str(int(e.element))
def _element_int_repr(self, FiniteField_givaroElement e):
r"""
Return integer representation of ``e``.
Elements of this field are represented as ints in as follows:
for `e \in \GF{p}[x]` with `e = a_0 + a_1x + a_2x^2 + \cdots`, `e` is
represented as: `n = a_0 + a_1 p + a_2 p^2 + \cdots`.
EXAMPLES::
sage: k.<a> = GF(3^4); k
Finite Field in a of size 3^4
sage: k._cache._element_int_repr(a^20)
'74'
"""
return str(e.integer_representation())
def _element_poly_repr(self, FiniteField_givaroElement e, varname=None):
"""
Return a polynomial expression in the generator of ``self``.
EXAMPLES::
sage: k.<a> = GF(3^4); k
Finite Field in a of size 3^4
sage: k._cache._element_poly_repr(a^20)
'2*a^3 + 2*a^2 + 2'
"""
if varname is None:
variable = self.parent.variable_name()
else:
variable = varname
quo = self.log_to_int(e.element)
b = int(self.characteristic())
ret = ""
for i in range(self.exponent()):
coeff = quo % b
if coeff != 0:
if i > 0:
if coeff == 1:
coeff = ""
else:
coeff = str(coeff) + "*"
if i > 1:
ret = coeff + variable + "^" + str(i) + " + " + ret
else:
ret = coeff + variable + " + " + ret
else:
ret = str(coeff) + " + " + ret
quo = quo // b
if ret == '':
return "0"
return ret[:-3]
def a_times_b_plus_c(self, FiniteField_givaroElement a,
FiniteField_givaroElement b,
FiniteField_givaroElement c):
"""
Return ``a*b + c``.
This is faster than multiplying ``a`` and ``b``
first and adding ``c`` to the result.
INPUT:
- ``a,b,c`` -- :class:`FiniteField_givaroElement`
EXAMPLES::
sage: k.<a> = GF(2**8)
sage: k._cache.a_times_b_plus_c(a,a,k(1))
a^2 + 1
"""
cdef int r
self.objectptr.axpy(r, a.element, b.element, c.element)
return make_FiniteField_givaroElement(self, r)
def a_times_b_minus_c(self, FiniteField_givaroElement a,
FiniteField_givaroElement b,
FiniteField_givaroElement c):
"""
Return ``a*b - c``.
INPUT:
- ``a,b,c`` -- :class:`FiniteField_givaroElement`
EXAMPLES::
sage: k.<a> = GF(3**3)
sage: k._cache.a_times_b_minus_c(a,a,k(1))
a^2 + 2
"""
cdef int r
self.objectptr.axmy(r, a.element, b.element, c.element, )
return make_FiniteField_givaroElement(self, r)
def c_minus_a_times_b(self, FiniteField_givaroElement a,
FiniteField_givaroElement b,
FiniteField_givaroElement c):
"""
Return ``c - a*b``.
INPUT:
- ``a,b,c`` -- :class:`FiniteField_givaroElement`
EXAMPLES::
sage: k.<a> = GF(3**3)
sage: k._cache.c_minus_a_times_b(a,a,k(1))
2*a^2 + 1
"""
cdef int r
self.objectptr.maxpy(r, a.element, b.element, c.element,)
return make_FiniteField_givaroElement(self, r)
def __reduce__(self):
"""
For pickling.
TESTS::
sage: k.<a> = GF(3^8)
sage: TestSuite(a).run()
"""
p, k = self.order().factor()[0]
if self.repr == 0:
rep = 'poly'
elif self.repr == 1:
rep = 'log'
elif self.repr == 2:
rep = 'int'
return unpickle_Cache_givaro, (self.parent, p, k, self.parent.polynomial(), rep, self._has_array)
cdef FiniteField_givaroElement _new_c(self, int value):
return make_FiniteField_givaroElement(self, value)
def unpickle_Cache_givaro(parent, p, k, modulus, rep, cache):
"""
EXAMPLES::
sage: k = GF(3**7, 'a')
sage: loads(dumps(k)) == k # indirect doctest
True
"""
return Cache_givaro(parent, p, k, modulus, rep, cache)
cdef class FiniteField_givaro_iterator:
"""
Iterator over :class:`FiniteField_givaro` elements. We iterate
multiplicatively, as powers of a fixed internal generator.
EXAMPLES::
sage: for x in GF(2^2,'a'): print(x)
0
a
a + 1
1
"""
def __init__(self, Cache_givaro cache):
"""
EXAMPLES::
sage: k.<a> = GF(3^4)
sage: i = iter(k) # indirect doctest
sage: i
Iterator over Finite Field in a of size 3^4
"""
self._cache = cache
self.iterator = -1
def __next__(self):
"""
EXAMPLES::
sage: k.<a> = GF(3^4)
sage: i = iter(k) # indirect doctest
sage: next(i)
0
sage: next(i)
a
"""
self.iterator += 1
if self.iterator == self._cache.order_c():
self.iterator = -1
raise StopIteration
return make_FiniteField_givaroElement(self._cache, self.iterator)
def __repr__(self):
"""
EXAMPLES::
sage: k.<a> = GF(3^4)
sage: i = iter(k)
sage: i # indirect doctest
Iterator over Finite Field in a of size 3^4
"""
return "Iterator over %s" % self._cache.parent
def __iter__(self):
"""
EXAMPLES::
sage: K.<a> = GF(4)
sage: K.list() # indirect doctest
[0, a, a + 1, 1]
"""
return self
cdef class FiniteField_givaroElement(FinitePolyExtElement):
"""
An element of a (Givaro) finite field.
"""
def __init__(FiniteField_givaroElement self, parent):
"""
Initializes an element in parent. It's much better to use
parent(<value>) or any specialized method of parent
like gen() instead. In general do not call this
constructor directly.
Alternatively you may provide a value which is directly
assigned to this element. So the value must represent the
log_g of the value you wish to assign.
INPUT:
- ``parent`` -- base field
OUTPUT:
A finite field element.
EXAMPLES::
sage: k.<a> = GF(5^2)
sage: from sage.rings.finite_rings.element_givaro import FiniteField_givaroElement
sage: FiniteField_givaroElement(k)
0
"""
FinitePolyExtElement.__init__(self, parent)
self._cache = parent._cache
self.element = 0
cdef FiniteField_givaroElement _new_c(self, int value):
return make_FiniteField_givaroElement(self._cache, value)
def __dealloc__(FiniteField_givaroElement self):
pass
def _repr_(FiniteField_givaroElement self):
"""
EXAMPLES::
sage: k.<FOOBAR> = GF(3^4)
sage: FOOBAR #indirect doctest
FOOBAR
sage: k.<FOOBAR> = GF(3^4, repr='log')
sage: FOOBAR
1
sage: k.<FOOBAR> = GF(3^4, repr='int')
sage: FOOBAR
3
"""
return self._cache._element_repr(self)
def _element(self):
"""
Return the int internally representing this element.
EXAMPLES::
sage: k.<a> = GF(3^4)
sage: (a^2 + 1)._element()
58
"""
return self.element
def __nonzero__(FiniteField_givaroElement self):
r"""
Return ``True`` if ``self != k(0)``.
EXAMPLES::
sage: k.<a> = GF(3^4); k
Finite Field in a of size 3^4
sage: a.is_zero()
False
sage: k(0).is_zero()
True
"""
return not self._cache.objectptr.isZero(self.element)
def is_one(FiniteField_givaroElement self):
r"""
Return ``True`` if ``self == k(1)``.
EXAMPLES::
sage: k.<a> = GF(3^4); k
Finite Field in a of size 3^4
sage: a.is_one()
False
sage: k(1).is_one()
True
"""
return self._cache.objectptr.isOne(self.element)
def is_unit(FiniteField_givaroElement self):
"""
Return ``True`` if self is nonzero, so it is a unit as an element of
the finite field.
EXAMPLES::
sage: k.<a> = GF(3^4); k
Finite Field in a of size 3^4
sage: a.is_unit()
True
sage: k(0).is_unit()
False
"""
return not (<Cache_givaro>self._cache).objectptr.isZero(self.element)
# **WARNING** Givaro seems to define unit to mean in the prime field,
# which is totally wrong! It's a confusion with the underlying polynomial
# representation maybe?? That's why the following is commented out.
# return (<FiniteField_givaro>self._parent).objectptr.isunit(self.element)
def is_square(FiniteField_givaroElement self):
"""
Return ``True`` if ``self`` is a square in ``self.parent()``
ALGORITHM:
Elements are stored as powers of generators, so we simply check
to see if it is an even power of a generator.
EXAMPLES::
sage: k.<a> = GF(9); k
Finite Field in a of size 3^2
sage: a.is_square()
False
sage: v = set([x^2 for x in k])
sage: [x.is_square() for x in v]
[True, True, True, True, True]
sage: [x.is_square() for x in k if not x in v]
[False, False, False, False]
TESTS::
sage: K = GF(27, 'a')
sage: set([a*a for a in K]) == set([a for a in K if a.is_square()])
True