Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemath
GitHub Repository: sagemath/sagesmc
Path: blob/master/src/sage/rings/finite_rings/integer_mod_ring.py
8820 views
1
r"""
2
Ring `\ZZ/n\ZZ` of integers modulo `n`
3
4
EXAMPLES::
5
6
sage: R = Integers(97)
7
sage: a = R(5)
8
sage: a**100000000000000000000000000000000000000000000000000000000000000
9
61
10
11
This example illustrates the relation between
12
`\ZZ/p\ZZ` and `\GF{p}`. In
13
particular, there is a canonical map to `\GF{p}`, but not in
14
the other direction.
15
16
::
17
18
sage: r = Integers(7)
19
sage: s = GF(7)
20
sage: r.has_coerce_map_from(s)
21
False
22
sage: s.has_coerce_map_from(r)
23
True
24
sage: s(1) + r(1)
25
2
26
sage: parent(s(1) + r(1))
27
Finite Field of size 7
28
sage: parent(r(1) + s(1))
29
Finite Field of size 7
30
31
We list the elements of `\ZZ/3\ZZ`::
32
33
sage: R = Integers(3)
34
sage: list(R)
35
[0, 1, 2]
36
37
AUTHORS:
38
39
- William Stein (initial code)
40
41
- David Joyner (2005-12-22): most examples
42
43
- Robert Bradshaw (2006-08-24): convert to SageX (Cython)
44
45
- William Stein (2007-04-29): square_roots_of_one
46
47
- Simon King (2011-04-21): allow to prescribe a category
48
"""
49
50
#*****************************************************************************
51
#
52
# Sage: System for Algebra and Geometry Experimentation
53
#
54
# Copyright (C) 2005 William Stein <[email protected]>
55
#
56
# Distributed under the terms of the GNU General Public License (GPL)
57
#
58
# This code is distributed in the hope that it will be useful,
59
# but WITHOUT ANY WARRANTY; without even the implied warranty of
60
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
61
# General Public License for more details.
62
#
63
# The full text of the GPL is available at:
64
#
65
# http://www.gnu.org/licenses/
66
#*****************************************************************************
67
68
import sage.misc.prandom as random
69
70
from sage.rings.arith import is_prime, factor, CRT_basis, LCM, prime_divisors, euler_phi
71
import sage.rings.commutative_ring as commutative_ring
72
import sage.rings.field as field
73
import integer_mod
74
import sage.rings.integer as integer
75
import sage.rings.integer_ring as integer_ring
76
import sage.rings.quotient_ring as quotient_ring
77
from sage.structure.parent_gens import ParentWithGens
78
79
from sage.libs.pari.all import pari, PariError
80
81
import sage.interfaces.all
82
from sage.misc.cachefunc import cached_method
83
84
from sage.structure.factory import UniqueFactory
85
86
class IntegerModFactory(UniqueFactory):
87
r"""
88
Return the quotient ring `\ZZ / n\ZZ`.
89
90
INPUT:
91
92
- ``order`` -- integer (default: 0), positive or negative
93
94
EXAMPLES::
95
96
sage: IntegerModRing(15)
97
Ring of integers modulo 15
98
sage: IntegerModRing(7)
99
Ring of integers modulo 7
100
sage: IntegerModRing(-100)
101
Ring of integers modulo 100
102
103
Note that you can also use ``Integers``, which is a
104
synonym for ``IntegerModRing``.
105
106
::
107
108
sage: Integers(18)
109
Ring of integers modulo 18
110
sage: Integers() is Integers(0) is ZZ
111
True
112
"""
113
def create_key(self, order=0, category=None):
114
"""
115
An integer mod ring is specified uniquely by its order.
116
117
EXAMPLES::
118
119
sage: Zmod.create_key(7)
120
7
121
sage: Zmod.create_key(7, Fields())
122
(7, Category of fields)
123
"""
124
if category is None:
125
return order
126
return (order, category)
127
128
def create_object(self, version, order):
129
"""
130
EXAMPLES::
131
132
sage: R = Integers(10)
133
sage: TestSuite(R).run() # indirect doctest
134
"""
135
category=None
136
if isinstance(order, tuple):
137
order, category = order
138
if order < 0:
139
order = -order
140
if order == 0:
141
return integer_ring.IntegerRing()
142
else:
143
return IntegerModRing_generic(order,category=category)
144
145
Zmod = Integers = IntegerModRing = IntegerModFactory("IntegerModRing")
146
147
148
def is_IntegerModRing(x):
149
"""
150
Return ``True`` if ``x`` is an integer modulo ring.
151
152
EXAMPLES::
153
154
sage: from sage.rings.finite_rings.integer_mod_ring import is_IntegerModRing
155
sage: R = IntegerModRing(17)
156
sage: is_IntegerModRing(R)
157
True
158
sage: is_IntegerModRing(GF(13))
159
True
160
sage: is_IntegerModRing(GF(4, 'a'))
161
False
162
sage: is_IntegerModRing(10)
163
False
164
sage: is_IntegerModRing(ZZ)
165
False
166
"""
167
return isinstance(x, IntegerModRing_generic)
168
169
from sage.categories.commutative_rings import CommutativeRings
170
from sage.categories.finite_enumerated_sets import FiniteEnumeratedSets
171
from sage.categories.category import JoinCategory
172
default_category = JoinCategory((CommutativeRings(), FiniteEnumeratedSets()))
173
ZZ = integer_ring.IntegerRing()
174
175
class IntegerModRing_generic(quotient_ring.QuotientRing_generic):
176
"""
177
The ring of integers modulo `N`, with `N` composite.
178
179
INPUT:
180
181
- ``order`` -- an integer
182
183
- ``category`` -- a subcategory of ``CommutativeRings()`` (the default)
184
(currently only available for subclasses)
185
186
OUTPUT:
187
188
The ring of integers modulo `N`.
189
190
EXAMPLES:
191
192
First we compute with integers modulo `29`.
193
194
::
195
196
sage: FF = IntegerModRing(29)
197
sage: FF
198
Ring of integers modulo 29
199
sage: FF.category()
200
Join of Category of commutative rings and Category of subquotients of monoids and Category of quotients of semigroups and Category of finite enumerated sets
201
sage: FF.is_field()
202
True
203
sage: FF.characteristic()
204
29
205
sage: FF.order()
206
29
207
sage: gens = FF.unit_gens()
208
sage: a = gens[0]
209
sage: a
210
2
211
sage: a.is_square()
212
False
213
sage: def pow(i): return a**i
214
sage: [pow(i) for i in range(16)]
215
[1, 2, 4, 8, 16, 3, 6, 12, 24, 19, 9, 18, 7, 14, 28, 27]
216
217
We have seen above that an integer mod ring is, by default, not
218
initialised as an object in the category of fields. However, one
219
can force it to be. Moreover, testing containment in the category
220
of fields my re-initialise the category of the integer mod ring::
221
222
sage: F19 = IntegerModRing(19, category = Fields())
223
sage: F19.category().is_subcategory(Fields())
224
True
225
sage: F23 = IntegerModRing(23)
226
sage: F23.category().is_subcategory(Fields())
227
False
228
sage: F23 in Fields()
229
True
230
sage: F23.category().is_subcategory(Fields())
231
True
232
233
234
Next we compute with the integers modulo `16`.
235
236
::
237
238
sage: Z16 = IntegerModRing(16)
239
sage: Z16.category()
240
Join of Category of commutative rings and Category of subquotients of monoids and Category of quotients of semigroups and Category of finite enumerated sets
241
sage: Z16.is_field()
242
False
243
sage: Z16.order()
244
16
245
sage: Z16.characteristic()
246
16
247
sage: gens = Z16.unit_gens()
248
sage: gens
249
(15, 5)
250
sage: a = gens[0]
251
sage: b = gens[1]
252
sage: def powa(i): return a**i
253
sage: def powb(i): return b**i
254
sage: gp_exp = FF.unit_group_exponent()
255
sage: gp_exp
256
28
257
sage: [powa(i) for i in range(15)]
258
[1, 15, 1, 15, 1, 15, 1, 15, 1, 15, 1, 15, 1, 15, 1]
259
sage: [powb(i) for i in range(15)]
260
[1, 5, 9, 13, 1, 5, 9, 13, 1, 5, 9, 13, 1, 5, 9]
261
sage: a.multiplicative_order()
262
2
263
sage: b.multiplicative_order()
264
4
265
266
Testing ideals and quotients::
267
268
sage: Z10 = Integers(10)
269
sage: I = Z10.principal_ideal(0)
270
sage: Z10.quotient(I) == Z10
271
True
272
sage: I = Z10.principal_ideal(2)
273
sage: Z10.quotient(I) == Z10
274
False
275
sage: I.is_prime()
276
True
277
278
::
279
280
sage: R = IntegerModRing(97)
281
sage: a = R(5)
282
sage: a**(10^62)
283
61
284
"""
285
def __init__(self, order, cache=None, category=None):
286
"""
287
Create with the command ``IntegerModRing(order)``.
288
289
TESTS::
290
291
sage: FF = IntegerModRing(29)
292
sage: TestSuite(FF).run()
293
sage: F19 = IntegerModRing(19, category = Fields())
294
sage: TestSuite(F19).run()
295
sage: F23 = IntegerModRing(23)
296
sage: F23 in Fields()
297
True
298
sage: TestSuite(F23).run()
299
sage: Z16 = IntegerModRing(16)
300
sage: TestSuite(Z16).run()
301
sage: R = Integers(100000)
302
sage: TestSuite(R).run() # long time (17s on sage.math, 2011)
303
"""
304
order = ZZ(order)
305
if order <= 0:
306
raise ZeroDivisionError("order must be positive")
307
self.__order = order
308
self._pyx_order = integer_mod.NativeIntStruct(order)
309
if category is None:
310
from sage.categories.commutative_rings import CommutativeRings
311
from sage.categories.finite_enumerated_sets import FiniteEnumeratedSets
312
from sage.categories.category import Category
313
category = Category.join([CommutativeRings(), FiniteEnumeratedSets()])
314
# category = default_category
315
# If the category is given then we trust that is it right.
316
# Give the generator a 'name' to make quotients work. The
317
# name 'x' is used because it's also used for the ring of
318
# integers: see the __init__ method for IntegerRing_class in
319
# sage/rings/integer_ring.pyx.
320
quotient_ring.QuotientRing_generic.__init__(self, ZZ, ZZ.ideal(order),
321
names=('x',),
322
category=category)
323
# Calling ParentWithGens is not needed, the job is done in
324
# the quotient ring initialisation.
325
#ParentWithGens.__init__(self, self, category = category)
326
# We want that the ring is its own base ring.
327
self._base = self
328
if cache is None:
329
cache = order < 500
330
if cache:
331
self._precompute_table()
332
self._zero_element = integer_mod.IntegerMod(self, 0)
333
self._one_element = integer_mod.IntegerMod(self, 1)
334
335
def _macaulay2_init_(self):
336
"""
337
EXAMPLES::
338
339
sage: macaulay2(Integers(7)) # optional - macaulay2
340
ZZ
341
--
342
7
343
344
::
345
346
sage: macaulay2(Integers(10)) # optional - macaulay2
347
Traceback (most recent call last):
348
...
349
TypeError: Error evaluating Macaulay2 code.
350
IN:sage1=ZZ/10;
351
OUT:...error: ZZ/n not implemented yet for composite n
352
"""
353
return "ZZ/{}".format(self.order())
354
355
def _axiom_init_(self):
356
"""
357
Returns a string representation of self in (Pan)Axiom.
358
359
EXAMPLES::
360
361
sage: Z7 = Integers(7)
362
sage: Z7._axiom_init_()
363
'IntegerMod(7)'
364
365
sage: axiom(Z7) #optional - axiom
366
IntegerMod 7
367
368
sage: fricas(Z7) #optional - fricas
369
IntegerMod(7)
370
"""
371
return 'IntegerMod({})'.format(self.order())
372
373
_fricas_init_ = _axiom_init_
374
375
def krull_dimension(self):
376
"""
377
Return the Krull dimension of ``self``.
378
379
EXAMPLES::
380
381
sage: Integers(18).krull_dimension()
382
0
383
"""
384
return integer.Integer(0)
385
386
def is_noetherian(self):
387
"""
388
Check if ``self`` is a Noetherian ring.
389
390
EXAMPLES::
391
392
sage: Integers(8).is_noetherian()
393
True
394
"""
395
return True
396
397
def extension(self, poly, name=None, names=None, embedding=None):
398
"""
399
Return an algebraic extension of ``self``. See
400
:meth:`sage.rings.ring.CommutativeRing.extension()` for more
401
information.
402
403
EXAMPLES::
404
405
sage: R.<t> = QQ[]
406
sage: Integers(8).extension(t^2 - 3)
407
Univariate Quotient Polynomial Ring in t over Ring of integers modulo 8 with modulus t^2 + 5
408
"""
409
if self.modulus() == 1:
410
return self
411
412
from sage.rings.ring import CommutativeRing
413
return CommutativeRing.extension(self, poly, name, names, embedding)
414
415
@cached_method
416
def is_prime_field(self):
417
"""
418
Return ``True`` if the order is prime.
419
420
EXAMPLES::
421
422
sage: Zmod(7).is_prime_field()
423
True
424
sage: Zmod(8).is_prime_field()
425
False
426
"""
427
return self.__order.is_prime()
428
429
def _precompute_table(self):
430
"""
431
Computes a table of elements so that elements are unique.
432
433
EXAMPLES::
434
435
sage: R = Zmod(500); R._precompute_table()
436
sage: R(7) + R(13) is R(3) + R(17)
437
True
438
"""
439
self._pyx_order.precompute_table(self)
440
441
def list_of_elements_of_multiplicative_group(self):
442
"""
443
Return a list of all invertible elements, as python ints.
444
445
EXAMPLES::
446
447
sage: R = Zmod(12)
448
sage: L = R.list_of_elements_of_multiplicative_group(); L
449
[1, 5, 7, 11]
450
sage: type(L[0])
451
<type 'int'>
452
"""
453
import sage.rings.fast_arith as a
454
if self.__order <= 46340: # todo: don't hard code
455
gcd = a.arith_int().gcd_int
456
elif self.__order <= 2147483647: # todo: don't hard code
457
gcd = a.arith_llong().gcd_longlong
458
else:
459
raise MemoryError("creating the list would exhaust memory")
460
N = self.__order
461
H = [i for i in range(N) if gcd(i, N) == 1]
462
return H
463
464
@cached_method
465
def multiplicative_subgroups(self):
466
r"""
467
Return generators for each subgroup of
468
`(\ZZ/N\ZZ)^*`.
469
470
EXAMPLES::
471
472
sage: Integers(5).multiplicative_subgroups()
473
((2,), (4,), ())
474
sage: Integers(15).multiplicative_subgroups()
475
((11, 7), (4, 11), (8,), (11,), (14,), (7,), (4,), ())
476
sage: Integers(2).multiplicative_subgroups()
477
((),)
478
sage: len(Integers(341).multiplicative_subgroups())
479
80
480
481
TESTS::
482
483
sage: IntegerModRing(1).multiplicative_subgroups()
484
((0,),)
485
sage: IntegerModRing(2).multiplicative_subgroups()
486
((),)
487
sage: IntegerModRing(3).multiplicative_subgroups()
488
((2,), ())
489
"""
490
from sage.groups.abelian_gps.values import AbelianGroupWithValues
491
U = self.unit_gens()
492
G = AbelianGroupWithValues(U, [x.multiplicative_order() for x in U], values_group=self)
493
mysubs = []
494
for Gsub in G.subgroups():
495
mysubs.append(tuple( g.value() for g in Gsub.gens() ))
496
return tuple(mysubs)
497
498
def is_finite(self):
499
"""
500
Return ``True`` since `\ZZ/N\ZZ` is finite for all positive `N`.
501
502
EXAMPLES::
503
504
sage: R = IntegerModRing(18)
505
sage: R.is_finite()
506
True
507
"""
508
return True
509
510
@cached_method
511
def is_integral_domain(self, proof = True):
512
"""
513
Return ``True`` if and only if the order of ``self`` is prime.
514
515
EXAMPLES::
516
517
sage: Integers(389).is_integral_domain()
518
True
519
sage: Integers(389^2).is_integral_domain()
520
False
521
"""
522
return is_prime(self.order())
523
524
@cached_method
525
def is_field(self, proof = True):
526
"""
527
Return ``True`` precisely if the order is prime.
528
529
EXAMPLES::
530
531
sage: R = IntegerModRing(18)
532
sage: R.is_field()
533
False
534
sage: FF = IntegerModRing(17)
535
sage: FF.is_field()
536
True
537
"""
538
return self.order().is_prime()
539
540
@cached_method
541
def field(self):
542
"""
543
If this ring is a field, return the corresponding field as a finite
544
field, which may have extra functionality and structure. Otherwise,
545
raise a ``ValueError``.
546
547
EXAMPLES::
548
549
sage: R = Integers(7); R
550
Ring of integers modulo 7
551
sage: R.field()
552
Finite Field of size 7
553
sage: R = Integers(9)
554
sage: R.field()
555
Traceback (most recent call last):
556
...
557
ValueError: self must be a field
558
"""
559
try:
560
return self.__field
561
except AttributeError:
562
if not self.is_field():
563
raise ValueError("self must be a field")
564
import constructor
565
k = constructor.FiniteField(self.order())
566
self.__field = k
567
return k
568
569
def _pseudo_fraction_field(self):
570
"""
571
If ``self`` is composite, we may still want to do division by elements
572
of ``self``.
573
574
EXAMPLES::
575
576
sage: Integers(15).fraction_field()
577
Traceback (most recent call last):
578
...
579
TypeError: self must be an integral domain.
580
sage: Integers(15)._pseudo_fraction_field()
581
Ring of integers modulo 15
582
sage: R.<x> = Integers(15)[]
583
sage: (x+5)/2
584
8*x + 10
585
586
This should be very fast::
587
588
sage: R.<x> = Integers(next_prime(10^101)*next_prime(10^100))[]
589
sage: x / R.base_ring()(2)
590
500000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000013365000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000401*x
591
"""
592
return self
593
594
@cached_method
595
def multiplicative_group_is_cyclic(self):
596
"""
597
Return ``True`` if the multiplicative group of this field is cyclic.
598
This is the case exactly when the order is less than 8, a power
599
of an odd prime, or twice a power of an odd prime.
600
601
EXAMPLES::
602
603
sage: R = Integers(7); R
604
Ring of integers modulo 7
605
sage: R.multiplicative_group_is_cyclic()
606
True
607
sage: R = Integers(9)
608
sage: R.multiplicative_group_is_cyclic()
609
True
610
sage: Integers(8).multiplicative_group_is_cyclic()
611
False
612
sage: Integers(4).multiplicative_group_is_cyclic()
613
True
614
sage: Integers(25*3).multiplicative_group_is_cyclic()
615
False
616
617
We test that :trac:`5250` is fixed::
618
619
sage: Integers(162).multiplicative_group_is_cyclic()
620
True
621
"""
622
n = self.order()
623
if n < 8:
624
return True
625
626
if n % 4 == 0:
627
return False # know n > 7, so n=4 case not a problem
628
if n % 4 == 2:
629
n = n // 2
630
631
return n.is_prime_power()
632
633
@cached_method
634
def multiplicative_generator(self):
635
"""
636
Return a generator for the multiplicative group of this ring,
637
assuming the multiplicative group is cyclic.
638
639
Use the unit_gens function to obtain generators even in the
640
non-cyclic case.
641
642
EXAMPLES::
643
644
sage: R = Integers(7); R
645
Ring of integers modulo 7
646
sage: R.multiplicative_generator()
647
3
648
sage: R = Integers(9)
649
sage: R.multiplicative_generator()
650
2
651
sage: Integers(8).multiplicative_generator()
652
Traceback (most recent call last):
653
...
654
ValueError: multiplicative group of this ring is not cyclic
655
sage: Integers(4).multiplicative_generator()
656
3
657
sage: Integers(25*3).multiplicative_generator()
658
Traceback (most recent call last):
659
...
660
ValueError: multiplicative group of this ring is not cyclic
661
sage: Integers(25*3).unit_gens()
662
(26, 52)
663
sage: Integers(162).unit_gens()
664
(83,)
665
"""
666
try:
667
return self.__mult_gen
668
except AttributeError:
669
if self.is_field():
670
a = self(self.field().multiplicative_generator())
671
self.__mult_gen = a
672
return a
673
if self.multiplicative_group_is_cyclic():
674
v = self.unit_gens()
675
if len(v) != 1:
676
raise ArithmeticError
677
return v[0]
678
679
raise ValueError("multiplicative group of this ring is not cyclic")
680
681
def quadratic_nonresidue(self):
682
"""
683
Return a quadratic non-residue in ``self``.
684
685
EXAMPLES::
686
687
sage: R = Integers(17)
688
sage: R.quadratic_nonresidue()
689
3
690
sage: R(3).is_square()
691
False
692
"""
693
try:
694
return self._nonresidue
695
except AttributeError:
696
for a in self:
697
if not a.is_square():
698
self._nonresidue = a
699
return a
700
701
def square_roots_of_one(self):
702
"""
703
Return all square roots of 1 in self, i.e., all solutions to
704
`x^2 - 1 = 0`.
705
706
OUTPUT:
707
708
The square roots of 1 in ``self`` as a tuple.
709
710
EXAMPLES::
711
712
sage: R = Integers(2^10)
713
sage: [x for x in R if x^2 == 1]
714
[1, 511, 513, 1023]
715
sage: R.square_roots_of_one()
716
(1, 511, 513, 1023)
717
718
::
719
720
sage: v = Integers(9*5).square_roots_of_one(); v
721
(1, 19, 26, 44)
722
sage: [x^2 for x in v]
723
[1, 1, 1, 1]
724
sage: v = Integers(9*5*8).square_roots_of_one(); v
725
(1, 19, 71, 89, 91, 109, 161, 179, 181, 199, 251, 269, 271, 289, 341, 359)
726
sage: [x^2 for x in v]
727
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
728
"""
729
try:
730
return self.__square_roots_of_one
731
except AttributeError:
732
pass
733
n = self.__order
734
if n.is_prime_power():
735
if n % 2 == 0:
736
# power of 2
737
if n == 2:
738
v = [self(1)]
739
elif n == 4:
740
v = [self(1), self(3)]
741
else: # n >= 8
742
half_ord = n//2
743
v = [self(1), self(-1), self(half_ord-1), self(half_ord+1)]
744
else:
745
v = [self(1), self(-1)]
746
else:
747
# Reduce to the prime power case.
748
F = self.factored_order()
749
vmod = []
750
moduli = []
751
for p, e in F:
752
k = p**e
753
R = IntegerModRing(p**e)
754
w = [self(x) for x in R.square_roots_of_one()]
755
vmod.append(w)
756
moduli.append(k)
757
# Now combine in all possible ways using the CRT
758
from sage.rings.arith import CRT_basis
759
basis = CRT_basis(moduli)
760
from sage.misc.mrange import cartesian_product_iterator
761
v = []
762
for x in cartesian_product_iterator(vmod):
763
# x is a specific choice of roots modulo each prime power divisor
764
a = sum([basis[i]*x[i] for i in range(len(x))])
765
v.append(a)
766
#end for
767
#end if
768
769
v.sort()
770
v = tuple(v)
771
self.__square_roots_of_one = v
772
return v
773
774
@cached_method
775
def factored_order(self):
776
"""
777
EXAMPLES::
778
779
sage: R = IntegerModRing(18)
780
sage: FF = IntegerModRing(17)
781
sage: R.factored_order()
782
2 * 3^2
783
sage: FF.factored_order()
784
17
785
"""
786
return factor(self.__order, int_=(self.__order < 2**31))
787
788
def factored_unit_order(self):
789
"""
790
Return a list of :class:`Factorization` objects, each the factorization
791
of the order of the units in a `\ZZ / p^n \ZZ` component of this group
792
(using the Chinese Remainder Theorem).
793
794
EXAMPLES::
795
796
sage: R = Integers(8*9*25*17*29)
797
sage: R.factored_unit_order()
798
[2^2, 2 * 3, 2^2 * 5, 2^4, 2^2 * 7]
799
"""
800
ans = []
801
from sage.structure.factorization import Factorization
802
for p, e in self.factored_order():
803
ans.append(Factorization([(p,e-1)]) * factor(p-1, int_=(self.__order < 2**31)))
804
return ans
805
806
def characteristic(self):
807
"""
808
EXAMPLES::
809
810
sage: R = IntegerModRing(18)
811
sage: FF = IntegerModRing(17)
812
sage: FF.characteristic()
813
17
814
sage: R.characteristic()
815
18
816
"""
817
return self.__order
818
819
def _repr_(self):
820
"""
821
String representation.
822
823
EXAMPLES::
824
825
sage: Zmod(87)
826
Ring of integers modulo 87
827
"""
828
return "Ring of integers modulo {}".format(self.__order)
829
830
def _latex_(self):
831
r"""
832
Latex representation.
833
834
EXAMPLES::
835
836
sage: latex(Zmod(87))
837
\ZZ/87\ZZ
838
"""
839
return "\\ZZ/{}\\ZZ".format(self.__order)
840
841
def modulus(self):
842
r"""
843
Return the polynomial `x - 1` over this ring.
844
845
.. NOTE::
846
847
This function exists for consistency with the finite-field
848
modulus function.
849
850
EXAMPLES::
851
852
sage: R = IntegerModRing(18)
853
sage: R.modulus()
854
x + 17
855
sage: R = IntegerModRing(17)
856
sage: R.modulus()
857
x + 16
858
"""
859
try:
860
return self.__modulus
861
except AttributeError:
862
x = self['x'].gen()
863
self.__modulus = x - 1
864
return self.__modulus
865
866
def order(self):
867
"""
868
Return the order of this ring.
869
870
EXAMPLES::
871
872
sage: Zmod(87).order()
873
87
874
"""
875
return self.__order
876
877
def cardinality(self):
878
"""
879
Return the cardinality of this ring.
880
881
EXAMPLES::
882
883
sage: Zmod(87).cardinality()
884
87
885
"""
886
return self.order()
887
888
def _pari_order(self):
889
"""
890
Return the pari integer representing the order of this ring.
891
892
EXAMPLES::
893
894
sage: Zmod(87)._pari_order()
895
87
896
"""
897
try:
898
return self.__pari_order
899
except AttributeError:
900
self.__pari_order = pari(self.order())
901
return self.__pari_order
902
903
def _element_constructor_(self, x):
904
"""
905
TESTS::
906
907
sage: K2 = GF(2)
908
sage: K3 = GF(3)
909
sage: K8 = GF(8,'a')
910
sage: K8(5) # indirect doctest
911
1
912
sage: K8('a+1')
913
a + 1
914
sage: K8(K2(1))
915
1
916
917
The following test refers to :trac:`6468`::
918
919
sage: class foo_parent(Parent):
920
... pass
921
sage: class foo(RingElement):
922
... def lift(self):
923
... raise PariError
924
sage: P = foo_parent()
925
sage: F = foo(P)
926
sage: GF(2)(F)
927
Traceback (most recent call last):
928
...
929
TypeError: error coercing to finite field
930
931
The following test refers to :trac:`8970`::
932
933
sage: R = Zmod(13); a = R(2)
934
sage: a == R(gap(a))
935
True
936
937
"""
938
try:
939
return integer_mod.IntegerMod(self, x)
940
except (NotImplementedError, PariError):
941
raise TypeError("error coercing to finite field")
942
except TypeError:
943
if sage.interfaces.all.is_GapElement(x):
944
from sage.interfaces.gap import intmod_gap_to_sage
945
try:
946
y = intmod_gap_to_sage(x)
947
return self.coerce(y)
948
except (ValueError, IndexError, TypeError), msg:
949
raise TypeError("{}\nerror coercing to finite field".format(msg))
950
951
raise # Continue up with the original TypeError
952
953
954
def __iter__(self):
955
"""
956
EXAMPLES::
957
958
sage: R = IntegerModRing(3)
959
sage: for i in R:
960
... print i
961
0
962
1
963
2
964
sage: L = [i for i in R]
965
sage: L[0].parent()
966
Ring of integers modulo 3
967
"""
968
i = 0
969
order = int(self.__order)
970
while i < order:
971
yield self(i)
972
i = i + 1
973
974
def _coerce_map_from_(self, S):
975
"""
976
EXAMPLES::
977
978
sage: R = Integers(15)
979
sage: f = R.coerce_map_from(Integers(450)); f # indirect doctest
980
Natural morphism:
981
From: Ring of integers modulo 450
982
To: Ring of integers modulo 15
983
sage: f(-1)
984
14
985
sage: f = R.coerce_map_from(int); f
986
Native morphism:
987
From: Set of Python objects of type 'int'
988
To: Ring of integers modulo 15
989
sage: f(-1r)
990
14
991
sage: f = R.coerce_map_from(ZZ); f
992
Natural morphism:
993
From: Integer Ring
994
To: Ring of integers modulo 15
995
sage: f(-1)
996
14
997
sage: f = R.coerce_map_from(Integers(10)); print f
998
None
999
sage: f = R.coerce_map_from(QQ); print f
1000
None
1001
1002
sage: R = IntegerModRing(17)
1003
sage: a = R(3)
1004
sage: b = R._coerce_(3)
1005
sage: b
1006
3
1007
sage: a==b
1008
True
1009
1010
This is allowed::
1011
1012
sage: R(2/3)
1013
12
1014
1015
But this is not, since there is no (canonical or not!) ring
1016
homomorphism from `\QQ` to `\GF{17}`.
1017
1018
::
1019
1020
sage: R._coerce_(2/3)
1021
Traceback (most recent call last):
1022
...
1023
TypeError: no canonical coercion from Rational Field to Ring of integers modulo 17
1024
1025
We do not allow the coercion ``GF(p) -> Z/pZ``, because in case of a
1026
canonical isomorphism, there is a coercion map in only one
1027
direction, i.e., to the object in the smaller category.
1028
"""
1029
if S is int:
1030
return integer_mod.Int_to_IntegerMod(self)
1031
elif S is integer_ring.ZZ:
1032
return integer_mod.Integer_to_IntegerMod(self)
1033
elif isinstance(S, IntegerModRing_generic):
1034
if isinstance(S, field.Field):
1035
return None
1036
try:
1037
return integer_mod.IntegerMod_to_IntegerMod(S, self)
1038
except TypeError:
1039
pass
1040
to_ZZ = integer_ring.ZZ.coerce_map_from(S)
1041
if to_ZZ is not None:
1042
return integer_mod.Integer_to_IntegerMod(self) * to_ZZ
1043
1044
def __cmp__(self, other):
1045
"""
1046
EXAMPLES::
1047
1048
sage: Z11 = IntegerModRing(11); Z11
1049
Ring of integers modulo 11
1050
sage: Z12 = IntegerModRing(12); Z12
1051
Ring of integers modulo 12
1052
sage: Z13 = IntegerModRing(13); Z13
1053
Ring of integers modulo 13
1054
sage: F = GF(11); F
1055
Finite Field of size 11
1056
sage: Z11 == Z11, Z11 == Z12, Z11 == Z13, Z11 == F
1057
(True, False, False, False)
1058
"""
1059
if type(other) is not type(self): # so that GF(p) =/= Z/pZ
1060
return cmp(type(self), type(other))
1061
return cmp(self.__order, other.__order)
1062
1063
# The following __unit_gens functions are here since I just factored
1064
# them out from the unit_gens function. They are only called by
1065
# the unit_gens function.
1066
def __unit_gens_primecase(self, p):
1067
"""
1068
Assuming the modulus is prime, returns the smallest generator
1069
of the group of units.
1070
1071
EXAMPLES::
1072
1073
sage: Zmod(17)._IntegerModRing_generic__unit_gens_primecase(17)
1074
3
1075
"""
1076
if p == 2:
1077
return integer_mod.Mod(1,p)
1078
P = prime_divisors(p-1)
1079
ord = integer.Integer(p-1)
1080
one = integer_mod.Mod(1,p)
1081
x = 2
1082
while x < p:
1083
generator = True
1084
z = integer_mod.Mod(x,p)
1085
for q in P:
1086
if z**(ord//q) == one:
1087
generator = False
1088
break
1089
if generator:
1090
return z
1091
x += 1
1092
#end for
1093
raise ValueError("didn't find primitive root for p={}".format(p))
1094
1095
def __unit_gens_primepowercase(self, p, r):
1096
r"""
1097
Find smallest generator for
1098
`(\ZZ/p^r\ZZ)^*`.
1099
1100
EXAMPLES::
1101
1102
sage: Zmod(27)._IntegerModRing_generic__unit_gens_primepowercase(3,3)
1103
[2]
1104
"""
1105
if r == 1:
1106
return [self.__unit_gens_primecase(p)]
1107
1108
if p == 2:
1109
if r < 1:
1110
raise ValueError("p=2, r={} should be >=1".format(r))
1111
if r == 1:
1112
return []
1113
if r == 2:
1114
return [integer_mod.Mod(-1,2**r)]
1115
1116
pr=2**r
1117
a = integer_mod.Mod(5, pr)
1118
return [integer_mod.Mod(-1,pr), a]
1119
1120
# odd prime
1121
pr = p**r
1122
R = IntegerModRing(pr)
1123
x = R(self.__unit_gens_primecase(p).lift())
1124
n = p**(r-2)*(p-1)
1125
one = integer_mod.Mod(1,pr)
1126
for b in range(0,p):
1127
z = x+R(b*p)
1128
if z**n != one:
1129
a = integer_mod.Mod(z,pr)
1130
return [a]
1131
raise ValueError("p={}, r={}, couldn't find generator".format(p,r))
1132
1133
@cached_method
1134
def unit_gens(self):
1135
r"""
1136
Returns generators for the unit group `(\ZZ/N\ZZ)^*`.
1137
1138
We compute the list of generators using a deterministic algorithm, so
1139
the generators list will always be the same. For each odd prime divisor
1140
of `N` there will be exactly one corresponding generator; if `N` is
1141
even there will be 0, 1 or 2 generators according to whether 2 divides
1142
`N` to order 1, 2 or `\geq 3`.
1143
1144
OUTPUT:
1145
1146
A tuple containing the units of ``self``.
1147
1148
EXAMPLES::
1149
1150
sage: R = IntegerModRing(18)
1151
sage: R.unit_gens()
1152
(11,)
1153
sage: R = IntegerModRing(17)
1154
sage: R.unit_gens()
1155
(3,)
1156
sage: IntegerModRing(next_prime(10^30)).unit_gens()
1157
(5,)
1158
1159
TESTS::
1160
1161
sage: IntegerModRing(2).unit_gens()
1162
()
1163
sage: IntegerModRing(4).unit_gens()
1164
(3,)
1165
sage: IntegerModRing(8).unit_gens()
1166
(7, 5)
1167
"""
1168
n = self.__order
1169
if n == 1:
1170
return (self(1),)
1171
unit_gens = []
1172
for p,r in self.factored_order():
1173
m = n/(p**r)
1174
for g in self.__unit_gens_primepowercase(p, r):
1175
x = g.crt(integer_mod.Mod(1,m))
1176
if x != 1:
1177
unit_gens.append(x)
1178
return tuple(unit_gens)
1179
1180
@cached_method
1181
def unit_group_exponent(self):
1182
"""
1183
EXAMPLES::
1184
1185
sage: R = IntegerModRing(17)
1186
sage: R.unit_group_exponent()
1187
16
1188
sage: R = IntegerModRing(18)
1189
sage: R.unit_group_exponent()
1190
6
1191
"""
1192
a = []
1193
for p, r in self.factored_order():
1194
if p != 2:
1195
a.append((p-1)*(p**(r-1))) # phi(p**r)
1196
elif r==2: # p=2 from this point on
1197
a.append(2)
1198
elif r>2:
1199
a.append(2**(r-2))
1200
return int(LCM(a))
1201
1202
def unit_group_order(self):
1203
"""
1204
Return the order of the unit group of this residue class ring.
1205
1206
EXAMPLES::
1207
1208
sage: R = Integers(500)
1209
sage: R.unit_group_order()
1210
200
1211
"""
1212
return euler_phi(self.order())
1213
1214
def random_element(self, bound=None):
1215
"""
1216
Return a random element of this ring.
1217
1218
If ``bound`` is not ``None``, return the coercion of an integer in the
1219
interval ``[-bound, bound]`` into this ring.
1220
1221
EXAMPLES::
1222
1223
sage: R = IntegerModRing(18)
1224
sage: R.random_element()
1225
2
1226
"""
1227
if not (bound is None):
1228
return commutative_ring.CommutativeRing.random_element(self, bound)
1229
a = random.randint(0,self.order()-1)
1230
return self(a)
1231
1232
#######################################################
1233
# Suppose for interfaces
1234
#######################################################
1235
def _gap_init_(self):
1236
"""
1237
EXAMPLES::
1238
1239
sage: R = Integers(12345678900)
1240
sage: R
1241
Ring of integers modulo 12345678900
1242
sage: gap(R) # indirect doctest
1243
(Integers mod 12345678900)
1244
"""
1245
return 'ZmodnZ({})'.format(self.order())
1246
1247
def _magma_init_(self, magma):
1248
"""
1249
EXAMPLES::
1250
1251
sage: R = Integers(12345678900)
1252
sage: R
1253
Ring of integers modulo 12345678900
1254
sage: magma(R) # indirect doctest, optional - magma
1255
Residue class ring of integers modulo 12345678900
1256
"""
1257
return 'Integers({})'.format(self.order())
1258
1259
def degree(self):
1260
"""
1261
Return 1.
1262
1263
EXAMPLE::
1264
1265
sage: R = Integers(12345678900)
1266
sage: R.degree()
1267
1
1268
"""
1269
return integer.Integer(1)
1270
1271
Zmod = IntegerModRing
1272
Integers = IntegerModRing
1273
1274
# Register unpickling methods for backward compatibility.
1275
1276
from sage.structure.sage_object import register_unpickle_override
1277
register_unpickle_override('sage.rings.integer_mod_ring', 'IntegerModRing_generic', IntegerModRing_generic)
1278
1279
## def GF(p):
1280
## """
1281
## EXAMPLES:
1282
## sage: F = GF(11)
1283
## sage: F
1284
## Finite field of size 11
1285
## """
1286
## if not arith.is_prime(p):
1287
## raise NotImplementedError("only prime fields currently implemented")
1288
## return IntegerModRing(p)
1289
1290
def crt(v):
1291
"""
1292
INPUT:
1293
1294
- ``v`` -- (list) a lift of elements of ``rings.IntegerMod(n)``, for
1295
various coprime moduli ``n``
1296
1297
EXAMPLES::
1298
1299
sage: from sage.rings.finite_rings.integer_mod_ring import crt
1300
sage: crt([mod(3, 8),mod(1,19),mod(7, 15)])
1301
1027
1302
"""
1303
if len(v) == 0:
1304
return IntegerModRing(1)(1)
1305
x = v[0]
1306
for i in range(1,len(v)):
1307
x = x.crt(v[i])
1308
return x
1309
1310
1311