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