Path: blob/master/sage/rings/finite_rings/integer_mod_ring.py
4072 views
r"""1Ring `\ZZ/n\ZZ` of integers modulo `n`23EXAMPLES::45sage: R = Integers(97)6sage: a = R(5)7sage: a**100000000000000000000000000000000000000000000000000000000000000861910This example illustrates the relation between11`\ZZ/p\ZZ` and `\GF{p}`. In12particular, there is a canonical map to `\GF{p}`, but not in13the other direction.1415::1617sage: r = Integers(7)18sage: s = GF(7)19sage: r.has_coerce_map_from(s)20False21sage: s.has_coerce_map_from(r)22True23sage: s(1) + r(1)24225sage: parent(s(1) + r(1))26Finite Field of size 727sage: parent(r(1) + s(1))28Finite Field of size 72930We list the elements of `\ZZ/3\ZZ`3132::3334sage: R = Integers(3)35sage: list(R)36[0, 1, 2]3738AUTHORS:3940- William Stein (initial code)4142- David Joyner (2005-12-22): most examples4344- Robert Bradshaw (2006-08-24): convert to SageX (Cython)4546- William Stein (2007-04-29): square_roots_of_one4748- Simon King (2011-04-21): allow to prescribe a category49"""5051#*****************************************************************************52#53# Sage: System for Algebra and Geometry Experimentation54#55# Copyright (C) 2005 William Stein <[email protected]>56#57# Distributed under the terms of the GNU General Public License (GPL)58#59# This code is distributed in the hope that it will be useful,60# but WITHOUT ANY WARRANTY; without even the implied warranty of61# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU62# General Public License for more details.63#64# The full text of the GPL is available at:65#66# http://www.gnu.org/licenses/67#*****************************************************************************6869import sage.misc.prandom as random7071from sage.rings.arith import is_prime, factor, CRT_basis, LCM, prime_divisors, euler_phi72import sage.rings.commutative_ring as commutative_ring73import sage.rings.field as field74import integer_mod75import sage.rings.integer as integer76import sage.rings.integer_ring as integer_ring77import sage.rings.quotient_ring as quotient_ring78from sage.structure.parent_gens import ParentWithGens7980from sage.libs.pari.all import pari, PariError8182import sage.interfaces.all83from sage.misc.cachefunc import cached_method8485from sage.structure.factory import UniqueFactory8687class IntegerModFactory(UniqueFactory):88r"""89Return the quotient ring `\ZZ / n\ZZ`.9091INPUT:929394- ``order`` - integer (default: 0), positive or95negative969798EXAMPLES::99100sage: IntegerModRing(15)101Ring of integers modulo 15102sage: IntegerModRing(7)103Ring of integers modulo 7104sage: IntegerModRing(-100)105Ring of integers modulo 100106107Note that you can also use ``Integers``, which is a108synonym for ``IntegerModRing``.109110::111112sage: Integers(18)113Ring of integers modulo 18114sage: Integers() is Integers(0) is ZZ115True116"""117def create_key(self, order=0, category=None):118"""119An integer mod ring is specified uniquely by its order.120121EXAMPLES::122123sage: Zmod.create_key(7)1247125sage: Zmod.create_key(7, Fields())126(7, Category of fields)127"""128if category is None:129return order130return (order, category)131132def create_object(self, version, order):133"""134EXAMPLES::135136sage: R = Integers(10)137sage: TestSuite(R).run() # indirect doctest138"""139category=None140if isinstance(order, tuple):141order, category = order142if order < 0:143order = -order144if order == 0:145return integer_ring.IntegerRing()146else:147return IntegerModRing_generic(order,category=category)148149Zmod = Integers = IntegerModRing = IntegerModFactory("IntegerModRing")150151152def is_IntegerModRing(x):153"""154Return True if x is an integer modulo ring.155156EXAMPLES::157158sage: from sage.rings.finite_rings.integer_mod_ring import is_IntegerModRing159sage: R = IntegerModRing(17)160sage: is_IntegerModRing(R)161True162sage: is_IntegerModRing(GF(13))163True164sage: is_IntegerModRing(GF(4, 'a'))165False166sage: is_IntegerModRing(10)167False168sage: is_IntegerModRing(ZZ)169False170"""171return isinstance(x, IntegerModRing_generic)172173from sage.categories.commutative_rings import CommutativeRings174from sage.categories.finite_enumerated_sets import FiniteEnumeratedSets175from sage.categories.category import JoinCategory176default_category = JoinCategory((CommutativeRings(), FiniteEnumeratedSets()))177ZZ = integer_ring.IntegerRing()178179class IntegerModRing_generic(quotient_ring.QuotientRing_generic):180"""181The ring of integers modulo N, with N composite.182183EXAMPLES::184185sage: R = IntegerModRing(97)186sage: a = R(5)187sage: a**(10^62)18861189"""190def __init__(self, order, cache=None, category=None):191"""192Create with the command IntegerModRing(order)193194INPUT:195196197- ``order`` - an integer 1198199- ``category`` - a subcategory of ``CommutativeRings()`` (the default)200(currently only available for subclasses)201202OUTPUT:203204205- ``IntegerModRing`` - the ring of integers modulo206N.207208209EXAMPLES:210211First we compute with integers modulo `29`.212213::214215sage: FF = IntegerModRing(29)216sage: FF217Ring of integers modulo 29218sage: FF.category()219Join of Category of commutative rings and Category of subquotients of monoids and Category of quotients of semigroups and Category of finite enumerated sets220sage: FF.is_field()221True222sage: FF.characteristic()22329224sage: FF.order()22529226sage: gens = FF.unit_gens()227sage: a = gens[0]228sage: a2292230sage: a.is_square()231False232sage: def pow(i): return a**i233sage: [pow(i) for i in range(16)]234[1, 2, 4, 8, 16, 3, 6, 12, 24, 19, 9, 18, 7, 14, 28, 27]235sage: TestSuite(FF).run()236237We have seen above that an integer mod ring is, by default, not238initialised as an object in the category of fields. However, one239can force it to be. Moreover, testing containment in the category240of fields my re-initialise the category of the integer mod ring::241242sage: F19 = IntegerModRing(19, category = Fields())243sage: F19.category().is_subcategory(Fields())244True245sage: F23 = IntegerModRing(23)246sage: F23.category().is_subcategory(Fields())247False248sage: F23 in Fields()249True250sage: F23.category().is_subcategory(Fields())251True252sage: TestSuite(F19).run()253sage: TestSuite(F23).run()254255Next we compute with the integers modulo `16`.256257::258259sage: Z16 = IntegerModRing(16)260sage: Z16.category()261Join of Category of commutative rings and Category of subquotients of monoids and Category of quotients of semigroups and Category of finite enumerated sets262sage: Z16.is_field()263False264sage: Z16.order()26516266sage: Z16.characteristic()26716268sage: gens = Z16.unit_gens()269sage: gens270[15, 5]271sage: a = gens[0]272sage: b = gens[1]273sage: def powa(i): return a**i274sage: def powb(i): return b**i275sage: gp_exp = FF.unit_group_exponent()276sage: gp_exp27728278sage: [powa(i) for i in range(15)]279[1, 15, 1, 15, 1, 15, 1, 15, 1, 15, 1, 15, 1, 15, 1]280sage: [powb(i) for i in range(15)]281[1, 5, 9, 13, 1, 5, 9, 13, 1, 5, 9, 13, 1, 5, 9]282sage: a.multiplicative_order()2832284sage: b.multiplicative_order()2854286sage: TestSuite(Z16).run()287288Saving and loading::289290sage: R = Integers(100000)291sage: TestSuite(R).run() # long time (17s on sage.math, 2011)292293Testing ideals and quotients::294295sage: Z10 = Integers(10)296sage: I = Z10.principal_ideal(0)297sage: Z10.quotient(I) == Z10298True299sage: I = Z10.principal_ideal(2)300sage: Z10.quotient(I) == Z10301False302sage: I.is_prime()303True304"""305order = ZZ(order)306if order <= 0:307raise ZeroDivisionError, "order must be positive"308self.__order = order309self._pyx_order = integer_mod.NativeIntStruct(order)310self.__unit_group_exponent = None311self.__factored_order = None312self.__factored_unit_order = None313if category is None:314from sage.categories.commutative_rings import CommutativeRings315from sage.categories.finite_enumerated_sets import FiniteEnumeratedSets316from sage.categories.category import Category317category = Category.join([CommutativeRings(), FiniteEnumeratedSets()])318# category = default_category319# If the category is given then we trust that is it right.320# Give the generator a 'name' to make quotients work. The321# name 'x' is used because it's also used for the ring of322# integers: see the __init__ method for IntegerRing_class in323# sage/rings/integer_ring.pyx.324quotient_ring.QuotientRing_generic.__init__(self, ZZ, ZZ.ideal(order),325names=('x',),326category=category)327# Calling ParentWithGens is not needed, the job is done in328# the quotient ring initialisation.329#ParentWithGens.__init__(self, self, category = category)330# We want that the ring is its own base ring.331self._base = self332if cache is None:333cache = order < 500334if cache:335self._precompute_table()336self._zero_element = integer_mod.IntegerMod(self, 0)337self._one_element = integer_mod.IntegerMod(self, 1)338339def _macaulay2_init_(self):340"""341EXAMPLES::342343sage: macaulay2(Integers(7)) # indirect doctest, optional - macaulay2344ZZ345--3467347348::349350sage: macaulay2(Integers(10)) # optional - macaulay2351Traceback (most recent call last):352...353TypeError: Error evaluating Macaulay2 code.354IN:sage1=ZZ/10;355OUT:stdio:3:9:(1):[0]: ZZ/n not implemented yet for composite n356"""357return "ZZ/%s"%self.order()358359def _axiom_init_(self):360"""361Returns a string representation of self in (Pan)Axiom.362363EXAMPLES::364365sage: Z7 = Integers(7)366sage: Z7._axiom_init_()367'IntegerMod(7)'368369sage: axiom(Z7) #optional - axiom370IntegerMod 7371372sage: fricas(Z7) #optional - fricas373IntegerMod(7)374"""375return 'IntegerMod(%s)'%self.order()376377_fricas_init_ = _axiom_init_378379def krull_dimension(self):380"""381EXAMPLES::382383sage: Integers(18).krull_dimension()3840385"""386return integer.Integer(0)387388def is_noetherian(self):389"""390EXAMPLES::391392sage: Integers(8).is_noetherian()393True394"""395return True396397@cached_method398def is_prime_field(self):399"""400Return ``True`` if the order is prime.401402EXAMPLES::403404sage: Zmod(7).is_prime_field()405True406sage: Zmod(8).is_prime_field()407False408"""409return self.__order.is_prime()410411412def _precompute_table(self):413"""414Computes a table of elements so that elements are unique.415416EXAMPLES::417418sage: R = Zmod(500); R._precompute_table()419sage: R(7) + R(13) is R(3) + R(17)420True421"""422self._pyx_order.precompute_table(self)423424def list_of_elements_of_multiplicative_group(self):425"""426Returns a list of all invertible elements, as python ints.427428EXAMPLES::429430sage: R = Zmod(12)431sage: L = R.list_of_elements_of_multiplicative_group(); L432[1, 5, 7, 11]433sage: type(L[0])434<type 'int'>435"""436import sage.rings.fast_arith as a437if self.__order <= 46340: # todo: don't hard code438gcd = a.arith_int().gcd_int439elif self.__order <= 2147483647: # todo: don't hard code440gcd = a.arith_llong().gcd_longlong441else:442raise MemoryError, "creating the list would exhaust memory."443N = self.__order444H = [i for i in range(N) if gcd(i, N) == 1]445return H446447@cached_method448def multiplicative_subgroups(self):449r"""450Return generators for each subgroup of451`(\ZZ/N\ZZ)^*`.452453EXAMPLES::454455sage: Integers(5).multiplicative_subgroups()456([2], [4], [])457sage: Integers(15).multiplicative_subgroups()458([11, 7], [4, 11], [8], [11], [14], [7], [4], [])459sage: Integers(2).multiplicative_subgroups()460([],)461sage: len(Integers(341).multiplicative_subgroups())46280463"""464from sage.groups.abelian_gps.abelian_group import AbelianGroup465from sage.misc.misc import mul466U = self.unit_gens()467G = AbelianGroup([x.multiplicative_order() for x in U])468rawsubs = G.subgroups()469mysubs = []470for G in rawsubs:471mysubs.append([])472for s in G.gens():473mysubs[-1].append(mul([U[i] ** s.list()[i] for i in xrange(len(U))]))474return tuple(mysubs) # make it immutable, so that we can cache475476def is_finite(self):477"""478Return True since Z/NZ is finite for all positive N.479480EXAMPLES::481482sage: R = IntegerModRing(18)483sage: R.is_finite()484True485"""486return True487488@cached_method489def is_integral_domain(self, proof = True):490"""491Return True if and only if the order of self is prime.492493EXAMPLES::494495sage: Integers(389).is_integral_domain()496True497sage: Integers(389^2).is_integral_domain()498False499"""500return is_prime(self.order())501502@cached_method503def is_field(self, proof = True):504"""505Return True precisely if the order is prime.506507EXAMPLES::508509sage: R = IntegerModRing(18)510sage: R.is_field()511False512sage: FF = IntegerModRing(17)513sage: FF.is_field()514True515"""516return self.order().is_prime()517518@cached_method519def field(self):520"""521If this ring is a field, return the corresponding field as a finite522field, which may have extra functionality and structure. Otherwise,523raise a ValueError.524525EXAMPLES::526527sage: R = Integers(7); R528Ring of integers modulo 7529sage: R.field()530Finite Field of size 7531sage: R = Integers(9)532sage: R.field()533Traceback (most recent call last):534...535ValueError: self must be a field536"""537try:538return self.__field539except AttributeError:540if not self.is_field():541raise ValueError, "self must be a field"542import constructor543k = constructor.FiniteField(self.order())544self.__field = k545return k546547def _pseudo_fraction_field(self):548"""549If self is composite, we may still want to do division by elements550of self.551552EXAMPLES::553554sage: Integers(15).fraction_field()555Traceback (most recent call last):556...557TypeError: self must be an integral domain.558sage: Integers(15)._pseudo_fraction_field()559Ring of integers modulo 15560sage: R.<x> = Integers(15)[]561sage: (x+5)/25628*x + 10563564This should be very fast::565566sage: R.<x> = Integers(next_prime(10^101)*next_prime(10^100))[]567sage: x / R.base_ring()(2)568500000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000013365000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000401*x569"""570return self571572@cached_method573def multiplicative_group_is_cyclic(self):574"""575Return True if the multiplicative group of this field is cyclic.576This is the case exactly when the order is less than 8, a power577of an odd prime, or twice a power of an odd prime.578579EXAMPLES::580581sage: R = Integers(7); R582Ring of integers modulo 7583sage: R.multiplicative_group_is_cyclic()584True585sage: R = Integers(9)586sage: R.multiplicative_group_is_cyclic()587True588sage: Integers(8).multiplicative_group_is_cyclic()589False590sage: Integers(4).multiplicative_group_is_cyclic()591True592sage: Integers(25*3).multiplicative_group_is_cyclic()593False594595We test that #5250 is fixed::596597sage: Integers(162).multiplicative_group_is_cyclic()598True599"""600n = self.order()601if n < 8:602return True603604if n % 4 == 0:605return False # know n > 7, so n=4 case not a problem606if n % 4 == 2:607n = n // 2608609if n.is_prime_power():610return True611else:612return False613614@cached_method615def multiplicative_generator(self):616"""617Return a generator for the multiplicative group of this ring,618assuming the multiplicative group is cyclic.619620Use the unit_gens function to obtain generators even in the621non-cyclic case.622623EXAMPLES::624625sage: R = Integers(7); R626Ring of integers modulo 7627sage: R.multiplicative_generator()6283629sage: R = Integers(9)630sage: R.multiplicative_generator()6312632sage: Integers(8).multiplicative_generator()633Traceback (most recent call last):634...635ValueError: multiplicative group of this ring is not cyclic636sage: Integers(4).multiplicative_generator()6373638sage: Integers(25*3).multiplicative_generator()639Traceback (most recent call last):640...641ValueError: multiplicative group of this ring is not cyclic642sage: Integers(25*3).unit_gens()643[26, 52]644sage: Integers(162).unit_gens()645[83]646"""647try:648return self.__mult_gen649except AttributeError:650if self.is_field():651a = self(self.field().multiplicative_generator())652elif self.multiplicative_group_is_cyclic():653v = self.unit_gens()654if len(v) != 1:655raise ArithmeticError656return v[0]657else:658raise ValueError, "multiplicative group of this ring is not cyclic"659self.__mult_gen = a660return a661662def quadratic_nonresidue(self):663"""664Return a quadratic non-residue in self.665666EXAMPLES::667668sage: R = Integers(17)669sage: R.quadratic_nonresidue()6703671sage: R(3).is_square()672False673"""674try:675return self._nonresidue676except AttributeError:677for a in self:678if not a.is_square():679self._nonresidue = a680return a681682def square_roots_of_one(self):683"""684Return all square roots of 1 in self, i.e., all solutions to685`x^2 - 1 = 0`.686687OUTPUT:688689690- ``tuple`` - the square roots of 1 in self.691692693EXAMPLES::694695sage: R = Integers(2^10)696sage: [x for x in R if x^2 == 1]697[1, 511, 513, 1023]698sage: R.square_roots_of_one()699(1, 511, 513, 1023)700701::702703sage: v = Integers(9*5).square_roots_of_one(); v704(1, 19, 26, 44)705sage: [x^2 for x in v]706[1, 1, 1, 1]707sage: v = Integers(9*5*8).square_roots_of_one(); v708(1, 19, 71, 89, 91, 109, 161, 179, 181, 199, 251, 269, 271, 289, 341, 359)709sage: [x^2 for x in v]710[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]711"""712try:713return self.__square_roots_of_one714except AttributeError:715pass716n = self.__order717if n.is_prime_power():718if n % 2 == 0:719# power of 2720if n == 2:721v = [self(1)]722elif n == 4:723v = [self(1), self(3)]724else: # n >= 8725half_ord = n//2726v = [self(1), self(-1), self(half_ord-1), self(half_ord+1)]727else:728v = [self(1), self(-1)]729else:730# Reduce to the prime power case.731F = self.factored_order()732vmod = []733moduli = []734for p, e in F:735k = p**e736R = IntegerModRing(p**e)737w = [self(x) for x in R.square_roots_of_one()]738vmod.append(w)739moduli.append(k)740# Now combine in all possible ways using the CRT741from sage.rings.arith import CRT_basis742basis = CRT_basis(moduli)743from sage.misc.mrange import cartesian_product_iterator744v = []745for x in cartesian_product_iterator(vmod):746# x is a specific choice of roots modulo each prime power divisor747a = sum([basis[i]*x[i] for i in range(len(x))])748v.append(a)749#end for750#end if751752v.sort()753v = tuple(v)754self.__square_roots_of_one = v755return v756757def factored_order(self):758"""759EXAMPLES::760761sage: R = IntegerModRing(18)762sage: FF = IntegerModRing(17)763sage: R.factored_order()7642 * 3^2765sage: FF.factored_order()76617767"""768if self.__factored_order is not None:769return self.__factored_order770self.__factored_order = factor(self.__order, int_=(self.__order < 2**31))771return self.__factored_order772773def factored_unit_order(self):774"""775Returns a list of Factorization objects, each the factorization of the776order of the units in a `\ZZ / p^n \ZZ` component of this group (using777the Chinese Remainder Theorem).778779EXAMPLES::780781sage: R = Integers(8*9*25*17*29)782sage: R.factored_unit_order()783[2^2, 2 * 3, 2^2 * 5, 2^4, 2^2 * 7]784"""785ans = []786from sage.structure.factorization import Factorization787for p, e in self.factored_order():788ans.append(Factorization([(p,e-1)]) * factor(p-1, int_=(self.__order < 2**31)))789return ans790791def characteristic(self):792"""793EXAMPLES::794795sage: R = IntegerModRing(18)796sage: FF = IntegerModRing(17)797sage: FF.characteristic()79817799sage: R.characteristic()80018801"""802return self.__order803804def _repr_(self):805"""806String representation.807808EXAMPLES::809810sage: Zmod(87) # indirect doctest811Ring of integers modulo 87812"""813return "Ring of integers modulo %s"%self.__order814815def _latex_(self):816"""817Latex representation.818819EXAMPLES::820821sage: latex(Zmod(87)) # indirect doctest822\ZZ/87\ZZ823"""824return "\ZZ/%s\ZZ" % self.__order825826def modulus(self):827r"""828Return the polynomial `x - 1` over this ring.829830.. note::831832This function exists for consistency with the finite-field833modulus function.834835EXAMPLES::836837sage: R = IntegerModRing(18)838sage: R.modulus()839x + 17840sage: R = IntegerModRing(17)841sage: R.modulus()842x + 16843"""844try:845return self.__modulus846except AttributeError:847x = self['x'].gen()848self.__modulus = x - 1849return self.__modulus850851def order(self):852"""853Returns the order of this ring.854855EXAMPLES::856857sage: Zmod(87).order()85887859"""860return self.__order861862def cardinality(self):863"""864Returns the cardinality of this ring.865866EXAMPLES::867868sage: Zmod(87).cardinality()86987870"""871return self.order()872873def _pari_order(self):874"""875Returns the pari integer representing the order of this ring.876877EXAMPLES::878879sage: Zmod(87)._pari_order()88087881"""882try:883return self.__pari_order884except AttributeError:885self.__pari_order = pari(self.order())886return self.__pari_order887888def _element_constructor_(self, x):889"""890TESTS::891892sage: K2 = GF(2)893sage: K3 = GF(3)894sage: K8 = GF(8,'a')895sage: K8(5) # indirect doctest8961897sage: K8('a+1')898a + 1899sage: K8(K2(1))9001901902The following test refers to Trac Ticket number 6468::903904sage: class foo_parent(Parent):905... pass906sage: class foo(RingElement):907... def lift(self):908... raise PariError909sage: P = foo_parent()910sage: F = foo(P)911sage: GF(2)(F)912Traceback (most recent call last):913...914TypeError: error coercing to finite field915916The following test refers to ticket #8970::917918sage: R = Zmod(13); a = R(2)919sage: a == R(gap(a))920True921922"""923try:924return integer_mod.IntegerMod(self, x)925except (NotImplementedError, PariError):926raise TypeError, "error coercing to finite field"927except TypeError:928if sage.interfaces.all.is_GapElement(x):929from sage.interfaces.gap import intmod_gap_to_sage930try:931y = intmod_gap_to_sage(x)932return self.coerce(y)933except (ValueError, IndexError, TypeError), msg:934raise TypeError, "%s\nerror coercing to finite field"%msg935else:936raise937938939def __iter__(self):940"""941EXAMPLES::942943sage: R = IntegerModRing(3)944sage: for i in R:945... print i946094719482949sage: L = [i for i in R]950sage: L[0].parent()951Ring of integers modulo 3952"""953i = 0954order = int(self.__order)955while i < order:956yield self(i)957i = i + 1958959def _coerce_map_from_(self, S):960"""961EXAMPLES::962963sage: R = Integers(15)964sage: f = R.coerce_map_from(Integers(450)); f # indirect doctest965Natural morphism:966From: Ring of integers modulo 450967To: Ring of integers modulo 15968sage: f(-1)96914970sage: f = R.coerce_map_from(int); f971Native morphism:972From: Set of Python objects of type 'int'973To: Ring of integers modulo 15974sage: f(-1r)97514976sage: f = R.coerce_map_from(ZZ); f977Natural morphism:978From: Integer Ring979To: Ring of integers modulo 15980sage: f(-1)98114982sage: f = R.coerce_map_from(Integers(10)); print f983None984sage: f = R.coerce_map_from(QQ); print f985None986987sage: R = IntegerModRing(17)988sage: a = R(3)989sage: b = R._coerce_(3)990sage: b9913992sage: a==b993True994995This is allowed::996997sage: R(2/3)998129991000But this is not, since there is no (canonical or not!) ring1001homomorphism from `\QQ` to `\GF{17}`.10021003::10041005sage: R._coerce_(2/3)1006Traceback (most recent call last):1007...1008TypeError: no canonical coercion from Rational Field to Ring of integers modulo 1710091010We do not allow the coercion GF(p) - Z/pZ, because in case of a1011canonical isomorphism, there is a coercion map in only one1012direction, i.e., to the object in the smaller category.1013"""1014if S is int:1015return integer_mod.Int_to_IntegerMod(self)1016elif S is integer_ring.ZZ:1017return integer_mod.Integer_to_IntegerMod(self)1018elif isinstance(S, IntegerModRing_generic):1019if isinstance(S, field.Field):1020return None1021try:1022return integer_mod.IntegerMod_to_IntegerMod(S, self)1023except TypeError:1024pass1025to_ZZ = integer_ring.ZZ.coerce_map_from(S)1026if to_ZZ is not None:1027return integer_mod.Integer_to_IntegerMod(self) * to_ZZ10281029def __cmp__(self, other):1030"""1031EXAMPLES::10321033sage: Z11 = IntegerModRing(11); Z111034Ring of integers modulo 111035sage: Z12 = IntegerModRing(12); Z121036Ring of integers modulo 121037sage: Z13 = IntegerModRing(13); Z131038Ring of integers modulo 131039sage: F = GF(11); F1040Finite Field of size 111041sage: Z11 == Z11, Z11 == Z12, Z11 == Z13, Z11 == F1042(True, False, False, False)1043"""1044if type(other) is not type(self): # so that GF(p) =/= Z/pZ1045return cmp(type(self), type(other))1046return cmp(self.__order, other.__order)10471048# The following __unit_gens functions are here since I just factored1049# them out from the unit_gens function. They are only called by1050# the unit_gens function.1051def __unit_gens_primecase(self, p):1052"""1053Assuming the modulus is prime, returns the smallest generator1054of the group of units.10551056EXAMPLES::10571058sage: Zmod(17)._IntegerModRing_generic__unit_gens_primecase(17)105931060"""1061if p==2:1062return integer_mod.Mod(1,p)1063P = prime_divisors(p-1)1064ord = integer.Integer(p-1)1065one = integer_mod.Mod(1,p)1066x = 21067while x < p:1068generator = True1069z = integer_mod.Mod(x,p)1070for q in P:1071if z**(ord//q) == one:1072generator = False1073break1074if generator:1075return z1076x += 11077#end for1078assert False, "didn't find primitive root for p=%s"%p10791080def __unit_gens_primepowercase(self, p, r):1081r"""1082Find smallest generator for1083`(\ZZ/p^r\ZZ)^*`.10841085EXAMPLES::10861087sage: Zmod(27)._IntegerModRing_generic__unit_gens_primepowercase(3,3)1088[2]1089"""1090if r==1:1091return [self.__unit_gens_primecase(p)]1092elif p==2:1093if r==1:1094return []1095elif r==2:1096return [integer_mod.Mod(-1,2**r)]1097elif r>=3:1098pr=2**r1099a = integer_mod.Mod(5, pr)1100return [integer_mod.Mod(-1,pr), a]1101assert False, "p=2, r=%s should be >=1"%r1102else: # odd prime1103pr = p**r1104R = IntegerModRing(pr)1105x = R(self.__unit_gens_primecase(p).lift())1106n = p**(r-2)*(p-1)1107one = integer_mod.Mod(1,pr)1108for b in range(0,p):1109z = x+R(b*p)1110if z**n != one:1111a = integer_mod.Mod(z,pr)1112return [a]1113assert False, "p=%s, r=%s, couldn't find generator"%(p,r)11141115def unit_gens(self):1116r"""1117Returns generators for the unit group `(\ZZ/N\ZZ)^*`.11181119We compute the list of generators using a deterministic algorithm, so1120the generators list will always be the same. For each odd prime divisor1121of N there will be exactly one corresponding generator; if N is even1122there will be 0, 1 or 2 generators according to whether 2 divides N to1123order 1, 2 or `\ge 3`.11241125INPUT: (none)11261127OUTPUT:11281129- ``list`` - a list of elements of self11301131EXAMPLES::11321133sage: R = IntegerModRing(18)1134sage: R.unit_gens()1135[11]1136sage: R = IntegerModRing(17)1137sage: R.unit_gens()1138[3]1139sage: IntegerModRing(next_prime(10^30)).unit_gens()1140[5]1141"""1142try:1143return self.__unit_gens1144except AttributeError:1145self.__unit_gens = []1146n = self.__order1147if n == 1:1148self.__unit_gens = [self(1)]1149return self.__unit_gens1150for p,r in self.factored_order():1151m = n/(p**r)1152for g in self.__unit_gens_primepowercase(p, r):1153x = g.crt(integer_mod.Mod(1,m))1154if x != 1:1155self.__unit_gens.append(x)1156return self.__unit_gens11571158def unit_group_exponent(self):1159"""1160EXAMPLES::11611162sage: R = IntegerModRing(17)1163sage: R.unit_group_exponent()1164161165sage: R = IntegerModRing(18)1166sage: R.unit_group_exponent()116761168"""1169if self.__unit_group_exponent != None:1170return self.__unit_group_exponent1171a = []1172for p, r in self.factored_order():1173if p != 2:1174a.append((p-1)*(p**(r-1))) # phi(p**r)1175else: # p=21176if r==2:1177a.append(2)1178elif r>2:1179a.append(2**(r-2))1180#endif1181#endfor1182self.__unit_group_exponent = int(LCM(a))1183return self.__unit_group_exponent11841185def unit_group_order(self):1186"""1187Return the order of the unit group of this residue class ring.11881189EXAMPLES;11901191::11921193sage: R = Integers(500)1194sage: R.unit_group_order()11952001196"""1197return euler_phi(self.order())11981199def random_element(self, bound=None):1200"""1201Return a random element of this ring.12021203If bound is not None, return the coercion of an integer in the1204interval [-bound, bound] into this ring.12051206EXAMPLES::12071208sage: R = IntegerModRing(18)1209sage: R.random_element()121021211"""1212if not (bound is None):1213return commutative_ring.CommutativeRing.random_element(self, bound)1214a = random.randint(0,self.order()-1)1215return self(a)12161217#######################################################1218# Suppose for interfaces1219#######################################################1220def _gap_init_(self):1221"""1222EXAMPLES::12231224sage: R = Integers(12345678900)1225sage: R1226Ring of integers modulo 123456789001227sage: gap(R) # indirect doctest1228(Integers mod 12345678900)1229"""1230return 'ZmodnZ(%s)'%self.order()12311232def _magma_init_(self, magma):1233"""1234EXAMPLES::12351236sage: R = Integers(12345678900)1237sage: R1238Ring of integers modulo 123456789001239sage: magma(R) # indirect doctest, optional - magma1240Residue class ring of integers modulo 123456789001241"""1242return 'Integers(%s)'%self.order()124312441245def degree(self):1246"""1247Return 1.12481249EXAMPLE::12501251sage: R = Integers(12345678900)1252sage: R.degree()125311254"""1255return integer.Integer(1)12561257Zmod = IntegerModRing1258Integers = IntegerModRing12591260# Register unpickling methods for backward compatibility.12611262from sage.structure.sage_object import register_unpickle_override1263register_unpickle_override('sage.rings.integer_mod_ring', 'IntegerModRing_generic', IntegerModRing_generic)12641265## def GF(p):1266## """1267## EXAMPLES:1268## sage: F = GF(11)1269## sage: F1270## Finite field of size 111271## """1272## if not arith.is_prime(p):1273## raise NotImplementedError, "Only prime fields currently implemented."1274## return IntegerModRing(p)12751276def crt(v):1277"""1278INPUT: v - (list) a lift of elements of rings.IntegerMod(n), for1279various coprime moduli n.12801281EXAMPLES::12821283sage: from sage.rings.finite_rings.integer_mod_ring import crt1284sage: crt([mod(3, 8),mod(1,19),mod(7, 15)])128510271286"""1287if len(v) == 0:1288return IntegerModRing(1)(1)1289x = v[0]1290for i in range(1,len(v)):1291x = x.crt(v[i])1292return x1293129412951296