Path: blob/master/src/sage/rings/finite_rings/integer_mod_ring.py
8820 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`::3132sage: R = Integers(3)33sage: list(R)34[0, 1, 2]3536AUTHORS:3738- William Stein (initial code)3940- David Joyner (2005-12-22): most examples4142- Robert Bradshaw (2006-08-24): convert to SageX (Cython)4344- William Stein (2007-04-29): square_roots_of_one4546- Simon King (2011-04-21): allow to prescribe a category47"""4849#*****************************************************************************50#51# Sage: System for Algebra and Geometry Experimentation52#53# Copyright (C) 2005 William Stein <[email protected]>54#55# Distributed under the terms of the GNU General Public License (GPL)56#57# This code is distributed in the hope that it will be useful,58# but WITHOUT ANY WARRANTY; without even the implied warranty of59# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU60# General Public License for more details.61#62# The full text of the GPL is available at:63#64# http://www.gnu.org/licenses/65#*****************************************************************************6667import sage.misc.prandom as random6869from sage.rings.arith import is_prime, factor, CRT_basis, LCM, prime_divisors, euler_phi70import sage.rings.commutative_ring as commutative_ring71import sage.rings.field as field72import integer_mod73import sage.rings.integer as integer74import sage.rings.integer_ring as integer_ring75import sage.rings.quotient_ring as quotient_ring76from sage.structure.parent_gens import ParentWithGens7778from sage.libs.pari.all import pari, PariError7980import sage.interfaces.all81from sage.misc.cachefunc import cached_method8283from sage.structure.factory import UniqueFactory8485class IntegerModFactory(UniqueFactory):86r"""87Return the quotient ring `\ZZ / n\ZZ`.8889INPUT:9091- ``order`` -- integer (default: 0), positive or negative9293EXAMPLES::9495sage: IntegerModRing(15)96Ring of integers modulo 1597sage: IntegerModRing(7)98Ring of integers modulo 799sage: IntegerModRing(-100)100Ring of integers modulo 100101102Note that you can also use ``Integers``, which is a103synonym for ``IntegerModRing``.104105::106107sage: Integers(18)108Ring of integers modulo 18109sage: Integers() is Integers(0) is ZZ110True111"""112def create_key(self, order=0, category=None):113"""114An integer mod ring is specified uniquely by its order.115116EXAMPLES::117118sage: Zmod.create_key(7)1197120sage: Zmod.create_key(7, Fields())121(7, Category of fields)122"""123if category is None:124return order125return (order, category)126127def create_object(self, version, order):128"""129EXAMPLES::130131sage: R = Integers(10)132sage: TestSuite(R).run() # indirect doctest133"""134category=None135if isinstance(order, tuple):136order, category = order137if order < 0:138order = -order139if order == 0:140return integer_ring.IntegerRing()141else:142return IntegerModRing_generic(order,category=category)143144Zmod = Integers = IntegerModRing = IntegerModFactory("IntegerModRing")145146147def is_IntegerModRing(x):148"""149Return ``True`` if ``x`` is an integer modulo ring.150151EXAMPLES::152153sage: from sage.rings.finite_rings.integer_mod_ring import is_IntegerModRing154sage: R = IntegerModRing(17)155sage: is_IntegerModRing(R)156True157sage: is_IntegerModRing(GF(13))158True159sage: is_IntegerModRing(GF(4, 'a'))160False161sage: is_IntegerModRing(10)162False163sage: is_IntegerModRing(ZZ)164False165"""166return isinstance(x, IntegerModRing_generic)167168from sage.categories.commutative_rings import CommutativeRings169from sage.categories.finite_enumerated_sets import FiniteEnumeratedSets170from sage.categories.category import JoinCategory171default_category = JoinCategory((CommutativeRings(), FiniteEnumeratedSets()))172ZZ = integer_ring.IntegerRing()173174class IntegerModRing_generic(quotient_ring.QuotientRing_generic):175"""176The ring of integers modulo `N`, with `N` composite.177178INPUT:179180- ``order`` -- an integer181182- ``category`` -- a subcategory of ``CommutativeRings()`` (the default)183(currently only available for subclasses)184185OUTPUT:186187The ring of integers modulo `N`.188189EXAMPLES:190191First we compute with integers modulo `29`.192193::194195sage: FF = IntegerModRing(29)196sage: FF197Ring of integers modulo 29198sage: FF.category()199Join of Category of commutative rings and Category of subquotients of monoids and Category of quotients of semigroups and Category of finite enumerated sets200sage: FF.is_field()201True202sage: FF.characteristic()20329204sage: FF.order()20529206sage: gens = FF.unit_gens()207sage: a = gens[0]208sage: a2092210sage: a.is_square()211False212sage: def pow(i): return a**i213sage: [pow(i) for i in range(16)]214[1, 2, 4, 8, 16, 3, 6, 12, 24, 19, 9, 18, 7, 14, 28, 27]215216We have seen above that an integer mod ring is, by default, not217initialised as an object in the category of fields. However, one218can force it to be. Moreover, testing containment in the category219of fields my re-initialise the category of the integer mod ring::220221sage: F19 = IntegerModRing(19, category = Fields())222sage: F19.category().is_subcategory(Fields())223True224sage: F23 = IntegerModRing(23)225sage: F23.category().is_subcategory(Fields())226False227sage: F23 in Fields()228True229sage: F23.category().is_subcategory(Fields())230True231232233Next we compute with the integers modulo `16`.234235::236237sage: Z16 = IntegerModRing(16)238sage: Z16.category()239Join of Category of commutative rings and Category of subquotients of monoids and Category of quotients of semigroups and Category of finite enumerated sets240sage: Z16.is_field()241False242sage: Z16.order()24316244sage: Z16.characteristic()24516246sage: gens = Z16.unit_gens()247sage: gens248(15, 5)249sage: a = gens[0]250sage: b = gens[1]251sage: def powa(i): return a**i252sage: def powb(i): return b**i253sage: gp_exp = FF.unit_group_exponent()254sage: gp_exp25528256sage: [powa(i) for i in range(15)]257[1, 15, 1, 15, 1, 15, 1, 15, 1, 15, 1, 15, 1, 15, 1]258sage: [powb(i) for i in range(15)]259[1, 5, 9, 13, 1, 5, 9, 13, 1, 5, 9, 13, 1, 5, 9]260sage: a.multiplicative_order()2612262sage: b.multiplicative_order()2634264265Testing ideals and quotients::266267sage: Z10 = Integers(10)268sage: I = Z10.principal_ideal(0)269sage: Z10.quotient(I) == Z10270True271sage: I = Z10.principal_ideal(2)272sage: Z10.quotient(I) == Z10273False274sage: I.is_prime()275True276277::278279sage: R = IntegerModRing(97)280sage: a = R(5)281sage: a**(10^62)28261283"""284def __init__(self, order, cache=None, category=None):285"""286Create with the command ``IntegerModRing(order)``.287288TESTS::289290sage: FF = IntegerModRing(29)291sage: TestSuite(FF).run()292sage: F19 = IntegerModRing(19, category = Fields())293sage: TestSuite(F19).run()294sage: F23 = IntegerModRing(23)295sage: F23 in Fields()296True297sage: TestSuite(F23).run()298sage: Z16 = IntegerModRing(16)299sage: TestSuite(Z16).run()300sage: R = Integers(100000)301sage: TestSuite(R).run() # long time (17s on sage.math, 2011)302"""303order = ZZ(order)304if order <= 0:305raise ZeroDivisionError("order must be positive")306self.__order = order307self._pyx_order = integer_mod.NativeIntStruct(order)308if category is None:309from sage.categories.commutative_rings import CommutativeRings310from sage.categories.finite_enumerated_sets import FiniteEnumeratedSets311from sage.categories.category import Category312category = Category.join([CommutativeRings(), FiniteEnumeratedSets()])313# category = default_category314# If the category is given then we trust that is it right.315# Give the generator a 'name' to make quotients work. The316# name 'x' is used because it's also used for the ring of317# integers: see the __init__ method for IntegerRing_class in318# sage/rings/integer_ring.pyx.319quotient_ring.QuotientRing_generic.__init__(self, ZZ, ZZ.ideal(order),320names=('x',),321category=category)322# Calling ParentWithGens is not needed, the job is done in323# the quotient ring initialisation.324#ParentWithGens.__init__(self, self, category = category)325# We want that the ring is its own base ring.326self._base = self327if cache is None:328cache = order < 500329if cache:330self._precompute_table()331self._zero_element = integer_mod.IntegerMod(self, 0)332self._one_element = integer_mod.IntegerMod(self, 1)333334def _macaulay2_init_(self):335"""336EXAMPLES::337338sage: macaulay2(Integers(7)) # optional - macaulay2339ZZ340--3417342343::344345sage: macaulay2(Integers(10)) # optional - macaulay2346Traceback (most recent call last):347...348TypeError: Error evaluating Macaulay2 code.349IN:sage1=ZZ/10;350OUT:...error: ZZ/n not implemented yet for composite n351"""352return "ZZ/{}".format(self.order())353354def _axiom_init_(self):355"""356Returns a string representation of self in (Pan)Axiom.357358EXAMPLES::359360sage: Z7 = Integers(7)361sage: Z7._axiom_init_()362'IntegerMod(7)'363364sage: axiom(Z7) #optional - axiom365IntegerMod 7366367sage: fricas(Z7) #optional - fricas368IntegerMod(7)369"""370return 'IntegerMod({})'.format(self.order())371372_fricas_init_ = _axiom_init_373374def krull_dimension(self):375"""376Return the Krull dimension of ``self``.377378EXAMPLES::379380sage: Integers(18).krull_dimension()3810382"""383return integer.Integer(0)384385def is_noetherian(self):386"""387Check if ``self`` is a Noetherian ring.388389EXAMPLES::390391sage: Integers(8).is_noetherian()392True393"""394return True395396def extension(self, poly, name=None, names=None, embedding=None):397"""398Return an algebraic extension of ``self``. See399:meth:`sage.rings.ring.CommutativeRing.extension()` for more400information.401402EXAMPLES::403404sage: R.<t> = QQ[]405sage: Integers(8).extension(t^2 - 3)406Univariate Quotient Polynomial Ring in t over Ring of integers modulo 8 with modulus t^2 + 5407"""408if self.modulus() == 1:409return self410411from sage.rings.ring import CommutativeRing412return CommutativeRing.extension(self, poly, name, names, embedding)413414@cached_method415def is_prime_field(self):416"""417Return ``True`` if the order is prime.418419EXAMPLES::420421sage: Zmod(7).is_prime_field()422True423sage: Zmod(8).is_prime_field()424False425"""426return self.__order.is_prime()427428def _precompute_table(self):429"""430Computes a table of elements so that elements are unique.431432EXAMPLES::433434sage: R = Zmod(500); R._precompute_table()435sage: R(7) + R(13) is R(3) + R(17)436True437"""438self._pyx_order.precompute_table(self)439440def list_of_elements_of_multiplicative_group(self):441"""442Return a list of all invertible elements, as python ints.443444EXAMPLES::445446sage: R = Zmod(12)447sage: L = R.list_of_elements_of_multiplicative_group(); L448[1, 5, 7, 11]449sage: type(L[0])450<type 'int'>451"""452import sage.rings.fast_arith as a453if self.__order <= 46340: # todo: don't hard code454gcd = a.arith_int().gcd_int455elif self.__order <= 2147483647: # todo: don't hard code456gcd = a.arith_llong().gcd_longlong457else:458raise MemoryError("creating the list would exhaust memory")459N = self.__order460H = [i for i in range(N) if gcd(i, N) == 1]461return H462463@cached_method464def multiplicative_subgroups(self):465r"""466Return generators for each subgroup of467`(\ZZ/N\ZZ)^*`.468469EXAMPLES::470471sage: Integers(5).multiplicative_subgroups()472((2,), (4,), ())473sage: Integers(15).multiplicative_subgroups()474((11, 7), (4, 11), (8,), (11,), (14,), (7,), (4,), ())475sage: Integers(2).multiplicative_subgroups()476((),)477sage: len(Integers(341).multiplicative_subgroups())47880479480TESTS::481482sage: IntegerModRing(1).multiplicative_subgroups()483((0,),)484sage: IntegerModRing(2).multiplicative_subgroups()485((),)486sage: IntegerModRing(3).multiplicative_subgroups()487((2,), ())488"""489from sage.groups.abelian_gps.values import AbelianGroupWithValues490U = self.unit_gens()491G = AbelianGroupWithValues(U, [x.multiplicative_order() for x in U], values_group=self)492mysubs = []493for Gsub in G.subgroups():494mysubs.append(tuple( g.value() for g in Gsub.gens() ))495return tuple(mysubs)496497def is_finite(self):498"""499Return ``True`` since `\ZZ/N\ZZ` is finite for all positive `N`.500501EXAMPLES::502503sage: R = IntegerModRing(18)504sage: R.is_finite()505True506"""507return True508509@cached_method510def is_integral_domain(self, proof = True):511"""512Return ``True`` if and only if the order of ``self`` is prime.513514EXAMPLES::515516sage: Integers(389).is_integral_domain()517True518sage: Integers(389^2).is_integral_domain()519False520"""521return is_prime(self.order())522523@cached_method524def is_field(self, proof = True):525"""526Return ``True`` precisely if the order is prime.527528EXAMPLES::529530sage: R = IntegerModRing(18)531sage: R.is_field()532False533sage: FF = IntegerModRing(17)534sage: FF.is_field()535True536"""537return self.order().is_prime()538539@cached_method540def field(self):541"""542If this ring is a field, return the corresponding field as a finite543field, which may have extra functionality and structure. Otherwise,544raise a ``ValueError``.545546EXAMPLES::547548sage: R = Integers(7); R549Ring of integers modulo 7550sage: R.field()551Finite Field of size 7552sage: R = Integers(9)553sage: R.field()554Traceback (most recent call last):555...556ValueError: self must be a field557"""558try:559return self.__field560except AttributeError:561if not self.is_field():562raise ValueError("self must be a field")563import constructor564k = constructor.FiniteField(self.order())565self.__field = k566return k567568def _pseudo_fraction_field(self):569"""570If ``self`` is composite, we may still want to do division by elements571of ``self``.572573EXAMPLES::574575sage: Integers(15).fraction_field()576Traceback (most recent call last):577...578TypeError: self must be an integral domain.579sage: Integers(15)._pseudo_fraction_field()580Ring of integers modulo 15581sage: R.<x> = Integers(15)[]582sage: (x+5)/25838*x + 10584585This should be very fast::586587sage: R.<x> = Integers(next_prime(10^101)*next_prime(10^100))[]588sage: x / R.base_ring()(2)589500000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000013365000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000401*x590"""591return self592593@cached_method594def multiplicative_group_is_cyclic(self):595"""596Return ``True`` if the multiplicative group of this field is cyclic.597This is the case exactly when the order is less than 8, a power598of an odd prime, or twice a power of an odd prime.599600EXAMPLES::601602sage: R = Integers(7); R603Ring of integers modulo 7604sage: R.multiplicative_group_is_cyclic()605True606sage: R = Integers(9)607sage: R.multiplicative_group_is_cyclic()608True609sage: Integers(8).multiplicative_group_is_cyclic()610False611sage: Integers(4).multiplicative_group_is_cyclic()612True613sage: Integers(25*3).multiplicative_group_is_cyclic()614False615616We test that :trac:`5250` is fixed::617618sage: Integers(162).multiplicative_group_is_cyclic()619True620"""621n = self.order()622if n < 8:623return True624625if n % 4 == 0:626return False # know n > 7, so n=4 case not a problem627if n % 4 == 2:628n = n // 2629630return n.is_prime_power()631632@cached_method633def multiplicative_generator(self):634"""635Return a generator for the multiplicative group of this ring,636assuming the multiplicative group is cyclic.637638Use the unit_gens function to obtain generators even in the639non-cyclic case.640641EXAMPLES::642643sage: R = Integers(7); R644Ring of integers modulo 7645sage: R.multiplicative_generator()6463647sage: R = Integers(9)648sage: R.multiplicative_generator()6492650sage: Integers(8).multiplicative_generator()651Traceback (most recent call last):652...653ValueError: multiplicative group of this ring is not cyclic654sage: Integers(4).multiplicative_generator()6553656sage: Integers(25*3).multiplicative_generator()657Traceback (most recent call last):658...659ValueError: multiplicative group of this ring is not cyclic660sage: Integers(25*3).unit_gens()661(26, 52)662sage: Integers(162).unit_gens()663(83,)664"""665try:666return self.__mult_gen667except AttributeError:668if self.is_field():669a = self(self.field().multiplicative_generator())670self.__mult_gen = a671return a672if self.multiplicative_group_is_cyclic():673v = self.unit_gens()674if len(v) != 1:675raise ArithmeticError676return v[0]677678raise ValueError("multiplicative group of this ring is not cyclic")679680def quadratic_nonresidue(self):681"""682Return a quadratic non-residue in ``self``.683684EXAMPLES::685686sage: R = Integers(17)687sage: R.quadratic_nonresidue()6883689sage: R(3).is_square()690False691"""692try:693return self._nonresidue694except AttributeError:695for a in self:696if not a.is_square():697self._nonresidue = a698return a699700def square_roots_of_one(self):701"""702Return all square roots of 1 in self, i.e., all solutions to703`x^2 - 1 = 0`.704705OUTPUT:706707The square roots of 1 in ``self`` as a tuple.708709EXAMPLES::710711sage: R = Integers(2^10)712sage: [x for x in R if x^2 == 1]713[1, 511, 513, 1023]714sage: R.square_roots_of_one()715(1, 511, 513, 1023)716717::718719sage: v = Integers(9*5).square_roots_of_one(); v720(1, 19, 26, 44)721sage: [x^2 for x in v]722[1, 1, 1, 1]723sage: v = Integers(9*5*8).square_roots_of_one(); v724(1, 19, 71, 89, 91, 109, 161, 179, 181, 199, 251, 269, 271, 289, 341, 359)725sage: [x^2 for x in v]726[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]727"""728try:729return self.__square_roots_of_one730except AttributeError:731pass732n = self.__order733if n.is_prime_power():734if n % 2 == 0:735# power of 2736if n == 2:737v = [self(1)]738elif n == 4:739v = [self(1), self(3)]740else: # n >= 8741half_ord = n//2742v = [self(1), self(-1), self(half_ord-1), self(half_ord+1)]743else:744v = [self(1), self(-1)]745else:746# Reduce to the prime power case.747F = self.factored_order()748vmod = []749moduli = []750for p, e in F:751k = p**e752R = IntegerModRing(p**e)753w = [self(x) for x in R.square_roots_of_one()]754vmod.append(w)755moduli.append(k)756# Now combine in all possible ways using the CRT757from sage.rings.arith import CRT_basis758basis = CRT_basis(moduli)759from sage.misc.mrange import cartesian_product_iterator760v = []761for x in cartesian_product_iterator(vmod):762# x is a specific choice of roots modulo each prime power divisor763a = sum([basis[i]*x[i] for i in range(len(x))])764v.append(a)765#end for766#end if767768v.sort()769v = tuple(v)770self.__square_roots_of_one = v771return v772773@cached_method774def factored_order(self):775"""776EXAMPLES::777778sage: R = IntegerModRing(18)779sage: FF = IntegerModRing(17)780sage: R.factored_order()7812 * 3^2782sage: FF.factored_order()78317784"""785return factor(self.__order, int_=(self.__order < 2**31))786787def factored_unit_order(self):788"""789Return a list of :class:`Factorization` objects, each the factorization790of the order of the units in a `\ZZ / p^n \ZZ` component of this group791(using the Chinese Remainder Theorem).792793EXAMPLES::794795sage: R = Integers(8*9*25*17*29)796sage: R.factored_unit_order()797[2^2, 2 * 3, 2^2 * 5, 2^4, 2^2 * 7]798"""799ans = []800from sage.structure.factorization import Factorization801for p, e in self.factored_order():802ans.append(Factorization([(p,e-1)]) * factor(p-1, int_=(self.__order < 2**31)))803return ans804805def characteristic(self):806"""807EXAMPLES::808809sage: R = IntegerModRing(18)810sage: FF = IntegerModRing(17)811sage: FF.characteristic()81217813sage: R.characteristic()81418815"""816return self.__order817818def _repr_(self):819"""820String representation.821822EXAMPLES::823824sage: Zmod(87)825Ring of integers modulo 87826"""827return "Ring of integers modulo {}".format(self.__order)828829def _latex_(self):830r"""831Latex representation.832833EXAMPLES::834835sage: latex(Zmod(87))836\ZZ/87\ZZ837"""838return "\\ZZ/{}\\ZZ".format(self.__order)839840def modulus(self):841r"""842Return the polynomial `x - 1` over this ring.843844.. NOTE::845846This function exists for consistency with the finite-field847modulus function.848849EXAMPLES::850851sage: R = IntegerModRing(18)852sage: R.modulus()853x + 17854sage: R = IntegerModRing(17)855sage: R.modulus()856x + 16857"""858try:859return self.__modulus860except AttributeError:861x = self['x'].gen()862self.__modulus = x - 1863return self.__modulus864865def order(self):866"""867Return the order of this ring.868869EXAMPLES::870871sage: Zmod(87).order()87287873"""874return self.__order875876def cardinality(self):877"""878Return the cardinality of this ring.879880EXAMPLES::881882sage: Zmod(87).cardinality()88387884"""885return self.order()886887def _pari_order(self):888"""889Return the pari integer representing the order of this ring.890891EXAMPLES::892893sage: Zmod(87)._pari_order()89487895"""896try:897return self.__pari_order898except AttributeError:899self.__pari_order = pari(self.order())900return self.__pari_order901902def _element_constructor_(self, x):903"""904TESTS::905906sage: K2 = GF(2)907sage: K3 = GF(3)908sage: K8 = GF(8,'a')909sage: K8(5) # indirect doctest9101911sage: K8('a+1')912a + 1913sage: K8(K2(1))9141915916The following test refers to :trac:`6468`::917918sage: class foo_parent(Parent):919... pass920sage: class foo(RingElement):921... def lift(self):922... raise PariError923sage: P = foo_parent()924sage: F = foo(P)925sage: GF(2)(F)926Traceback (most recent call last):927...928TypeError: error coercing to finite field929930The following test refers to :trac:`8970`::931932sage: R = Zmod(13); a = R(2)933sage: a == R(gap(a))934True935936"""937try:938return integer_mod.IntegerMod(self, x)939except (NotImplementedError, PariError):940raise TypeError("error coercing to finite field")941except TypeError:942if sage.interfaces.all.is_GapElement(x):943from sage.interfaces.gap import intmod_gap_to_sage944try:945y = intmod_gap_to_sage(x)946return self.coerce(y)947except (ValueError, IndexError, TypeError), msg:948raise TypeError("{}\nerror coercing to finite field".format(msg))949950raise # Continue up with the original TypeError951952953def __iter__(self):954"""955EXAMPLES::956957sage: R = IntegerModRing(3)958sage: for i in R:959... print i960096119622963sage: L = [i for i in R]964sage: L[0].parent()965Ring of integers modulo 3966"""967i = 0968order = int(self.__order)969while i < order:970yield self(i)971i = i + 1972973def _coerce_map_from_(self, S):974"""975EXAMPLES::976977sage: R = Integers(15)978sage: f = R.coerce_map_from(Integers(450)); f # indirect doctest979Natural morphism:980From: Ring of integers modulo 450981To: Ring of integers modulo 15982sage: f(-1)98314984sage: f = R.coerce_map_from(int); f985Native morphism:986From: Set of Python objects of type 'int'987To: Ring of integers modulo 15988sage: f(-1r)98914990sage: f = R.coerce_map_from(ZZ); f991Natural morphism:992From: Integer Ring993To: Ring of integers modulo 15994sage: f(-1)99514996sage: f = R.coerce_map_from(Integers(10)); print f997None998sage: f = R.coerce_map_from(QQ); print f999None10001001sage: R = IntegerModRing(17)1002sage: a = R(3)1003sage: b = R._coerce_(3)1004sage: b100531006sage: a==b1007True10081009This is allowed::10101011sage: R(2/3)10121210131014But this is not, since there is no (canonical or not!) ring1015homomorphism from `\QQ` to `\GF{17}`.10161017::10181019sage: R._coerce_(2/3)1020Traceback (most recent call last):1021...1022TypeError: no canonical coercion from Rational Field to Ring of integers modulo 1710231024We do not allow the coercion ``GF(p) -> Z/pZ``, because in case of a1025canonical isomorphism, there is a coercion map in only one1026direction, i.e., to the object in the smaller category.1027"""1028if S is int:1029return integer_mod.Int_to_IntegerMod(self)1030elif S is integer_ring.ZZ:1031return integer_mod.Integer_to_IntegerMod(self)1032elif isinstance(S, IntegerModRing_generic):1033if isinstance(S, field.Field):1034return None1035try:1036return integer_mod.IntegerMod_to_IntegerMod(S, self)1037except TypeError:1038pass1039to_ZZ = integer_ring.ZZ.coerce_map_from(S)1040if to_ZZ is not None:1041return integer_mod.Integer_to_IntegerMod(self) * to_ZZ10421043def __cmp__(self, other):1044"""1045EXAMPLES::10461047sage: Z11 = IntegerModRing(11); Z111048Ring of integers modulo 111049sage: Z12 = IntegerModRing(12); Z121050Ring of integers modulo 121051sage: Z13 = IntegerModRing(13); Z131052Ring of integers modulo 131053sage: F = GF(11); F1054Finite Field of size 111055sage: Z11 == Z11, Z11 == Z12, Z11 == Z13, Z11 == F1056(True, False, False, False)1057"""1058if type(other) is not type(self): # so that GF(p) =/= Z/pZ1059return cmp(type(self), type(other))1060return cmp(self.__order, other.__order)10611062# The following __unit_gens functions are here since I just factored1063# them out from the unit_gens function. They are only called by1064# the unit_gens function.1065def __unit_gens_primecase(self, p):1066"""1067Assuming the modulus is prime, returns the smallest generator1068of the group of units.10691070EXAMPLES::10711072sage: Zmod(17)._IntegerModRing_generic__unit_gens_primecase(17)107331074"""1075if p == 2:1076return integer_mod.Mod(1,p)1077P = prime_divisors(p-1)1078ord = integer.Integer(p-1)1079one = integer_mod.Mod(1,p)1080x = 21081while x < p:1082generator = True1083z = integer_mod.Mod(x,p)1084for q in P:1085if z**(ord//q) == one:1086generator = False1087break1088if generator:1089return z1090x += 11091#end for1092raise ValueError("didn't find primitive root for p={}".format(p))10931094def __unit_gens_primepowercase(self, p, r):1095r"""1096Find smallest generator for1097`(\ZZ/p^r\ZZ)^*`.10981099EXAMPLES::11001101sage: Zmod(27)._IntegerModRing_generic__unit_gens_primepowercase(3,3)1102[2]1103"""1104if r == 1:1105return [self.__unit_gens_primecase(p)]11061107if p == 2:1108if r < 1:1109raise ValueError("p=2, r={} should be >=1".format(r))1110if r == 1:1111return []1112if r == 2:1113return [integer_mod.Mod(-1,2**r)]11141115pr=2**r1116a = integer_mod.Mod(5, pr)1117return [integer_mod.Mod(-1,pr), a]11181119# odd prime1120pr = p**r1121R = IntegerModRing(pr)1122x = R(self.__unit_gens_primecase(p).lift())1123n = p**(r-2)*(p-1)1124one = integer_mod.Mod(1,pr)1125for b in range(0,p):1126z = x+R(b*p)1127if z**n != one:1128a = integer_mod.Mod(z,pr)1129return [a]1130raise ValueError("p={}, r={}, couldn't find generator".format(p,r))11311132@cached_method1133def unit_gens(self):1134r"""1135Returns generators for the unit group `(\ZZ/N\ZZ)^*`.11361137We compute the list of generators using a deterministic algorithm, so1138the generators list will always be the same. For each odd prime divisor1139of `N` there will be exactly one corresponding generator; if `N` is1140even there will be 0, 1 or 2 generators according to whether 2 divides1141`N` to order 1, 2 or `\geq 3`.11421143OUTPUT:11441145A tuple containing the units of ``self``.11461147EXAMPLES::11481149sage: R = IntegerModRing(18)1150sage: R.unit_gens()1151(11,)1152sage: R = IntegerModRing(17)1153sage: R.unit_gens()1154(3,)1155sage: IntegerModRing(next_prime(10^30)).unit_gens()1156(5,)11571158TESTS::11591160sage: IntegerModRing(2).unit_gens()1161()1162sage: IntegerModRing(4).unit_gens()1163(3,)1164sage: IntegerModRing(8).unit_gens()1165(7, 5)1166"""1167n = self.__order1168if n == 1:1169return (self(1),)1170unit_gens = []1171for p,r in self.factored_order():1172m = n/(p**r)1173for g in self.__unit_gens_primepowercase(p, r):1174x = g.crt(integer_mod.Mod(1,m))1175if x != 1:1176unit_gens.append(x)1177return tuple(unit_gens)11781179@cached_method1180def unit_group_exponent(self):1181"""1182EXAMPLES::11831184sage: R = IntegerModRing(17)1185sage: R.unit_group_exponent()1186161187sage: R = IntegerModRing(18)1188sage: R.unit_group_exponent()118961190"""1191a = []1192for p, r in self.factored_order():1193if p != 2:1194a.append((p-1)*(p**(r-1))) # phi(p**r)1195elif r==2: # p=2 from this point on1196a.append(2)1197elif r>2:1198a.append(2**(r-2))1199return int(LCM(a))12001201def unit_group_order(self):1202"""1203Return the order of the unit group of this residue class ring.12041205EXAMPLES::12061207sage: R = Integers(500)1208sage: R.unit_group_order()12092001210"""1211return euler_phi(self.order())12121213def random_element(self, bound=None):1214"""1215Return a random element of this ring.12161217If ``bound`` is not ``None``, return the coercion of an integer in the1218interval ``[-bound, bound]`` into this ring.12191220EXAMPLES::12211222sage: R = IntegerModRing(18)1223sage: R.random_element()122421225"""1226if not (bound is None):1227return commutative_ring.CommutativeRing.random_element(self, bound)1228a = random.randint(0,self.order()-1)1229return self(a)12301231#######################################################1232# Suppose for interfaces1233#######################################################1234def _gap_init_(self):1235"""1236EXAMPLES::12371238sage: R = Integers(12345678900)1239sage: R1240Ring of integers modulo 123456789001241sage: gap(R) # indirect doctest1242(Integers mod 12345678900)1243"""1244return 'ZmodnZ({})'.format(self.order())12451246def _magma_init_(self, magma):1247"""1248EXAMPLES::12491250sage: R = Integers(12345678900)1251sage: R1252Ring of integers modulo 123456789001253sage: magma(R) # indirect doctest, optional - magma1254Residue class ring of integers modulo 123456789001255"""1256return 'Integers({})'.format(self.order())12571258def degree(self):1259"""1260Return 1.12611262EXAMPLE::12631264sage: R = Integers(12345678900)1265sage: R.degree()126611267"""1268return integer.Integer(1)12691270Zmod = IntegerModRing1271Integers = IntegerModRing12721273# Register unpickling methods for backward compatibility.12741275from sage.structure.sage_object import register_unpickle_override1276register_unpickle_override('sage.rings.integer_mod_ring', 'IntegerModRing_generic', IntegerModRing_generic)12771278## def GF(p):1279## """1280## EXAMPLES:1281## sage: F = GF(11)1282## sage: F1283## Finite field of size 111284## """1285## if not arith.is_prime(p):1286## raise NotImplementedError("only prime fields currently implemented")1287## return IntegerModRing(p)12881289def crt(v):1290"""1291INPUT:12921293- ``v`` -- (list) a lift of elements of ``rings.IntegerMod(n)``, for1294various coprime moduli ``n``12951296EXAMPLES::12971298sage: from sage.rings.finite_rings.integer_mod_ring import crt1299sage: crt([mod(3, 8),mod(1,19),mod(7, 15)])130010271301"""1302if len(v) == 0:1303return IntegerModRing(1)(1)1304x = v[0]1305for i in range(1,len(v)):1306x = x.crt(v[i])1307return x1308130913101311