Path: blob/master/src/sage/rings/finite_rings/integer_mod.pyx
8820 views
r"""1Elements of `\ZZ/n\ZZ`23An element of the integers modulo `n`.45There are three types of integer_mod classes, depending on the6size of the modulus.789- ``IntegerMod_int`` stores its value in a10``int_fast32_t`` (typically an ``int``);11this is used if the modulus is less than12`\sqrt{2^{31}-1}`.1314- ``IntegerMod_int64`` stores its value in a15``int_fast64_t`` (typically a ``long16long``); this is used if the modulus is less than17`2^{31}-1`.1819- ``IntegerMod_gmp`` stores its value in a20``mpz_t``; this can be used for an arbitrarily large21modulus.222324All extend ``IntegerMod_abstract``.2526For efficiency reasons, it stores the modulus (in all three forms,27if possible) in a common (cdef) class28``NativeIntStruct`` rather than in the parent.2930AUTHORS:3132- Robert Bradshaw: most of the work3334- Didier Deshommes: bit shifting3536- William Stein: editing and polishing; new arith architecture3738- Robert Bradshaw: implement native is_square and square_root3940- William Stein: sqrt4142- Maarten Derickx: moved the valuation code from the global43valuation function to here444546TESTS::4748sage: R = Integers(101^3)49sage: a = R(824362); b = R(205942)50sage: a * b518511275253sage: type(IntegerModRing(2^31-1).an_element())54<type 'sage.rings.finite_rings.integer_mod.IntegerMod_int64'>55sage: type(IntegerModRing(2^31).an_element())56<type 'sage.rings.finite_rings.integer_mod.IntegerMod_gmp'>57"""5859#################################################################################60# Copyright (C) 2006 Robert Bradshaw <[email protected]>61# 2006 William Stein <[email protected]>62#63# Distributed under the terms of the GNU General Public License (GPL)64#65# http://www.gnu.org/licenses/66#*****************************************************************************676869include "sage/ext/interrupt.pxi" # ctrl-c interrupt block support70include "sage/ext/stdsage.pxi"7172from cpython.int cimport *73from cpython.list cimport *74from cpython.ref cimport *7576cdef extern from "math.h":77double log(double)78int ceil(double)7980cdef extern from "mpz_pylong.h":81cdef mpz_get_pyintlong(mpz_t src)8283import operator8485cdef bint use_32bit_type(int_fast64_t modulus):86return modulus <= INTEGER_MOD_INT32_LIMIT8788## import arith89import sage.rings.rational as rational90from sage.libs.pari.all import pari, PariError91import sage.rings.integer_ring as integer_ring9293import sage.rings.commutative_ring_element as commutative_ring_element94import sage.interfaces.all9596import sage.rings.integer97import sage.rings.integer_ring98cimport sage.rings.integer99from sage.rings.integer cimport Integer100101import sage.structure.element102cimport sage.structure.element103coerce_binop = sage.structure.element.coerce_binop104from sage.structure.element cimport RingElement, ModuleElement, Element105from sage.categories.morphism cimport Morphism106from sage.categories.map cimport Map107108from sage.structure.sage_object import register_unpickle_override109110#from sage.structure.parent cimport Parent111112cdef Integer one_Z = Integer(1)113114def Mod(n, m, parent=None):115"""116Return the equivalence class of `n` modulo `m` as117an element of `\ZZ/m\ZZ`.118119EXAMPLES::120121sage: x = Mod(12345678, 32098203845329048)122sage: x12312345678124sage: x^1001251017322209155072126127You can also use the lowercase version::128129sage: mod(12,5)1302131132Illustrates that trac #5971 is fixed. Consider `n` modulo `m` when133`m = 0`. Then `\ZZ/0\ZZ` is isomorphic to `\ZZ` so `n` modulo `0` is134is equivalent to `n` for any integer value of `n`::135136sage: Mod(10, 0)13710138sage: a = randint(-100, 100)139sage: Mod(a, 0) == a140True141"""142# when m is zero, then ZZ/0ZZ is isomorphic to ZZ143if m == 0:144return n145146# m is non-zero, so return n mod m147cdef IntegerMod_abstract x148import integer_mod_ring149x = IntegerMod(integer_mod_ring.IntegerModRing(m), n)150if parent is None:151return x152x._parent = parent153return x154155156mod = Mod157158register_unpickle_override('sage.rings.integer_mod', 'Mod', Mod)159register_unpickle_override('sage.rings.integer_mod', 'mod', mod)160161def IntegerMod(parent, value):162"""163Create an integer modulo `n` with the given parent.164165This is mainly for internal use.166"""167cdef NativeIntStruct modulus168cdef Py_ssize_t res169modulus = parent._pyx_order170if modulus.table is not None:171if PY_TYPE_CHECK(value, sage.rings.integer.Integer) or PY_TYPE_CHECK(value, int) or PY_TYPE_CHECK(value, long):172res = value % modulus.int64173if res < 0:174res = res + modulus.int64175a = modulus.lookup(res)176if (<Element>a)._parent is not parent:177(<Element>a)._parent = parent178# print (<Element>a)._parent, " is not ", parent179return a180if modulus.int32 != -1:181return IntegerMod_int(parent, value)182elif modulus.int64 != -1:183return IntegerMod_int64(parent, value)184else:185return IntegerMod_gmp(parent, value)186187def is_IntegerMod(x):188"""189Return ``True`` if and only if x is an integer modulo190`n`.191192EXAMPLES::193194sage: from sage.rings.finite_rings.integer_mod import is_IntegerMod195sage: is_IntegerMod(5)196False197sage: is_IntegerMod(Mod(5,10))198True199"""200return PY_TYPE_CHECK(x, IntegerMod_abstract)201202def makeNativeIntStruct(sage.rings.integer.Integer z):203"""204Function to convert a Sage Integer into class NativeIntStruct.205206.. note::207208This function is only used for the unpickle override below.209"""210return NativeIntStruct(z)211212register_unpickle_override('sage.rings.integer_mod', 'makeNativeIntStruct', makeNativeIntStruct)213214cdef class NativeIntStruct:215"""216We store the various forms of the modulus here rather than in the217parent for efficiency reasons.218219We may also store a cached table of all elements of a given ring in220this class.221"""222def __init__(NativeIntStruct self, sage.rings.integer.Integer z):223self.int64 = -1224self.int32 = -1225self.table = None # NULL226self.sageInteger = z227if mpz_cmp_si(z.value, INTEGER_MOD_INT64_LIMIT) <= 0:228self.int64 = mpz_get_si(z.value)229if use_32bit_type(self.int64):230self.int32 = self.int64231232def __reduce__(NativeIntStruct self):233return sage.rings.finite_rings.integer_mod.makeNativeIntStruct, (self.sageInteger, )234235def precompute_table(NativeIntStruct self, parent, inverses=True):236"""237Function to compute and cache all elements of this class.238239If ``inverses == True``, also computes and caches the inverses240of the invertible elements.241242EXAMPLES:243244This is used by the :class:`sage.rings.finite_rings.integer_mod_ring.IntegerModRing_generic` constructor::245246sage: from sage.rings.finite_rings.integer_mod_ring import IntegerModRing_generic247sage: R = IntegerModRing_generic(39, cache=False)248sage: R(5)^-12498250sage: R(5)^-1 is R(8)251False252sage: R = IntegerModRing_generic(39, cache=True) # indirect doctest253sage: R(5)^-1 is R(8)254True255256Check that the inverse of 0 modulo 1 works, see :trac:`13639`::257258sage: R = IntegerModRing_generic(1, cache=True) # indirect doctest259sage: R(0)^-1 is R(0)260True261"""262self.table = PyList_New(self.int64)263cdef Py_ssize_t i264if self.int32 != -1:265for i from 0 <= i < self.int32:266z = IntegerMod_int(parent, i)267Py_INCREF(z); PyList_SET_ITEM(self.table, i, z)268else:269for i from 0 <= i < self.int64:270z = IntegerMod_int64(parent, i)271Py_INCREF(z); PyList_SET_ITEM(self.table, i, z)272273if inverses:274if self.int64 == 1:275# Special case for integers modulo 1276self.inverses = self.table277else:278tmp = [None] * self.int64279for i from 1 <= i < self.int64:280try:281tmp[i] = ~self.table[i]282except ZeroDivisionError:283pass284self.inverses = tmp285286def _get_table(self):287return self.table288289cdef lookup(NativeIntStruct self, Py_ssize_t value):290return <object>PyList_GET_ITEM(self.table, value)291292293cdef class IntegerMod_abstract(FiniteRingElement):294295def __init__(self, parent):296"""297EXAMPLES::298299sage: a = Mod(10,30^10); a30010301sage: loads(a.dumps()) == a302True303"""304self._parent = parent305self.__modulus = parent._pyx_order306307308cdef _new_c_from_long(self, long value):309cdef IntegerMod_abstract x310x = <IntegerMod_abstract>PY_NEW(<object>PY_TYPE(self))311if PY_TYPE_CHECK(x, IntegerMod_gmp):312mpz_init((<IntegerMod_gmp>x).value) # should be done by the new method313x._parent = self._parent314x.__modulus = self.__modulus315x.set_from_long(value)316return x317318cdef void set_from_mpz(self, mpz_t value):319raise NotImplementedError, "Must be defined in child class."320321cdef void set_from_long(self, long value):322raise NotImplementedError, "Must be defined in child class."323324def __abs__(self):325"""326Raise an error message, since ``abs(x)`` makes no sense327when ``x`` is an integer modulo `n`.328329EXAMPLES::330331sage: abs(Mod(2,3))332Traceback (most recent call last):333...334ArithmeticError: absolute valued not defined on integers modulo n.335"""336raise ArithmeticError, "absolute valued not defined on integers modulo n."337338def __reduce__(IntegerMod_abstract self):339"""340EXAMPLES::341342sage: a = Mod(4,5); a3434344sage: loads(a.dumps()) == a345True346sage: a = Mod(-1,5^30)^25;347sage: loads(a.dumps()) == a348True349"""350return sage.rings.finite_rings.integer_mod.mod, (self.lift(), self.modulus(), self.parent())351352def is_nilpotent(self):353r"""354Return ``True`` if ``self`` is nilpotent,355i.e., some power of ``self`` is zero.356357EXAMPLES::358359sage: a = Integers(90384098234^3)360sage: factor(a.order())3612^3 * 191^3 * 236607587^3362sage: b = a(2*191)363sage: b.is_nilpotent()364False365sage: b = a(2*191*236607587)366sage: b.is_nilpotent()367True368369ALGORITHM: Let `m \geq \log_2(n)`, where `n` is370the modulus. Then `x \in \ZZ/n\ZZ` is371nilpotent if and only if `x^m = 0`.372373PROOF: This is clear if you reduce to the prime power case, which374you can do via the Chinese Remainder Theorem.375376We could alternatively factor `n` and check to see if the377prime divisors of `n` all divide `x`. This is378asymptotically slower :-).379"""380if self.is_zero():381return True382m = self.__modulus.sageInteger.exact_log(2) + 1383return (self**m).is_zero()384385#################################################################386# Interfaces387#################################################################388def _pari_init_(self):389return 'Mod(%s,%s)'%(str(self), self.__modulus.sageInteger)390391def _pari_(self):392return self.lift()._pari_().Mod(self.__modulus.sageInteger)393394def _gap_init_(self):395r"""396Return string representation of corresponding GAP object.397398EXAMPLES::399400sage: a = Mod(2,19)401sage: gap(a)402Z(19)403sage: gap(Mod(3, next_prime(10000)))404Z(10007)^6190405sage: gap(Mod(3, next_prime(100000)))406ZmodpZObj( 3, 100003 )407sage: gap(Mod(4, 48))408ZmodnZObj( 4, 48 )409"""410return '%s*One(ZmodnZ(%s))' % (self, self.__modulus.sageInteger)411412def _magma_init_(self, magma):413"""414Coercion to Magma.415416EXAMPLES::417418sage: a = Integers(15)(4)419sage: b = magma(a) # optional - magma420sage: b.Type() # optional - magma421RngIntResElt422sage: b^2 # optional - magma4231424"""425return '%s!%s'%(self.parent()._magma_init_(magma), self)426427def _axiom_init_(self):428"""429Return a string representation of the corresponding to430(Pan)Axiom object.431432EXAMPLES::433434sage: a = Integers(15)(4)435sage: a._axiom_init_()436'4 :: IntegerMod(15)'437438sage: aa = axiom(a); aa #optional - axiom4394440sage: aa.type() #optional - axiom441IntegerMod 15442443sage: aa = fricas(a); aa #optional - fricas4444445sage: aa.type() #optional - fricas446IntegerMod(15)447448"""449return '%s :: %s'%(self, self.parent()._axiom_init_())450451_fricas_init_ = _axiom_init_452453def _sage_input_(self, sib, coerced):454r"""455Produce an expression which will reproduce this value when456evaluated.457458EXAMPLES::459460sage: K = GF(7)461sage: sage_input(K(5), verify=True)462# Verified463GF(7)(5)464sage: sage_input(K(5) * polygen(K), verify=True)465# Verified466R.<x> = GF(7)[]4675*x468sage: from sage.misc.sage_input import SageInputBuilder469sage: K(5)._sage_input_(SageInputBuilder(), False)470{call: {call: {atomic:GF}({atomic:7})}({atomic:5})}471sage: K(5)._sage_input_(SageInputBuilder(), True)472{atomic:5}473"""474v = sib.int(self.lift())475if coerced:476return v477else:478return sib(self.parent())(v)479480def log(self, b=None):481r"""482Return an integer `x` such that `b^x = a`, where483`a` is ``self``.484485INPUT:486487488- ``self`` - unit modulo `n`489490- ``b`` - a unit modulo `n`. If ``b`` is not given,491``R.multiplicative_generator()`` is used, where492``R`` is the parent of ``self``.493494495OUTPUT: Integer `x` such that `b^x = a`, if this exists; a ValueError otherwise.496497.. note::498499If the modulus is prime and b is a generator, this calls Pari's ``znlog``500function, which is rather fast. If not, it falls back on the generic501discrete log implementation in :meth:`sage.groups.generic.discrete_log`.502503EXAMPLES::504505sage: r = Integers(125)506sage: b = r.multiplicative_generator()^3507sage: a = b^17508sage: a.log(b)50917510sage: a.log()51151512513A bigger example::514515sage: FF = FiniteField(2^32+61)516sage: c = FF(4294967356)517sage: x = FF(2)518sage: a = c.log(x)519sage: a5202147483678521sage: x^a5224294967356523524Things that can go wrong. E.g., if the base is not a generator for525the multiplicative group, or not even a unit.526527::528529sage: Mod(3, 7).log(Mod(2, 7))530Traceback (most recent call last):531...532ValueError: No discrete log of 3 found to base 2533sage: a = Mod(16, 100); b = Mod(4,100)534sage: a.log(b)535Traceback (most recent call last):536...537ZeroDivisionError: Inverse does not exist.538539We check that #9205 is fixed::540541sage: Mod(5,9).log(Mod(2, 9))5425543544We test against a bug (side effect on PARI) fixed in #9438::545546sage: R.<a, b> = QQ[]547sage: pari(b)548b549sage: GF(7)(5).log()5505551sage: pari(b)552b553554AUTHORS:555556- David Joyner and William Stein (2005-11)557558- William Stein (2007-01-27): update to use PARI as requested559by David Kohel.560561- Simon King (2010-07-07): fix a side effect on PARI562"""563if b is None:564b = self._parent.multiplicative_generator()565else:566b = self._parent(b)567568if self.modulus().is_prime() and b.multiplicative_order() == b.parent().unit_group_order():569570# use PARI571572cmd = 'if(znorder(Mod(%s,%s))!=eulerphi(%s),-1,znlog(%s,Mod(%s,%s)))'%(b, self.__modulus.sageInteger,573self.__modulus.sageInteger,574self, b, self.__modulus.sageInteger)575try:576n = Integer(pari(cmd))577return n578except PariError, msg:579raise ValueError, "%s\nPARI failed to compute discrete log (perhaps base is not a generator or is too large)"%msg580581else: # fall back on slower native implementation582583from sage.groups.generic import discrete_log584return discrete_log(self, b)585586def generalised_log(self):587r"""588Return integers `n_i` such that589590..math::591592\prod_i x_i^{n_i} = \text{self},593594where `x_1, \dots, x_d` are the generators of the unit group595returned by ``self.parent().unit_gens()``. See also :meth:`log`.596597EXAMPLES::598599sage: m = Mod(3, 1568)600sage: v = m.generalised_log(); v601[1, 3, 1]602sage: prod([Zmod(1568).unit_gens()[i] ** v[i] for i in [0..2]])6033604605"""606if not self.is_unit():607raise ZeroDivisionError608N = self.modulus()609h = []610for (p, c) in N.factor():611if p != 2 or (p == 2 and c == 2):612h.append((self % p**c).log())613elif c > 2:614m = self % p**c615if m % 4 == 1:616h.append(0)617else:618h.append(1)619m *= -1620h.append(m.log(5))621return h622623def modulus(IntegerMod_abstract self):624"""625EXAMPLES::626627sage: Mod(3,17).modulus()62817629"""630return self.__modulus.sageInteger631632def charpoly(self, var='x'):633"""634Returns the characteristic polynomial of this element.635636EXAMPLES::637638sage: k = GF(3)639sage: a = k.gen()640sage: a.charpoly('x')641x + 2642sage: a + 26430644645AUTHORS:646647- Craig Citro648"""649R = self.parent()[var]650return R([-self,1])651652def minpoly(self, var='x'):653"""654Returns the minimal polynomial of this element.655656EXAMPLES:657sage: GF(241, 'a')(1).minpoly()658x + 240659"""660return self.charpoly(var)661662def minimal_polynomial(self, var='x'):663"""664Returns the minimal polynomial of this element.665666EXAMPLES:667sage: GF(241, 'a')(1).minimal_polynomial(var = 'z')668z + 240669"""670return self.minpoly(var)671672def polynomial(self, var='x'):673"""674Returns a constant polynomial representing this value.675676EXAMPLES::677678sage: k = GF(7)679sage: a = k.gen(); a6801681sage: a.polynomial()6821683sage: type(a.polynomial())684<type 'sage.rings.polynomial.polynomial_zmod_flint.Polynomial_zmod_flint'>685"""686R = self.parent()[var]687return R(self)688689def norm(self):690"""691Returns the norm of this element, which is itself. (This is here692for compatibility with higher order finite fields.)693694EXAMPLES::695696sage: k = GF(691)697sage: a = k(389)698sage: a.norm()699389700701AUTHORS:702703- Craig Citro704"""705return self706707def trace(self):708"""709Returns the trace of this element, which is itself. (This is here710for compatibility with higher order finite fields.)711712EXAMPLES::713714sage: k = GF(691)715sage: a = k(389)716sage: a.trace()717389718719AUTHORS:720721- Craig Citro722"""723return self724725def centerlift(self):726r"""727Lift ``self`` to an integer `i` such that `n/2 < i <= n/2`728(where `n` denotes the modulus).729730EXAMPLES::731732sage: Mod(0,5).centerlift()7330734sage: Mod(1,5).centerlift()7351736sage: Mod(2,5).centerlift()7372738sage: Mod(3,5).centerlift()739-2740sage: Mod(4,5).centerlift()741-1742sage: Mod(50,100).centerlift()74350744sage: Mod(51,100).centerlift()745-49746sage: Mod(-1,3^100).centerlift()747-1748"""749n = self.modulus()750x = self.lift()751if 2*x <= n:752return x753else:754return x - n755756cpdef bint is_one(self):757raise NotImplementedError758759cpdef bint is_unit(self):760raise NotImplementedError761762def is_square(self):763r"""764EXAMPLES::765766sage: Mod(3,17).is_square()767False768sage: Mod(9,17).is_square()769True770sage: Mod(9,17*19^2).is_square()771True772sage: Mod(-1,17^30).is_square()773True774sage: Mod(1/9, next_prime(2^40)).is_square()775True776sage: Mod(1/25, next_prime(2^90)).is_square()777True778779TESTS::780781sage: Mod(1/25, 2^8).is_square()782True783sage: Mod(1/25, 2^40).is_square()784True785786sage: for p,q,r in cartesian_product_iterator([[3,5],[11,13],[17,19]]): # long time787....: for ep,eq,er in cartesian_product_iterator([[0,1,2,3],[0,1,2,3],[0,1,2,3]]):788....: for e2 in [0, 1, 2, 3, 4]:789....: n = p^ep * q^eq * r^er * 2^e2790....: for _ in range(2):791....: a = Zmod(n).random_element()792....: if a.is_square().__xor__(a._pari_().issquare()):793....: print a, n794795ALGORITHM: Calculate the Jacobi symbol796`(\mathtt{self}/p)` at each prime `p`797dividing `n`. It must be 1 or 0 for each prime, and if it798is 0 mod `p`, where `p^k || n`, then799`ord_p(\mathtt{self})` must be even or greater than800`k`.801802The case `p = 2` is handled separately.803804AUTHORS:805806- Robert Bradshaw807"""808return self.is_square_c()809810cdef bint is_square_c(self) except -2:811cdef int l2, m2812if self.is_zero() or self.is_one():813return 1814# We first try to rule out self being a square without815# factoring the modulus.816lift = self.lift()817m2, modd = self.modulus().val_unit(2)818if m2 == 2:819if lift & 2 == 2: # lift = 2 or 3 (mod 4)820return 0821elif m2 > 2:822l2, lodd = lift.val_unit(2)823if l2 < m2 and (l2 % 2 == 1 or lodd % (1 << min(3, m2 - l2)) != 1):824return 0825# self is a square modulo 2^m2. We compute the Jacobi symbol826# modulo modd. If this is -1, then self is not a square.827if lift.jacobi(modd) == -1:828return 0829# We need to factor the modulus. We do it here instead of830# letting PARI do it, so that we can cache the factorisation.831return lift._pari_().Zn_issquare(self._parent.factored_order()._pari_())832833def sqrt(self, extend=True, all=False):834r"""835Returns square root or square roots of ``self`` modulo836`n`.837838INPUT:839840841- ``extend`` - bool (default: ``True``);842if ``True``, return a square root in an extension ring,843if necessary. Otherwise, raise a ``ValueError`` if the844square root is not in the base ring.845846- ``all`` - bool (default: ``False``); if847``True``, return {all} square roots of self, instead of848just one.849850851ALGORITHM: Calculates the square roots mod `p` for each of852the primes `p` dividing the order of the ring, then lifts853them `p`-adically and uses the CRT to find a square root854mod `n`.855856See also ``square_root_mod_prime_power`` and857``square_root_mod_prime`` (in this module) for more858algorithmic details.859860EXAMPLES::861862sage: mod(-1, 17).sqrt()8634864sage: mod(5, 389).sqrt()86586866sage: mod(7, 18).sqrt()8675868sage: a = mod(14, 5^60).sqrt()869sage: a*a87014871sage: mod(15, 389).sqrt(extend=False)872Traceback (most recent call last):873...874ValueError: self must be a square875sage: Mod(1/9, next_prime(2^40)).sqrt()^(-2)8769877sage: Mod(1/25, next_prime(2^90)).sqrt()^(-2)87825879880::881882sage: a = Mod(3,5); a8833884sage: x = Mod(-1, 360)885sage: x.sqrt(extend=False)886Traceback (most recent call last):887...888ValueError: self must be a square889sage: y = x.sqrt(); y890sqrt359891sage: y.parent()892Univariate Quotient Polynomial Ring in sqrt359 over Ring of integers modulo 360 with modulus x^2 + 1893sage: y^2894359895896We compute all square roots in several cases::897898sage: R = Integers(5*2^3*3^2); R899Ring of integers modulo 360900sage: R(40).sqrt(all=True)901[20, 160, 200, 340]902sage: [x for x in R if x^2 == 40] # Brute force verification903[20, 160, 200, 340]904sage: R(1).sqrt(all=True)905[1, 19, 71, 89, 91, 109, 161, 179, 181, 199, 251, 269, 271, 289, 341, 359]906sage: R(0).sqrt(all=True)907[0, 60, 120, 180, 240, 300]908909::910911sage: R = Integers(5*13^3*37); R912Ring of integers modulo 406445913sage: v = R(-1).sqrt(all=True); v914[78853, 111808, 160142, 193097, 213348, 246303, 294637, 327592]915sage: [x^2 for x in v]916[406444, 406444, 406444, 406444, 406444, 406444, 406444, 406444]917sage: v = R(169).sqrt(all=True); min(v), -max(v), len(v)918(13, 13, 104)919sage: all([x^2==169 for x in v])920True921922::923924sage: t = FiniteField(next_prime(2^100))(4)925sage: t.sqrt(extend = False, all = True)926[2, 1267650600228229401496703205651]927sage: t = FiniteField(next_prime(2^100))(2)928sage: t.sqrt(extend = False, all = True)929[]930931Modulo a power of 2::932933sage: R = Integers(2^7); R934Ring of integers modulo 128935sage: a = R(17)936sage: a.sqrt()93723938sage: a.sqrt(all=True)939[23, 41, 87, 105]940sage: [x for x in R if x^2==17]941[23, 41, 87, 105]942"""943if self.is_one():944if all:945return list(self.parent().square_roots_of_one())946else:947return self948949if not self.is_square_c():950if extend:951y = 'sqrt%s'%self952R = self.parent()['x']953modulus = R.gen()**2 - R(self)954if self._parent.is_field():955import constructor956Q = constructor.FiniteField(self.__modulus.sageInteger**2, y, modulus)957else:958R = self.parent()['x']959Q = R.quotient(modulus, names=(y,))960z = Q.gen()961if all:962# TODO963raise NotImplementedError964return z965if all:966return []967raise ValueError, "self must be a square"968969F = self._parent.factored_order()970cdef long e, exp, val971if len(F) == 1:972p, e = F[0]973974if all and e > 1 and not self.is_unit():975if self.is_zero():976# All multiples of p^ciel(e/2) vanish977return [self._parent(x) for x in xrange(0, self.__modulus.sageInteger, p**((e+1)/2))]978else:979z = self.lift()980val = z.valuation(p)/2 # square => valuation is even981from sage.rings.finite_rings.integer_mod_ring import IntegerModRing982# Find the unit part (mod the ring with appropriate precision)983u = IntegerModRing(p**(e-val))(z // p**(2*val))984# will add multiples of p^exp985exp = e - val986if p == 2:987exp -= 1 # note the factor of 2 below988if 2*exp < e:989exp = (e+1)/2990# For all a^2 = u and all integers b991# (a*p^val + b*p^exp) ^ 2992# = u*p^(2*val) + 2*a*b*p^(val+exp) + b^2*p^(2*exp)993# = u*p^(2*val) mod p^e994# whenever min(val+exp, 2*exp) > e995p_val = p**val996p_exp = p**exp997w = [self._parent(a.lift() * p_val + b)998for a in u.sqrt(all=True)999for b in xrange(0, self.__modulus.sageInteger, p_exp)]1000if p == 2:1001w = list(set(w))1002w.sort()1003return w10041005if e > 1:1006x = square_root_mod_prime_power(mod(self, p**e), p, e)1007else:1008x = square_root_mod_prime(self, p)1009x = x._balanced_abs()10101011if not all:1012return x10131014v = list(set([x*a for a in self._parent.square_roots_of_one()]))1015v.sort()1016return v10171018else:1019if not all:1020# Use CRT to combine together a square root modulo each prime power1021sqrts = [square_root_mod_prime(mod(self, p), p) for p, e in F if e == 1] + \1022[square_root_mod_prime_power(mod(self, p**e), p, e) for p, e in F if e != 1]10231024x = sqrts.pop()1025for y in sqrts:1026x = x.crt(y)1027return x._balanced_abs()1028else:1029# Use CRT to combine together all square roots modulo each prime power1030vmod = []1031moduli = []1032P = self.parent()1033from sage.rings.finite_rings.integer_mod_ring import IntegerModRing1034for p, e in F:1035k = p**e1036R = IntegerModRing(p**e)1037w = [P(x) for x in R(self).sqrt(all=True)]1038vmod.append(w)1039moduli.append(k)1040# Now combine in all possible ways using the CRT1041from sage.rings.arith import CRT_basis1042basis = CRT_basis(moduli)1043from sage.misc.mrange import cartesian_product_iterator1044v = []1045for x in cartesian_product_iterator(vmod):1046# x is a specific choice of roots modulo each prime power divisor1047a = sum([basis[i]*x[i] for i in range(len(x))])1048v.append(a)1049v.sort()1050return v10511052square_root = sqrt10531054def nth_root(self, n, extend = False, all = False, algorithm = None, cunningham = False):1055r"""1056Returns an `n`\th root of ``self``.10571058INPUT:10591060- ``n`` - integer `\geq 1`10611062- ``extend`` - bool (default: True); if True, return an nth1063root in an extension ring, if necessary. Otherwise, raise a1064ValueError if the root is not in the base ring. Warning:1065this option is not implemented!10661067- ``all`` - bool (default: ``False``); if ``True``, return all `n`\th1068roots of ``self``, instead of just one.10691070- ``algorithm`` - string (default: None); The algorithm for the prime modulus case.1071CRT and p-adic log techniques are used to reduce to this case.1072'Johnston' is the only currently supported option.10731074- ``cunningham`` - bool (default: ``False``); In some cases,1075factorization of ``n`` is computed. If cunningham is set to ``True``,1076the factorization of ``n`` is computed using trial division for all1077primes in the so called Cunningham table. Refer to1078sage.rings.factorint.factor_cunningham for more information. You need1079to install an optional package to use this method, this can be done1080with the following command line ``sage -i cunningham_tables``10811082OUTPUT:10831084If self has an `n`\th root, returns one (if ``all`` is ``False``) or a1085list of all of them (if ``all`` is ``True``). Otherwise, raises a1086``ValueError`` (if ``extend`` is ``False``) or a ``NotImplementedError`` (if1087``extend`` is ``True``).10881089.. warning::1090The 'extend' option is not implemented (yet).10911092NOTES:10931094- If `n = 0`:10951096- if ``all=True``:10971098- if ``self=1``: all nonzero elements of the parent are returned in1099a list. Note that this could be very expensive for large1100parents.11011102- otherwise: an empty list is returned11031104- if ``all=False``:11051106- if ``self=1``: ``self`` is returned11071108- otherwise; a ``ValueError`` is raised11091110- If `n < 0`:11111112- if self is invertible, the `(-n)`\th root of the inverse of self is returned11131114- otherwise a ``ValueError`` is raised or empty list returned.11151116EXAMPLES::111711181119sage: K = GF(31)1120sage: a = K(22)1121sage: K(22).nth_root(7)1122131123sage: K(25).nth_root(5)112451125sage: K(23).nth_root(3)1126291127sage: mod(225,2^5*3^2).nth_root(4, all=True)1128[225, 129, 33, 63, 255, 159, 9, 201, 105, 279, 183, 87, 81, 273, 177, 207, 111, 15, 153, 57, 249, 135, 39, 231]1129sage: mod(275,2^5*7^4).nth_root(7, all=True)1130[58235, 25307, 69211, 36283, 3355, 47259, 14331]1131sage: mod(1,8).nth_root(2,all=True)1132[1, 7, 5, 3]1133sage: mod(4,8).nth_root(2,all=True)1134[2, 6]1135sage: mod(1,16).nth_root(4,all=True)1136[1, 15, 13, 3, 9, 7, 5, 11]1137sage: (mod(22,31)^200).nth_root(200)113851139sage: mod(3,6).nth_root(0,all=True)1140[]1141sage: mod(3,6).nth_root(0)1142Traceback (most recent call last):1143...1144ValueError1145sage: mod(1,6).nth_root(0,all=True)1146[1, 2, 3, 4, 5]11471148TESTS::11491150sage: for p in [1009,2003,10007,100003]:1151... K = GF(p)1152... for r in (p-1).divisors():1153... if r == 1: continue1154... x = K.random_element()1155... y = x^r1156... if y.nth_root(r)**r != y: raise RuntimeError1157... if (y^41).nth_root(41*r)**(41*r) != y^41: raise RuntimeError1158... if (y^307).nth_root(307*r)**(307*r) != y^307: raise RuntimeError11591160sage: for t in xrange(200):1161... n = randint(1,2^63)1162... K = Integers(n)1163... b = K.random_element()1164... e = randint(-2^62, 2^63)1165... try:1166... a = b.nth_root(e)1167... if a^e != b:1168... print n, b, e, a1169... raise NotImplementedError1170... except ValueError:1171... pass11721173We check that #13172 is resolved::11741175sage: mod(-1, 4489).nth_root(2, all=True)1176[]11771178Check that the code path cunningham might be used::11791180sage: a = Mod(9,11)1181sage: a.nth_root(2, False, True, 'Johnston', cunningham = True) # optional - cunningham1182[3, 8]11831184ALGORITHMS:11851186- The default for prime modulus is currently an algorithm described in the following paper:11871188Johnston, Anna M. A generalized qth root algorithm. Proceedings of the tenth annual ACM-SIAM symposium on Discrete algorithms. Baltimore, 1999: pp 929-930.11891190AUTHORS:11911192- David Roe (2010-2-13)1193"""1194if extend:1195raise NotImplementedError1196K = self.parent()1197n = Integer(n)1198if n == 0:1199if self == 1:1200if all: return [K(a) for a in range(1,K.order())]1201else: return self1202else:1203if all: return []1204else: raise ValueError1205F = K.factored_order()1206if len(F) == 0:1207if all:1208return [self]1209else:1210return self1211if len(F) != 1:1212if all:1213# we should probably do a first pass to see if there are any solutions so that we don't get giant intermediate lists and waste time...1214L = []1215for p, k in F:1216L.append(mod(self, p**k).nth_root(n, all=True, algorithm=algorithm))1217ans = L[0]1218for i in range(1, len(L)):1219ans = [a.crt(b) for a in ans for b in L[i]]1220else:1221ans = mod(0,1)1222for p, k in F:1223ans = ans.crt(mod(self, p**k).nth_root(n, algorithm=algorithm))1224return ans1225p, k = F[0]1226if self.is_zero():1227if n < 0:1228if all: return []1229else: raise ValueError1230if all:1231if k == 1:1232return [self]1233else:1234minval = max(1, (k/n).ceil())1235return [K(a*p**minval) for a in range(p**(k-minval))]1236else:1237return self1238if n < 0:1239try:1240self = ~self1241except ZeroDivisionError:1242if all: return []1243else: raise ValueError1244n = -n1245if p == 2 and k == 1:1246if all: return [self]1247else: return self1248if k > 1:1249pval, upart = self.lift().val_unit(p)1250if not n.divides(pval):1251if all:1252return []1253else:1254raise ValueError, "no nth root"1255if pval > 0:1256if all:1257return [K(a.lift()*p**(pval // n) + p**(k - (pval - pval//n)) * b) for a in mod(upart, p**(k-pval)).nth_root(n, all=True, algorithm=algorithm) for b in range(p**(pval - pval//n))]1258else:1259return K(p**(pval // n) * mod(upart, p**(k-pval)).nth_root(n, algorithm=algorithm).lift())1260from sage.rings.padics.all import ZpFM1261R = ZpFM(p,k)1262self_orig = self1263if p == 2:1264sign = [1]1265if self % 4 == 3:1266if n % 2 == 0:1267if all: return []1268else: raise ValueError, "no nth root"1269else:1270sign = [-1]1271self = -self1272elif n % 2 == 0:1273if k > 2 and self % 8 == 5:1274if all: return []1275else: raise ValueError, "no nth root"1276sign = [1, -1]1277if k == 2:1278if all: return [K(s) for s in sign[:2]]1279else: return K(sign[0])1280if all: modp = [mod(self,8)]1281else: modp = mod(self,8)1282else:1283sign = [1]1284modp = self % p1285self = self / K(R.teichmuller(modp))1286modp = modp.nth_root(n, all=all, algorithm=algorithm)1287# now self is congruent to 1 mod 4 or 1 mod p (for odd p), so the power series for p-adic log converges.1288# Hensel lifting is probably better, but this is easier at the moment.1289plog = R(self).log()1290nval = n.valuation(p)1291if nval >= plog.valuation() + (-1 if p == 2 else 0):1292if self == 1:1293if all:1294return [s*K(p*k+m.lift()) for k in range(p**(k-(2 if p==2 else 1))) for m in modp for s in sign]1295else: return self_orig1296else:1297if all: return []1298else: raise ValueError, "no nth root"1299if all:1300ans = [plog // n + p**(k - nval) * i for i in range(p**nval)]1301ans = [s*K(R.teichmuller(m) * a.exp()) for a in ans for m in modp for s in sign]1302return ans1303else:1304return sign[0] * K(R.teichmuller(modp) * (plog // n).exp())1305return self._nth_root_common(n, all, algorithm, cunningham)13061307def _nth_root_naive(self, n):1308"""1309Computes all nth roots using brute force, for doc-testing.13101311TESTS::13121313sage: for n in range(2,100): # long time1314....: K=Integers(n)1315....: elist = range(1,min(2*n+2,100))1316....: for e in random_sublist(elist, 5/len(elist)):1317....: for a in random_sublist(range(1,n), min((n+2)//2,10)/(n-1)):1318....: b = K(a)1319....: try:1320....: L = b.nth_root(e, all=True)1321....: if len(L) > 0:1322....: c = b.nth_root(e)1323....: except Exception:1324....: L = [-1]1325....: M = b._nth_root_naive(e)1326....: if sorted(L) != M:1327....: print "mod(%s, %s).nth_root(%s,all=True), mod(%s, %s)._nth_root_naive(%s)"%(a,n,e,a,n,e)1328....: if len(L) > 0 and (c not in L):1329....: print "mod(%s, %s).nth_root(%s), mod(%s, %s).nth_root(%s,all=True)"%(a,n,e,a,n,e)1330"""1331L = []1332for a in self.parent():1333if a**n == self:1334L.append(a)1335return L13361337def _balanced_abs(self):1338"""1339This function returns `x` or `-x`, whichever has a1340positive representative in `-n/2 < x \leq n/2`.13411342This is used so that the same square root is always returned,1343despite the possibly probabalistic nature of the underlying1344algorithm.1345"""1346if self.lift() > self.__modulus.sageInteger >> 1:1347return -self1348else:1349return self135013511352def rational_reconstruction(self):1353"""1354EXAMPLES::13551356sage: R = IntegerModRing(97)1357sage: a = R(2) / R(3)1358sage: a1359331360sage: a.rational_reconstruction()13612/31362"""1363return self.lift().rational_reconstruction(self.modulus())13641365def crt(IntegerMod_abstract self, IntegerMod_abstract other):1366r"""1367Use the Chinese Remainder Theorem to find an element of the1368integers modulo the product of the moduli that reduces to1369``self`` and to ``other``. The modulus of1370``other`` must be coprime to the modulus of1371``self``.13721373EXAMPLES::13741375sage: a = mod(3,5)1376sage: b = mod(2,7)1377sage: a.crt(b)13782313791380::13811382sage: a = mod(37,10^8)1383sage: b = mod(9,3^8)1384sage: a.crt(b)138512590000003713861387::13881389sage: b = mod(0,1)1390sage: a.crt(b) == a1391True1392sage: a.crt(b).modulus()139310000000013941395TESTS::13961397sage: mod(0,1).crt(mod(4,2^127))139841399sage: mod(4,2^127).crt(mod(0,1))140041401sage: mod(4,2^30).crt(mod(0,1))140241403sage: mod(0,1).crt(mod(4,2^30))140441405sage: mod(0,1).crt(mod(4,2^15))140641407sage: mod(4,2^15).crt(mod(0,1))1408414091410AUTHORS:14111412- Robert Bradshaw1413"""1414cdef int_fast64_t new_modulus1415if not PY_TYPE_CHECK(self, IntegerMod_gmp) and not PY_TYPE_CHECK(other, IntegerMod_gmp):14161417if other.__modulus.int64 == 1: return self1418new_modulus = self.__modulus.int64 * other.__modulus.int641419if new_modulus < INTEGER_MOD_INT32_LIMIT:1420return self.__crt(other)14211422elif new_modulus < INTEGER_MOD_INT64_LIMIT:1423if not PY_TYPE_CHECK(self, IntegerMod_int64):1424self = IntegerMod_int64(self._parent, self.lift())1425if not PY_TYPE_CHECK(other, IntegerMod_int64):1426other = IntegerMod_int64(other._parent, other.lift())1427return self.__crt(other)14281429if not PY_TYPE_CHECK(self, IntegerMod_gmp):1430if self.__modulus.int64 == 1: return other1431self = IntegerMod_gmp(self._parent, self.lift())14321433if not PY_TYPE_CHECK(other, IntegerMod_gmp):1434if other.__modulus.int64 == 1: return self1435other = IntegerMod_gmp(other._parent, other.lift())14361437return self.__crt(other)143814391440def additive_order(self):1441r"""1442Returns the additive order of self.14431444This is the same as ``self.order()``.14451446EXAMPLES::14471448sage: Integers(20)(2).additive_order()1449101450sage: Integers(20)(7).additive_order()1451201452sage: Integers(90308402384902)(2).additive_order()1453451542011924511454"""1455n = self.__modulus.sageInteger1456return sage.rings.integer.Integer(n.__floordiv__(self.lift().gcd(n)))14571458def is_primitive_root(self):1459"""1460Determines whether this element generates the group of units modulo n.14611462This is only possible if the group of units is cyclic, which occurs if1463n is 2, 4, a power of an odd prime or twice a power of an odd prime.14641465EXAMPLES::14661467sage: mod(1,2).is_primitive_root()1468True1469sage: mod(3,4).is_primitive_root()1470True1471sage: mod(2,7).is_primitive_root()1472False1473sage: mod(3,98).is_primitive_root()1474True1475sage: mod(11,1009^2).is_primitive_root()1476True14771478TESTS::14791480sage: for p in prime_range(3,12):1481... for k in range(1,4):1482... for even in [1,2]:1483... n = even*p^k1484... phin = euler_phi(n)1485... for _ in range(6):1486... a = Zmod(n).random_element()1487... if not a.is_unit(): continue1488... if a.is_primitive_root().__xor__(a.multiplicative_order()==phin):1489... print "mod(%s,%s) incorrect"%(a,n)1490"""1491cdef Integer p1, q = Integer(2)1492m = self.modulus()1493if m == 2:1494return self == 11495if m == 4:1496return self == 31497pow2, odd = m.val_unit(2)1498if pow2 > 1:1499return False1500if pow2 == 1:1501if self % 2 == 0:1502return False1503self = self % odd1504p, k = odd.perfect_power()1505if not p.is_prime():1506return False1507if k > 1:1508if self**((p-1)*p**(k-2)) == 1:1509return False1510# self**(p**(k-1)*(p-1)//q) = 1 for some q1511# iff mod(self,p)**((p-1)//q) = 1 for some q1512self = self % p1513# Now self is modulo a prime and need the factorization of p-1.1514p1 = p - 11515while mpz_cmpabs_ui(p1.value, 1):1516q = p1.trial_division(bound=1000, start=mpz_get_ui(q.value))1517if q == p1:1518break1519if self**((p-1)//q) == 1:1520return False1521mpz_remove(p1.value, p1.value, q.value)1522if q.is_prime():1523return self**((p-1)//q) != 11524# No small factors remain: we need to do some real work.1525for qq, e in q.factor():1526if self**((p-1)//qq) == 1:1527return False1528return True15291530def multiplicative_order(self):1531"""1532Returns the multiplicative order of self.15331534EXAMPLES::15351536sage: Mod(-1,5).multiplicative_order()153721538sage: Mod(1,5).multiplicative_order()153911540sage: Mod(0,5).multiplicative_order()1541Traceback (most recent call last):1542...1543ArithmeticError: multiplicative order of 0 not defined since it is not a unit modulo 51544"""1545try:1546return sage.rings.integer.Integer(self._pari_().order()) # pari's "order" is by default multiplicative1547except PariError:1548raise ArithmeticError, "multiplicative order of %s not defined since it is not a unit modulo %s"%(1549self, self.__modulus.sageInteger)15501551def valuation(self, p):1552"""1553The largest power r such that m is in the ideal generated by p^r or infinity if there is not a largest such power.1554However it is an error to take the valuation with respect to a unit.15551556.. NOTE::15571558This is not a valuation in the mathematical sense. As shown with the examples below.15591560EXAMPLES:15611562This example shows that the (a*b).valuation(n) is not always the same as a.valuation(n) + b.valuation(n)15631564::15651566sage: R=ZZ.quo(9)1567sage: a=R(3)1568sage: b=R(6)1569sage: a.valuation(3)157011571sage: a.valuation(3) + b.valuation(3)157221573sage: (a*b).valuation(3)1574+Infinity15751576The valuation with respect to a unit is an error15771578::15791580sage: a.valuation(4)1581Traceback (most recent call last):1582...1583ValueError: Valuation with respect to a unit is not defined.15841585TESTS::15861587sage: R=ZZ.quo(12)1588sage: a=R(2)1589sage: b=R(4)1590sage: a.valuation(2)159111592sage: b.valuation(2)1593+Infinity1594sage: ZZ.quo(1024)(16).valuation(4)1595215961597"""1598p=self.__modulus.sageInteger.gcd(p)1599if p==1:1600raise ValueError("Valuation with respect to a unit is not defined.")1601r = 01602power = p1603while not (self % power): # self % power == 01604r += 11605power *= p1606if not power.divides(self.__modulus.sageInteger):1607from sage.rings.all import infinity1608return infinity1609return r16101611def __floordiv__(self, other):1612"""1613Exact division for prime moduli, for compatibility with other fields.16141615EXAMPLES:1616sage: GF(7)(3) // GF(7)(5)161721618"""1619# needs to be rewritten for coercion1620if other.parent() is not self.parent():1621other = self.parent().coerce(other)1622if self.parent().is_field():1623return self / other1624else:1625raise TypeError, "Floor division not defined for non-prime modulus"16261627def _repr_(self):1628return str(self.lift())16291630def _latex_(self):1631return str(self)16321633def _integer_(self, ZZ=None):1634return self.lift()16351636def _rational_(self):1637return rational.Rational(self.lift())16381639164016411642######################################################################1643# class IntegerMod_gmp1644######################################################################164516461647cdef class IntegerMod_gmp(IntegerMod_abstract):1648"""1649Elements of `\ZZ/n\ZZ` for n not small enough1650to be operated on in word size.16511652AUTHORS:16531654- Robert Bradshaw (2006-08-24)1655"""16561657def __init__(IntegerMod_gmp self, parent, value, empty=False):1658"""1659EXAMPLES::16601661sage: a = mod(5,14^20)1662sage: type(a)1663<type 'sage.rings.finite_rings.integer_mod.IntegerMod_gmp'>1664sage: loads(dumps(a)) == a1665True1666"""1667mpz_init(self.value)1668IntegerMod_abstract.__init__(self, parent)1669if empty:1670return1671cdef sage.rings.integer.Integer z1672if PY_TYPE_CHECK(value, sage.rings.integer.Integer):1673z = value1674elif PY_TYPE_CHECK(value, rational.Rational):1675z = value % self.__modulus.sageInteger1676elif PY_TYPE_CHECK(value, int):1677self.set_from_long(value)1678return1679else:1680z = sage.rings.integer_ring.Z(value)1681self.set_from_mpz(z.value)16821683cdef IntegerMod_gmp _new_c(self):1684cdef IntegerMod_gmp x1685x = PY_NEW(IntegerMod_gmp)1686mpz_init(x.value)1687x.__modulus = self.__modulus1688x._parent = self._parent1689return x16901691def __dealloc__(self):1692mpz_clear(self.value)16931694cdef void set_from_mpz(self, mpz_t value):1695cdef sage.rings.integer.Integer modulus1696modulus = self.__modulus.sageInteger1697if mpz_sgn(value) == -1 or mpz_cmp(value, modulus.value) >= 0:1698mpz_mod(self.value, value, modulus.value)1699else:1700mpz_set(self.value, value)17011702cdef void set_from_long(self, long value):1703cdef sage.rings.integer.Integer modulus1704mpz_set_si(self.value, value)1705if value < 0 or mpz_cmp_si(self.__modulus.sageInteger.value, value) >= 0:1706mpz_mod(self.value, self.value, self.__modulus.sageInteger.value)17071708cdef mpz_t* get_value(IntegerMod_gmp self):1709return &self.value17101711def __lshift__(IntegerMod_gmp self, k):1712r"""1713Performs a left shift by ``k`` bits.17141715For details, see :meth:`shift`.17161717EXAMPLES::17181719sage: e = Mod(19, 10^10)1720sage: e << 102172194436085761722"""1723return self.shift(long(k))17241725def __rshift__(IntegerMod_gmp self, k):1726r"""1727Performs a right shift by ``k`` bits.17281729For details, see :meth:`shift`.17301731EXAMPLES::17321733sage: e = Mod(19, 10^10)1734sage: e >> 1173591736"""1737return self.shift(-long(k))17381739cdef shift(IntegerMod_gmp self, long k):1740r"""1741Performs a bit-shift specified by ``k`` on ``self``.17421743Suppose that ``self`` represents an integer `x` modulo `n`. If `k` is1744`k = 0`, returns `x`. If `k > 0`, shifts `x` to the left, that is,1745multiplies `x` by `2^k` and then returns the representative in the1746range `[0,n)`. If `k < 0`, shifts `x` to the right, that is, returns1747the integral part of `x` divided by `2^k`.17481749Note that, in any case, ``self`` remains unchanged.17501751INPUT:17521753- ``k`` - Integer of type ``long``17541755OUTPUT17561757- Result of type ``IntegerMod_gmp``17581759EXAMPLES::17601761sage: e = Mod(19, 10^10)1762sage: e << 102176394436085761764sage: e >> 1176591766sage: e >> 4176711768"""1769cdef IntegerMod_gmp x1770if k == 0:1771return self1772else:1773x = self._new_c()1774if k > 0:1775mpz_mul_2exp(x.value, self.value, k)1776mpz_fdiv_r(x.value, x.value, self.__modulus.sageInteger.value)1777else:1778mpz_fdiv_q_2exp(x.value, self.value, -k)1779return x17801781cdef int _cmp_c_impl(left, Element right) except -2:1782"""1783EXAMPLES::17841785sage: mod(5,13^20) == mod(5,13^20)1786True1787sage: mod(5,13^20) == mod(-5,13^20)1788False1789sage: mod(5,13^20) == mod(-5,13)1790False1791"""1792cdef int i1793i = mpz_cmp((<IntegerMod_gmp>left).value, (<IntegerMod_gmp>right).value)1794if i < 0:1795return -11796elif i == 0:1797return 01798else:1799return 118001801def __richcmp__(left, right, int op):1802return (<Element>left)._richcmp(right, op)180318041805cpdef bint is_one(IntegerMod_gmp self):1806"""1807Returns ``True`` if this is `1`, otherwise1808``False``.18091810EXAMPLES::18111812sage: mod(1,5^23).is_one()1813True1814sage: mod(0,5^23).is_one()1815False1816"""1817return mpz_cmp_si(self.value, 1) == 018181819def __nonzero__(IntegerMod_gmp self):1820"""1821Returns ``True`` if this is not `0`, otherwise1822``False``.18231824EXAMPLES::18251826sage: mod(13,5^23).is_zero()1827False1828sage: (mod(25,5^23)^23).is_zero()1829True1830"""1831return mpz_cmp_si(self.value, 0) != 018321833cpdef bint is_unit(self):1834"""1835Return True iff this element is a unit.18361837EXAMPLES::18381839sage: mod(13, 5^23).is_unit()1840True1841sage: mod(25, 5^23).is_unit()1842False1843"""1844return self.lift().gcd(self.modulus()) == 118451846def __crt(IntegerMod_gmp self, IntegerMod_gmp other):1847cdef IntegerMod_gmp lift, x1848cdef sage.rings.integer.Integer modulus, other_modulus18491850modulus = self.__modulus.sageInteger1851other_modulus = other.__modulus.sageInteger1852import integer_mod_ring1853lift = IntegerMod_gmp(integer_mod_ring.IntegerModRing(modulus*other_modulus), None, empty=True)1854try:1855if mpz_cmp(self.value, other.value) > 0:1856x = (other - IntegerMod_gmp(other._parent, self.lift())) / IntegerMod_gmp(other._parent, modulus)1857mpz_mul(lift.value, x.value, modulus.value)1858mpz_add(lift.value, lift.value, self.value)1859else:1860x = (self - IntegerMod_gmp(self._parent, other.lift())) / IntegerMod_gmp(self._parent, other_modulus)1861mpz_mul(lift.value, x.value, other_modulus.value)1862mpz_add(lift.value, lift.value, other.value)1863return lift1864except ZeroDivisionError:1865raise ZeroDivisionError, "moduli must be coprime"186618671868def __copy__(IntegerMod_gmp self):1869cdef IntegerMod_gmp x1870x = self._new_c()1871mpz_set(x.value, self.value)1872return x18731874cpdef ModuleElement _add_(self, ModuleElement right):1875"""1876EXAMPLES::18771878sage: R = Integers(10^10)1879sage: R(7) + R(8)1880151881"""1882cdef IntegerMod_gmp x1883x = self._new_c()1884mpz_add(x.value, self.value, (<IntegerMod_gmp>right).value)1885if mpz_cmp(x.value, self.__modulus.sageInteger.value) >= 0:1886mpz_sub(x.value, x.value, self.__modulus.sageInteger.value)1887return x;18881889cpdef ModuleElement _iadd_(self, ModuleElement right):1890"""1891EXAMPLES::18921893sage: R = Integers(10^10)1894sage: R(7) + R(8)1895151896"""1897mpz_add(self.value, self.value, (<IntegerMod_gmp>right).value)1898if mpz_cmp(self.value, self.__modulus.sageInteger.value) >= 0:1899mpz_sub(self.value, self.value, self.__modulus.sageInteger.value)1900return self19011902cpdef ModuleElement _sub_(self, ModuleElement right):1903"""1904EXAMPLES::19051906sage: R = Integers(10^10)1907sage: R(7) - R(8)190899999999991909"""1910cdef IntegerMod_gmp x1911x = self._new_c()1912mpz_sub(x.value, self.value, (<IntegerMod_gmp>right).value)1913if mpz_sgn(x.value) == -1:1914mpz_add(x.value, x.value, self.__modulus.sageInteger.value)1915return x;19161917cpdef ModuleElement _isub_(self, ModuleElement right):1918"""1919EXAMPLES::19201921sage: R = Integers(10^10)1922sage: R(7) - R(8)192399999999991924"""1925mpz_sub(self.value, self.value, (<IntegerMod_gmp>right).value)1926if mpz_sgn(self.value) == -1:1927mpz_add(self.value, self.value, self.__modulus.sageInteger.value)1928return self19291930cpdef ModuleElement _neg_(self):1931"""1932EXAMPLES::19331934sage: -mod(5,10^10)193599999999951936sage: -mod(0,10^10)193701938"""1939if mpz_cmp_si(self.value, 0) == 0:1940return self1941cdef IntegerMod_gmp x1942x = self._new_c()1943mpz_sub(x.value, self.__modulus.sageInteger.value, self.value)1944return x19451946cpdef RingElement _mul_(self, RingElement right):1947"""1948EXAMPLES::19491950sage: R = Integers(10^11)1951sage: R(700000) * R(800000)1952600000000001953"""1954cdef IntegerMod_gmp x1955x = self._new_c()1956mpz_mul(x.value, self.value, (<IntegerMod_gmp>right).value)1957mpz_fdiv_r(x.value, x.value, self.__modulus.sageInteger.value)1958return x19591960cpdef RingElement _imul_(self, RingElement right):1961"""1962EXAMPLES::19631964sage: R = Integers(10^11)1965sage: R(700000) * R(800000)1966600000000001967"""1968mpz_mul(self.value, self.value, (<IntegerMod_gmp>right).value)1969mpz_fdiv_r(self.value, self.value, self.__modulus.sageInteger.value)1970return self19711972cpdef RingElement _div_(self, RingElement right):1973"""1974EXAMPLES::19751976sage: R = Integers(10^11)1977sage: R(3) / R(7)1978714285714291979"""1980return self._mul_(~right)19811982def __int__(self):1983return int(self.lift())19841985def __index__(self):1986"""1987Needed so integers modulo `n` can be used as list indices.19881989EXAMPLES::19901991sage: v = [1,2,3,4,5]1992sage: v[Mod(3,10^20)]199341994"""1995return int(self.lift())19961997def __long__(self):1998return long(self.lift())19992000def __mod__(self, right):2001if self.modulus() % right != 0:2002raise ZeroDivisionError, "reduction modulo right not defined."2003import integer_mod_ring2004return IntegerMod(integer_mod_ring.IntegerModRing(right), self)20052006def __pow__(IntegerMod_gmp self, exp, m): # NOTE: m ignored, always use modulus of parent ring2007"""2008EXAMPLES:2009sage: R = Integers(10^10)2010sage: R(2)^1000201156680693762012sage: p = next_prime(11^10)2013sage: R = Integers(p)2014sage: R(9876)^(p-1)201512016sage: mod(3, 10^100)^-2201788888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888892018sage: mod(2, 10^100)^-22019Traceback (most recent call last):2020...2021ZeroDivisionError: Inverse does not exist.20222023TESTS:20242025We define ``0^0`` to be unity, :trac:`13894`::20262027sage: p = next_prime(11^10)2028sage: R = Integers(p)2029sage: R(0)^02030120312032The value returned from ``0^0`` should belong to our ring::20332034sage: type(R(0)^0) == type(R(0))2035True20362037When the modulus is ``1``, the only element in the ring is2038``0`` (and it is equivalent to ``1``), so we return that2039instead::20402041sage: from sage.rings.finite_rings.integer_mod \2042... import IntegerMod_gmp2043sage: zero = IntegerMod_gmp(Integers(1),0)2044sage: type(zero)2045<type 'sage.rings.finite_rings.integer_mod.IntegerMod_gmp'>2046sage: zero^02047020482049"""2050cdef IntegerMod_gmp x = self._new_c()2051sig_on()2052try:2053mpz_pow_helper(x.value, self.value, exp, self.__modulus.sageInteger.value)2054return x2055finally:2056sig_off()20572058def __invert__(IntegerMod_gmp self):2059"""2060Return the multiplicative inverse of self.20612062EXAMPLES::20632064sage: a = mod(3,10^100); type(a)2065<type 'sage.rings.finite_rings.integer_mod.IntegerMod_gmp'>2066sage: ~a206766666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666672068sage: ~mod(2,10^100)2069Traceback (most recent call last):2070...2071ZeroDivisionError: Inverse does not exist.2072"""2073if self.is_zero():2074raise ZeroDivisionError, "Inverse does not exist."20752076cdef IntegerMod_gmp x2077x = self._new_c()2078if mpz_invert(x.value, self.value, self.__modulus.sageInteger.value):2079return x2080else:2081raise ZeroDivisionError, "Inverse does not exist."20822083def lift(IntegerMod_gmp self):2084"""2085Lift an integer modulo `n` to the integers.20862087EXAMPLES::20882089sage: a = Mod(8943, 2^70); type(a)2090<type 'sage.rings.finite_rings.integer_mod.IntegerMod_gmp'>2091sage: lift(a)209289432093sage: a.lift()209489432095"""2096cdef sage.rings.integer.Integer z2097z = sage.rings.integer.Integer()2098z.set_from_mpz(self.value)2099return z21002101def __float__(self):2102return float(self.lift())21032104def __hash__(self):2105"""2106EXAMPLES::21072108sage: a = Mod(8943, 2^100)2109sage: hash(a)211089432111"""2112# return mpz_pythonhash(self.value)2113return hash(self.lift())21142115@coerce_binop2116def gcd(self, IntegerMod_gmp other):2117"""2118Greatest common divisor21192120Returns the "smallest" generator in `\ZZ / N\ZZ` of the ideal2121generated by ``self`` and ``other``.21222123INPUT:21242125- ``other`` -- an element of the same ring as this one.21262127EXAMPLES::21282129sage: mod(2^3*3^2*5, 3^3*2^2*17^8).gcd(mod(2^4*3*17, 3^3*2^2*17^8))2130122131sage: mod(0,17^8).gcd(mod(0,17^8))213202133"""2134cdef IntegerMod_gmp ans = self._new_c()2135sig_on()2136mpz_gcd(ans.value, self.value, self.__modulus.sageInteger.value)2137mpz_gcd(ans.value, ans.value, other.value)2138sig_off()2139if mpz_cmp(ans.value, self.__modulus.sageInteger.value) == 0:2140# self = other = 02141mpz_set_ui(ans.value, 0)2142return ans21432144######################################################################2145# class IntegerMod_int2146######################################################################214721482149cdef class IntegerMod_int(IntegerMod_abstract):2150"""2151Elements of `\ZZ/n\ZZ` for n small enough to2152be operated on in 32 bits21532154AUTHORS:21552156- Robert Bradshaw (2006-08-24)2157"""21582159def __init__(self, parent, value, empty=False):2160"""2161EXAMPLES::21622163sage: a = Mod(10,30); a2164102165sage: loads(a.dumps()) == a2166True2167"""2168IntegerMod_abstract.__init__(self, parent)2169if empty:2170return2171if self.__modulus.int32 == 1:2172self.ivalue = 02173return2174cdef long x2175if PY_TYPE_CHECK(value, int):2176x = value2177self.ivalue = x % self.__modulus.int322178if self.ivalue < 0:2179self.ivalue = self.ivalue + self.__modulus.int322180return2181elif PY_TYPE_CHECK(value, IntegerMod_int):2182self.ivalue = (<IntegerMod_int>value).ivalue % self.__modulus.int322183return2184cdef sage.rings.integer.Integer z2185if PY_TYPE_CHECK(value, sage.rings.integer.Integer):2186z = value2187elif PY_TYPE_CHECK(value, rational.Rational):2188z = value % self.__modulus.sageInteger2189else:2190z = sage.rings.integer_ring.Z(value)2191self.set_from_mpz(z.value)21922193def _make_new_with_parent_c(self, parent): #ParentWithBase parent):2194cdef IntegerMod_int x = PY_NEW(IntegerMod_int)2195x._parent = parent2196x.__modulus = parent._pyx_order2197x.ivalue = self.ivalue2198return x21992200cdef IntegerMod_int _new_c(self, int_fast32_t value):2201if self.__modulus.table is not None:2202return self.__modulus.lookup(value)2203cdef IntegerMod_int x = PY_NEW(IntegerMod_int)2204x._parent = self._parent2205x.__modulus = self.__modulus2206x.ivalue = value2207return x22082209cdef void set_from_mpz(self, mpz_t value):2210if mpz_sgn(value) == -1 or mpz_cmp_si(value, self.__modulus.int32) >= 0:2211self.ivalue = mpz_fdiv_ui(value, self.__modulus.int32)2212else:2213self.ivalue = mpz_get_si(value)22142215cdef void set_from_long(self, long value):2216self.ivalue = value % self.__modulus.int3222172218cdef void set_from_int(IntegerMod_int self, int_fast32_t ivalue):2219if ivalue < 0:2220self.ivalue = self.__modulus.int32 + (ivalue % self.__modulus.int32)2221elif ivalue >= self.__modulus.int32:2222self.ivalue = ivalue % self.__modulus.int322223else:2224self.ivalue = ivalue22252226cdef int_fast32_t get_int_value(IntegerMod_int self):2227return self.ivalue2228222922302231cdef int _cmp_c_impl(self, Element right) except -2:2232"""2233EXAMPLES::22342235sage: mod(5,13) == mod(-8,13)2236True2237sage: mod(5,13) == mod(8,13)2238False2239sage: mod(5,13) == mod(5,24)2240False2241sage: mod(0, 13) == 02242True2243sage: mod(0, 13) == int(0)2244True2245"""2246if self.ivalue == (<IntegerMod_int>right).ivalue:2247return 02248elif self.ivalue < (<IntegerMod_int>right).ivalue:2249return -12250else:2251return 122522253def __richcmp__(left, right, int op):2254return (<Element>left)._richcmp(right, op)225522562257cpdef bint is_one(IntegerMod_int self):2258"""2259Returns ``True`` if this is `1`, otherwise2260``False``.22612262EXAMPLES::22632264sage: mod(6,5).is_one()2265True2266sage: mod(0,5).is_one()2267False2268"""2269return self.ivalue == 122702271def __nonzero__(IntegerMod_int self):2272"""2273Returns ``True`` if this is not `0`, otherwise2274``False``.22752276EXAMPLES::22772278sage: mod(13,5).is_zero()2279False2280sage: mod(25,5).is_zero()2281True2282"""2283return self.ivalue != 022842285cpdef bint is_unit(IntegerMod_int self):2286"""2287Return True iff this element is a unit22882289EXAMPLES::22902291sage: a=Mod(23,100)2292sage: a.is_unit()2293True2294sage: a=Mod(24,100)2295sage: a.is_unit()2296False2297"""2298return gcd_int(self.ivalue, self.__modulus.int32) == 122992300def __crt(IntegerMod_int self, IntegerMod_int other):2301"""2302Use the Chinese Remainder Theorem to find an element of the2303integers modulo the product of the moduli that reduces to self and2304to other. The modulus of other must be coprime to the modulus of2305self.23062307EXAMPLES::23082309sage: a = mod(3,5)2310sage: b = mod(2,7)2311sage: a.crt(b)23122323132314AUTHORS:23152316- Robert Bradshaw2317"""2318cdef IntegerMod_int lift2319cdef int_fast32_t x23202321import integer_mod_ring2322lift = IntegerMod_int(integer_mod_ring.IntegerModRing(self.__modulus.int32 * other.__modulus.int32), None, empty=True)23232324try:2325x = (other.ivalue - self.ivalue % other.__modulus.int32) * mod_inverse_int(self.__modulus.int32, other.__modulus.int32)2326lift.set_from_int( x * self.__modulus.int32 + self.ivalue )2327return lift2328except ZeroDivisionError:2329raise ZeroDivisionError, "moduli must be coprime"233023312332def __copy__(IntegerMod_int self):2333cdef IntegerMod_int x = PY_NEW(IntegerMod_int)2334x._parent = self._parent2335x.__modulus = self.__modulus2336x.ivalue = self.ivalue2337return x23382339cpdef ModuleElement _add_(self, ModuleElement right):2340"""2341EXAMPLES::23422343sage: R = Integers(10)2344sage: R(7) + R(8)234552346"""2347cdef int_fast32_t x2348x = self.ivalue + (<IntegerMod_int>right).ivalue2349if x >= self.__modulus.int32:2350x = x - self.__modulus.int322351return self._new_c(x)23522353cpdef ModuleElement _iadd_(self, ModuleElement right):2354"""2355EXAMPLES::23562357sage: R = Integers(10)2358sage: R(7) + R(8)235952360"""2361cdef int_fast32_t x2362x = self.ivalue + (<IntegerMod_int>right).ivalue2363if x >= self.__modulus.int32:2364x = x - self.__modulus.int322365self.ivalue = x2366return self23672368cpdef ModuleElement _sub_(self, ModuleElement right):2369"""2370EXAMPLES::23712372sage: R = Integers(10)2373sage: R(7) - R(8)237492375"""2376cdef int_fast32_t x2377x = self.ivalue - (<IntegerMod_int>right).ivalue2378if x < 0:2379x = x + self.__modulus.int322380return self._new_c(x)23812382cpdef ModuleElement _isub_(self, ModuleElement right):2383"""2384EXAMPLES::23852386sage: R = Integers(10)2387sage: R(7) - R(8)238892389"""2390cdef int_fast32_t x2391x = self.ivalue - (<IntegerMod_int>right).ivalue2392if x < 0:2393x = x + self.__modulus.int322394self.ivalue = x2395return self23962397cpdef ModuleElement _neg_(self):2398"""2399EXAMPLES::24002401sage: -mod(7,10)240232403sage: -mod(0,10)240402405"""2406if self.ivalue == 0:2407return self2408return self._new_c(self.__modulus.int32 - self.ivalue)24092410cpdef RingElement _mul_(self, RingElement right):2411"""2412EXAMPLES::24132414sage: R = Integers(10)2415sage: R(7) * R(8)241662417"""2418return self._new_c((self.ivalue * (<IntegerMod_int>right).ivalue) % self.__modulus.int32)24192420cpdef RingElement _imul_(self, RingElement right):2421"""2422EXAMPLES::24232424sage: R = Integers(10)2425sage: R(7) * R(8)242662427"""2428self.ivalue = (self.ivalue * (<IntegerMod_int>right).ivalue) % self.__modulus.int322429return self24302431cpdef RingElement _div_(self, RingElement right):2432"""2433EXAMPLES::24342435sage: R = Integers(10)2436sage: R(2)/3243742438"""2439if self.__modulus.inverses is not None:2440right_inverse = self.__modulus.inverses[(<IntegerMod_int>right).ivalue]2441if right_inverse is None:2442raise ZeroDivisionError, "Inverse does not exist."2443else:2444return self._new_c((self.ivalue * (<IntegerMod_int>right_inverse).ivalue) % self.__modulus.int32)24452446cdef int_fast32_t x2447x = self.ivalue * mod_inverse_int((<IntegerMod_int>right).ivalue, self.__modulus.int32)2448return self._new_c(x% self.__modulus.int32)24492450def __int__(IntegerMod_int self):2451return self.ivalue24522453def __index__(self):2454"""2455Needed so integers modulo `n` can be used as list indices.24562457EXAMPLES::24582459sage: v = [1,2,3,4,5]2460sage: v[Mod(10,7)]246142462"""2463return self.ivalue24642465def __long__(IntegerMod_int self):2466return self.ivalue24672468def __mod__(IntegerMod_int self, right):2469right = int(right)2470if self.__modulus.int32 % right != 0:2471raise ZeroDivisionError, "reduction modulo right not defined."2472import integer_mod_ring2473return integer_mod_ring.IntegerModRing(right)(self)24742475def __lshift__(IntegerMod_int self, k):2476r"""2477Performs a left shift by ``k`` bits.24782479For details, see :meth:`shift`.24802481EXAMPLES::24822483sage: e = Mod(5, 2^10 - 1)2484sage: e << 524851602486sage: e * 2^524871602488"""2489return self.shift(int(k))24902491def __rshift__(IntegerMod_int self, k):2492r"""2493Performs a right shift by ``k`` bits.24942495For details, see :meth:`shift`.24962497EXAMPLES::24982499sage: e = Mod(5, 2^10 - 1)2500sage: e << 525011602502sage: e * 2^525031602504"""2505return self.shift(-int(k))25062507cdef shift(IntegerMod_int self, int k):2508"""2509Performs a bit-shift specified by ``k`` on ``self``.25102511Suppose that ``self`` represents an integer `x` modulo `n`. If `k` is2512`k = 0`, returns `x`. If `k > 0`, shifts `x` to the left, that is,2513multiplies `x` by `2^k` and then returns the representative in the2514range `[0,n)`. If `k < 0`, shifts `x` to the right, that is, returns2515the integral part of `x` divided by `2^k`.25162517Note that, in any case, ``self`` remains unchanged.25182519INPUT:25202521- ``k`` - Integer of type ``int``25222523OUTPUT:25242525- Result of type ``IntegerMod_int``25262527WARNING:25282529For positive ``k``, if ``x << k`` overflows as a 32-bit integer, the2530result is meaningless.25312532EXAMPLES::25332534sage: e = Mod(5, 2^10 - 1)2535sage: e << 525361602537sage: e * 2^525381602539sage: e = Mod(8, 2^5 - 1)2540sage: e >> 3254112542sage: int(e)/int(2^3)254312544"""2545if k == 0:2546return self2547elif k > 0:2548return self._new_c((self.ivalue << k) % self.__modulus.int32)2549else:2550return self._new_c(self.ivalue >> (-k))25512552def __pow__(IntegerMod_int self, exp, m): # NOTE: m ignored, always use modulus of parent ring2553"""2554EXAMPLES:2555sage: R = Integers(10)2556sage: R(2)^10255742558sage: R = Integers(389)2559sage: R(7)^3882560125612562sage: mod(3, 100)^-12563672564sage: mod(3, 100)^-1000000002565125662567sage: mod(2, 100)^-12568Traceback (most recent call last):2569...2570ZeroDivisionError: Inverse does not exist.2571sage: mod(2, 100)^-1000000002572Traceback (most recent call last):2573...2574ZeroDivisionError: Inverse does not exist.25752576TESTS:25772578We define ``0^0`` to be unity, :trac:`13894`::25792580sage: R = Integers(100)2581sage: R(0)^02582125832584The value returned from ``0^0`` should belong to our ring::25852586sage: type(R(0)^0) == type(R(0))2587True25882589When the modulus is ``1``, the only element in the ring is2590``0`` (and it is equivalent to ``1``), so we return that2591instead::25922593sage: R = Integers(1)2594sage: R(0)^02595025962597"""2598cdef long long_exp2599cdef int_fast32_t res2600cdef mpz_t res_mpz2601if PyInt_CheckExact(exp) and -100000 < PyInt_AS_LONG(exp) < 100000:2602long_exp = PyInt_AS_LONG(exp)2603elif PY_TYPE_CHECK_EXACT(exp, Integer) and mpz_cmpabs_ui((<Integer>exp).value, 100000) == -1:2604long_exp = mpz_get_si((<Integer>exp).value)2605else:2606sig_on()2607try:2608mpz_init(res_mpz)2609base = self.lift()2610mpz_pow_helper(res_mpz, (<Integer>base).value, exp, self.__modulus.sageInteger.value)2611return self._new_c(mpz_get_ui(res_mpz))2612finally:2613mpz_clear(res_mpz)2614sig_off()26152616if long_exp == 0 and self.ivalue == 0:2617# Return 0 if the modulus is 1, otherwise return 1.2618return self._new_c(self.__modulus.int32 != 1)2619cdef bint invert = False2620if long_exp < 0:2621invert = True2622long_exp = -long_exp2623res = mod_pow_int(self.ivalue, long_exp, self.__modulus.int32)2624if invert:2625return ~self._new_c(res)2626else:2627return self._new_c(res)26282629def __invert__(IntegerMod_int self):2630"""2631Return the multiplicative inverse of self.26322633EXAMPLES::26342635sage: ~mod(7,100)2636432637sage: Mod(0,1)^-1263802639"""2640if self.__modulus.inverses is not None:2641x = self.__modulus.inverses[self.ivalue]2642if x is None:2643raise ZeroDivisionError, "Inverse does not exist."2644else:2645return x2646else:2647return self._new_c(mod_inverse_int(self.ivalue, self.__modulus.int32))26482649def lift(IntegerMod_int self):2650"""2651Lift an integer modulo `n` to the integers.26522653EXAMPLES::26542655sage: a = Mod(8943, 2^10); type(a)2656<type 'sage.rings.finite_rings.integer_mod.IntegerMod_int'>2657sage: lift(a)26587512659sage: a.lift()26607512661"""2662cdef sage.rings.integer.Integer z2663z = sage.rings.integer.Integer()2664mpz_set_si(z.value, self.ivalue)2665return z26662667def __float__(IntegerMod_int self):2668return <double>self.ivalue26692670def __hash__(self):2671"""2672EXAMPLES::26732674sage: a = Mod(89, 2^10)2675sage: hash(a)2676892677"""2678return hash(self.ivalue)26792680cdef bint is_square_c(self) except -2:2681cdef int_fast32_t l2, lodd, m2, modd2682if self.ivalue <= 1:2683return 12684# We first try to rule out self being a square without2685# factoring the modulus.2686lift = self.lift()2687m2, modd = self.modulus().val_unit(2)2688if m2 == 2:2689if self.ivalue & 2 == 2: # self.ivalue = 2 or 3 (mod 4)2690return 02691elif m2 > 2:2692l2, lodd = lift.val_unit(2)2693if l2 < m2 and (l2 % 2 == 1 or lodd % (1 << min(3, m2 - l2)) != 1):2694return 02695# self is a square modulo 2^m2. We compute the Jacobi symbol2696# modulo modd. If this is -1, then self is not a square.2697if jacobi_int(self.ivalue, modd) == -1:2698return 02699# We need to factor the modulus. We do it here instead of2700# letting PARI do it, so that we can cache the factorisation.2701return lift._pari_().Zn_issquare(self._parent.factored_order()._pari_())27022703def sqrt(self, extend=True, all=False):2704r"""2705Returns square root or square roots of ``self`` modulo2706`n`.27072708INPUT:270927102711- ``extend`` - bool (default: ``True``);2712if ``True``, return a square root in an extension ring,2713if necessary. Otherwise, raise a ``ValueError`` if the2714square root is not in the base ring.27152716- ``all`` - bool (default: ``False``); if2717``True``, return {all} square roots of self, instead of2718just one.271927202721ALGORITHM: Calculates the square roots mod `p` for each of2722the primes `p` dividing the order of the ring, then lifts2723them `p`-adically and uses the CRT to find a square root2724mod `n`.27252726See also ``square_root_mod_prime_power`` and2727``square_root_mod_prime`` (in this module) for more2728algorithmic details.27292730EXAMPLES::27312732sage: mod(-1, 17).sqrt()273342734sage: mod(5, 389).sqrt()2735862736sage: mod(7, 18).sqrt()273752738sage: a = mod(14, 5^60).sqrt()2739sage: a*a2740142741sage: mod(15, 389).sqrt(extend=False)2742Traceback (most recent call last):2743...2744ValueError: self must be a square2745sage: Mod(1/9, next_prime(2^40)).sqrt()^(-2)274692747sage: Mod(1/25, next_prime(2^90)).sqrt()^(-2)27482527492750::27512752sage: a = Mod(3,5); a275332754sage: x = Mod(-1, 360)2755sage: x.sqrt(extend=False)2756Traceback (most recent call last):2757...2758ValueError: self must be a square2759sage: y = x.sqrt(); y2760sqrt3592761sage: y.parent()2762Univariate Quotient Polynomial Ring in sqrt359 over Ring of integers modulo 360 with modulus x^2 + 12763sage: y^2276435927652766We compute all square roots in several cases::27672768sage: R = Integers(5*2^3*3^2); R2769Ring of integers modulo 3602770sage: R(40).sqrt(all=True)2771[20, 160, 200, 340]2772sage: [x for x in R if x^2 == 40] # Brute force verification2773[20, 160, 200, 340]2774sage: R(1).sqrt(all=True)2775[1, 19, 71, 89, 91, 109, 161, 179, 181, 199, 251, 269, 271, 289, 341, 359]2776sage: R(0).sqrt(all=True)2777[0, 60, 120, 180, 240, 300]2778sage: GF(107)(0).sqrt(all=True)2779[0]27802781::27822783sage: R = Integers(5*13^3*37); R2784Ring of integers modulo 4064452785sage: v = R(-1).sqrt(all=True); v2786[78853, 111808, 160142, 193097, 213348, 246303, 294637, 327592]2787sage: [x^2 for x in v]2788[406444, 406444, 406444, 406444, 406444, 406444, 406444, 406444]2789sage: v = R(169).sqrt(all=True); min(v), -max(v), len(v)2790(13, 13, 104)2791sage: all([x^2==169 for x in v])2792True27932794Modulo a power of 2::27952796sage: R = Integers(2^7); R2797Ring of integers modulo 1282798sage: a = R(17)2799sage: a.sqrt()2800232801sage: a.sqrt(all=True)2802[23, 41, 87, 105]2803sage: [x for x in R if x^2==17]2804[23, 41, 87, 105]2805"""2806cdef int_fast32_t i, n = self.__modulus.int322807if n > 100:2808moduli = self._parent.factored_order()2809# Unless the modulus is tiny, test to see if we're in the really2810# easy case of n prime, n = 3 mod 4.2811if n > 100 and n % 4 == 3 and len(moduli) == 1 and moduli[0][1] == 1:2812if jacobi_int(self.ivalue, self.__modulus.int32) == 1:2813# it's a non-zero square, sqrt(a) = a^(p+1)/42814i = mod_pow_int(self.ivalue, (self.__modulus.int32+1)/4, n)2815if i > n/2:2816i = n-i2817if all:2818return [self._new_c(i), self._new_c(n-i)]2819else:2820return self._new_c(i)2821elif self.ivalue == 0:2822return [self] if all else self2823elif not extend:2824raise ValueError, "self must be a square"2825# Now we use a heuristic to guess whether or not it will2826# be faster to just brute-force search for squares in a c loop...2827# TODO: more tuning?2828elif n <= 100 or n / (1 << len(moduli)) < 5000:2829if all:2830return [self._new_c(i) for i from 0 <= i < n if (i*i) % n == self.ivalue]2831else:2832for i from 0 <= i <= n/2:2833if (i*i) % n == self.ivalue:2834return self._new_c(i)2835if not extend:2836if all:2837return []2838raise ValueError, "self must be a square"2839# Either it failed but extend was True, or the generic algorithm is better2840return IntegerMod_abstract.sqrt(self, extend=extend, all=all)284128422843def _balanced_abs(self):2844"""2845This function returns `x` or `-x`, whichever has a2846positive representative in `-n/2 < x \leq n/2`.2847"""2848if self.ivalue > self.__modulus.int32 / 2:2849return -self2850else:2851return self28522853@coerce_binop2854def gcd(self, IntegerMod_int other):2855"""2856Greatest common divisor28572858Returns the "smallest" generator in `\ZZ / N\ZZ` of the ideal2859generated by ``self`` and ``other``.28602861INPUT:28622863- ``other`` -- an element of the same ring as this one.28642865EXAMPLES::28662867sage: R = Zmod(60); S = Zmod(72)2868sage: a = R(40).gcd(S(30)); a286922870sage: a.parent()2871Ring of integers modulo 122872sage: b = R(17).gcd(60); b287312874sage: b.parent()2875Ring of integers modulo 6028762877sage: mod(72*5, 3^3*2^2*17^2).gcd(mod(48*17, 3^3*2^2*17^2))2878122879sage: mod(0,1).gcd(mod(0,1))288002881"""2882cdef int_fast32_t g = gcd_int(self.ivalue, self.__modulus.int32)2883g = gcd_int(g, other.ivalue)2884if g == self.__modulus.int32: # self = other = 02885g = 02886return self._new_c(g)28872888### End of class288928902891cdef int_fast32_t gcd_int(int_fast32_t a, int_fast32_t b):2892"""2893Returns the gcd of a and b28942895For use with IntegerMod_int28962897AUTHORS:28982899- Robert Bradshaw2900"""2901cdef int_fast32_t tmp2902if a < b:2903tmp = b2904b = a2905a = tmp2906while b:2907tmp = b2908b = a % b2909a = tmp2910return a291129122913cdef int_fast32_t mod_inverse_int(int_fast32_t x, int_fast32_t n) except 0:2914"""2915Returns y such that xy=1 mod n29162917For use in IntegerMod_int29182919AUTHORS:29202921- Robert Bradshaw2922"""2923cdef int_fast32_t tmp, a, b, last_t, t, next_t, q2924if n == 1:2925return 02926a = n2927b = x2928t = 02929next_t = 12930while b:2931# a = s * n + t * x2932if b == 1:2933next_t = next_t % n2934if next_t < 0:2935next_t = next_t + n2936return next_t2937q = a / b2938tmp = b2939b = a % b2940a = tmp2941last_t = t2942t = next_t2943next_t = last_t - q * t2944raise ZeroDivisionError, "Inverse does not exist."294529462947cdef int_fast32_t mod_pow_int(int_fast32_t base, int_fast32_t exp, int_fast32_t n):2948"""2949Returns base^exp mod n29502951For use in IntegerMod_int29522953EXAMPLES::29542955sage: z = Mod(2, 256)2956sage: z^82957029582959AUTHORS:29602961- Robert Bradshaw2962"""2963cdef int_fast32_t prod, pow22964if exp <= 5:2965if exp == 0: return 12966if exp == 1: return base2967prod = base * base % n2968if exp == 2: return prod2969if exp == 3: return (prod * base) % n2970if exp == 4: return (prod * prod) % n29712972pow2 = base2973if exp % 2: prod = base2974else: prod = 12975exp = exp >> 12976while(exp != 0):2977pow2 = pow2 * pow22978if pow2 >= INTEGER_MOD_INT32_LIMIT: pow2 = pow2 % n2979if exp % 2:2980prod = prod * pow22981if prod >= INTEGER_MOD_INT32_LIMIT: prod = prod % n2982exp = exp >> 129832984if prod >= n:2985prod = prod % n2986return prod298729882989cdef int jacobi_int(int_fast32_t a, int_fast32_t m) except -2:2990"""2991Calculates the jacobi symbol (a/n)29922993For use in IntegerMod_int29942995AUTHORS:29962997- Robert Bradshaw2998"""2999cdef int s, jacobi = 13000cdef int_fast32_t b30013002a = a % m30033004while 1:3005if a == 0:3006return 0 # gcd was nontrivial3007elif a == 1:3008return jacobi3009s = 03010while (1 << s) & a == 0:3011s += 13012b = a >> s3013# Now a = 2^s * b30143015# factor out (2/m)^s term3016if s % 2 == 1 and (m % 8 == 3 or m % 8 == 5):3017jacobi = -jacobi30183019if b == 1:3020return jacobi30213022# quadratic reciprocity3023if b % 4 == 3 and m % 4 == 3:3024jacobi = -jacobi3025a = m % b3026m = b30273028######################################################################3029# class IntegerMod_int643030######################################################################30313032cdef class IntegerMod_int64(IntegerMod_abstract):3033"""3034Elements of `\ZZ/n\ZZ` for n small enough to3035be operated on in 64 bits30363037AUTHORS:30383039- Robert Bradshaw (2006-09-14)3040"""30413042def __init__(self, parent, value, empty=False):3043"""3044EXAMPLES::30453046sage: a = Mod(10,3^10); a3047103048sage: type(a)3049<type 'sage.rings.finite_rings.integer_mod.IntegerMod_int64'>3050sage: loads(a.dumps()) == a3051True3052sage: Mod(5, 2^31)305353054"""3055IntegerMod_abstract.__init__(self, parent)3056if empty:3057return3058cdef int_fast64_t x3059if PY_TYPE_CHECK(value, int):3060x = value3061self.ivalue = x % self.__modulus.int643062if self.ivalue < 0:3063self.ivalue = self.ivalue + self.__modulus.int643064return3065cdef sage.rings.integer.Integer z3066if PY_TYPE_CHECK(value, sage.rings.integer.Integer):3067z = value3068elif PY_TYPE_CHECK(value, rational.Rational):3069z = value % self.__modulus.sageInteger3070else:3071z = sage.rings.integer_ring.Z(value)3072self.set_from_mpz(z.value)30733074cdef IntegerMod_int64 _new_c(self, int_fast64_t value):3075cdef IntegerMod_int64 x3076x = PY_NEW(IntegerMod_int64)3077x.__modulus = self.__modulus3078x._parent = self._parent3079x.ivalue = value3080return x30813082cdef void set_from_mpz(self, mpz_t value):3083if mpz_sgn(value) == -1 or mpz_cmp_si(value, self.__modulus.int64) >= 0:3084self.ivalue = mpz_fdiv_ui(value, self.__modulus.int64)3085else:3086self.ivalue = mpz_get_si(value)30873088cdef void set_from_long(self, long value):3089self.ivalue = value % self.__modulus.int6430903091cdef void set_from_int(IntegerMod_int64 self, int_fast64_t ivalue):3092if ivalue < 0:3093self.ivalue = self.__modulus.int64 + (ivalue % self.__modulus.int64) # Is ivalue % self.__modulus.int64 actually negative?3094elif ivalue >= self.__modulus.int64:3095self.ivalue = ivalue % self.__modulus.int643096else:3097self.ivalue = ivalue30983099cdef int_fast64_t get_int_value(IntegerMod_int64 self):3100return self.ivalue310131023103cdef int _cmp_c_impl(self, Element right) except -2:3104"""3105EXAMPLES::31063107sage: mod(5,13^5) == mod(13^5+5,13^5)3108True3109sage: mod(5,13^5) == mod(8,13^5)3110False3111sage: mod(5,13^5) == mod(5,13)3112True3113sage: mod(0, 13^5) == 03114True3115sage: mod(0, 13^5) == int(0)3116True3117"""3118if self.ivalue == (<IntegerMod_int64>right).ivalue: return 03119elif self.ivalue < (<IntegerMod_int64>right).ivalue: return -13120else: return 131213122def __richcmp__(left, right, int op):3123return (<Element>left)._richcmp(right, op)312431253126cpdef bint is_one(IntegerMod_int64 self):3127"""3128Returns ``True`` if this is `1`, otherwise3129``False``.31303131EXAMPLES::31323133sage: (mod(-1,5^10)^2).is_one()3134True3135sage: mod(0,5^10).is_one()3136False3137"""3138return self.ivalue == 131393140def __nonzero__(IntegerMod_int64 self):3141"""3142Returns ``True`` if this is not `0`, otherwise3143``False``.31443145EXAMPLES::31463147sage: mod(13,5^10).is_zero()3148False3149sage: mod(5^12,5^10).is_zero()3150True3151"""3152return self.ivalue != 031533154cpdef bint is_unit(IntegerMod_int64 self):3155"""3156Return True iff this element is a unit.31573158EXAMPLES::31593160sage: mod(13, 5^10).is_unit()3161True3162sage: mod(25, 5^10).is_unit()3163False3164"""3165return gcd_int64(self.ivalue, self.__modulus.int64) == 131663167def __crt(IntegerMod_int64 self, IntegerMod_int64 other):3168"""3169Use the Chinese Remainder Theorem to find an element of the3170integers modulo the product of the moduli that reduces to self and3171to other. The modulus of other must be coprime to the modulus of3172self.31733174EXAMPLES::31753176sage: a = mod(3,5^10)3177sage: b = mod(2,7)3178sage: a.crt(b)3179292968783180sage: type(a.crt(b)) == type(b.crt(a)) and type(a.crt(b)) == type(mod(1, 7 * 5^10))3181True31823183::31843185sage: a = mod(3,10^10)3186sage: b = mod(2,9)3187sage: a.crt(b)3188800000000033189sage: type(a.crt(b)) == type(b.crt(a)) and type(a.crt(b)) == type(mod(1, 9 * 10^10))3190True31913192AUTHORS:31933194- Robert Bradshaw3195"""3196cdef IntegerMod_int64 lift3197cdef int_fast64_t x31983199import integer_mod_ring3200lift = IntegerMod_int64(integer_mod_ring.IntegerModRing(self.__modulus.int64 * other.__modulus.int64), None, empty=True)32013202try:3203x = (other.ivalue - self.ivalue % other.__modulus.int64) * mod_inverse_int64(self.__modulus.int64, other.__modulus.int64)3204lift.set_from_int( x * self.__modulus.int64 + self.ivalue )3205return lift3206except ZeroDivisionError:3207raise ZeroDivisionError, "moduli must be coprime"32083209def __copy__(IntegerMod_int64 self):3210return self._new_c(self.ivalue)32113212cpdef ModuleElement _add_(self, ModuleElement right):3213"""3214EXAMPLES::32153216sage: R = Integers(10^5)3217sage: R(7) + R(8)3218153219"""3220cdef int_fast64_t x3221x = self.ivalue + (<IntegerMod_int64>right).ivalue3222if x >= self.__modulus.int64:3223x = x - self.__modulus.int643224return self._new_c(x)32253226cpdef ModuleElement _iadd_(self, ModuleElement right):3227"""3228EXAMPLES::32293230sage: R = Integers(10^5)3231sage: R(7) + R(8)3232153233"""3234cdef int_fast64_t x3235x = self.ivalue + (<IntegerMod_int64>right).ivalue3236if x >= self.__modulus.int64:3237x = x - self.__modulus.int643238self.ivalue = x3239return self32403241cpdef ModuleElement _sub_(self, ModuleElement right):3242"""3243EXAMPLES::32443245sage: R = Integers(10^5)3246sage: R(7) - R(8)3247999993248"""3249cdef int_fast64_t x3250x = self.ivalue - (<IntegerMod_int64>right).ivalue3251if x < 0:3252x = x + self.__modulus.int643253return self._new_c(x)32543255cpdef ModuleElement _isub_(self, ModuleElement right):3256"""3257EXAMPLES::32583259sage: R = Integers(10^5)3260sage: R(7) - R(8)3261999993262"""3263cdef int_fast64_t x3264x = self.ivalue - (<IntegerMod_int64>right).ivalue3265if x < 0:3266x = x + self.__modulus.int643267self.ivalue = x3268return self32693270cpdef ModuleElement _neg_(self):3271"""3272EXAMPLES::32733274sage: -mod(7,10^5)3275999933276sage: -mod(0,10^6)327703278"""3279if self.ivalue == 0:3280return self3281return self._new_c(self.__modulus.int64 - self.ivalue)32823283cpdef RingElement _mul_(self, RingElement right):3284"""3285EXAMPLES::32863287sage: R = Integers(10^5)3288sage: R(700) * R(800)3289600003290"""3291return self._new_c((self.ivalue * (<IntegerMod_int64>right).ivalue) % self.__modulus.int64)329232933294cpdef RingElement _imul_(self, RingElement right):3295"""3296EXAMPLES::32973298sage: R = Integers(10^5)3299sage: R(700) * R(800)3300600003301"""3302self.ivalue = (self.ivalue * (<IntegerMod_int64>right).ivalue) % self.__modulus.int643303return self33043305cpdef RingElement _div_(self, RingElement right):3306"""3307EXAMPLES::33083309sage: R = Integers(10^5)3310sage: R(2)/33311333343312"""3313return self._new_c((self.ivalue * mod_inverse_int64((<IntegerMod_int64>right).ivalue,3314self.__modulus.int64) ) % self.__modulus.int64)33153316def __int__(IntegerMod_int64 self):3317return self.ivalue33183319def __index__(self):3320"""3321Needed so integers modulo `n` can be used as list indices.33223323EXAMPLES::33243325sage: v = [1,2,3,4,5]3326sage: v[Mod(3, 2^20)]332743328"""3329return self.ivalue33303331def __long__(IntegerMod_int64 self):3332return self.ivalue33333334def __mod__(IntegerMod_int64 self, right):3335right = int(right)3336if self.__modulus.int64 % right != 0:3337raise ZeroDivisionError, "reduction modulo right not defined."3338import integer_mod_ring3339return integer_mod_ring.IntegerModRing(right)(self)33403341def __lshift__(IntegerMod_int64 self, k):3342r"""3343Performs a left shift by ``k`` bits.33443345For details, see :meth:`shift`.33463347EXAMPLES::33483349sage: e = Mod(5, 2^31 - 1)3350sage: e << 323351103352sage: e * 2^323353103354"""3355return self.shift(int(k))33563357def __rshift__(IntegerMod_int64 self, k):3358r"""3359Performs a right shift by ``k`` bits.33603361For details, see :meth:`shift`.33623363EXAMPLES::33643365sage: e = Mod(5, 2^31 - 1)3366sage: e >> 1336723368"""3369return self.shift(-int(k))33703371cdef shift(IntegerMod_int64 self, int k):3372"""3373Performs a bit-shift specified by ``k`` on ``self``.33743375Suppose that ``self`` represents an integer `x` modulo `n`. If `k` is3376`k = 0`, returns `x`. If `k > 0`, shifts `x` to the left, that is,3377multiplies `x` by `2^k` and then returns the representative in the3378range `[0,n)`. If `k < 0`, shifts `x` to the right, that is, returns3379the integral part of `x` divided by `2^k`.33803381Note that, in any case, ``self`` remains unchanged.33823383INPUT:33843385- ``k`` - Integer of type ``int``33863387OUTPUT:33883389- Result of type ``IntegerMod_int64``33903391WARNING:33923393For positive ``k``, if ``x << k`` overflows as a 64-bit integer, the3394result is meaningless.33953396EXAMPLES::33973398sage: e = Mod(5, 2^31 - 1)3399sage: e << 323400103401sage: e * 2^323402103403sage: e = Mod(5, 2^31 - 1)3404sage: e >> 1340523406"""3407if k == 0:3408return self3409elif k > 0:3410return self._new_c((self.ivalue << k) % self.__modulus.int64)3411else:3412return self._new_c(self.ivalue >> (-k))34133414def __pow__(IntegerMod_int64 self, exp, m): # NOTE: m ignored, always use modulus of parent ring3415"""3416EXAMPLES:3417sage: R = Integers(10)3418sage: R(2)^10341943420sage: p = next_prime(10^5)3421sage: R = Integers(p)3422sage: R(1234)^(p-1)342313424sage: R = Integers(17^5)3425sage: R(17)^53426034273428sage: R(2)^-1 * 2342913430sage: R(2)^-1000000 * 2^1000000343113432sage: R(17)^-13433Traceback (most recent call last):3434...3435ZeroDivisionError: Inverse does not exist.3436sage: R(17)^-1000000003437Traceback (most recent call last):3438...3439ZeroDivisionError: Inverse does not exist.34403441TESTS::34423443sage: type(R(0))3444<type 'sage.rings.finite_rings.integer_mod.IntegerMod_int64'>34453446We define ``0^0`` to be unity, :trac:`13894`::34473448sage: p = next_prime(10^5)3449sage: R = Integers(p)3450sage: R(0)^03451134523453The value returned from ``0^0`` should belong to our ring::34543455sage: type(R(0)^0) == type(R(0))3456True34573458When the modulus is ``1``, the only element in the ring is3459``0`` (and it is equivalent to ``1``), so we return that3460instead::34613462sage: from sage.rings.finite_rings.integer_mod \3463... import IntegerMod_int643464sage: zero = IntegerMod_int64(Integers(1),0)3465sage: type(zero)3466<type 'sage.rings.finite_rings.integer_mod.IntegerMod_int64'>3467sage: zero^03468034693470"""3471cdef long long_exp3472cdef int_fast64_t res3473cdef mpz_t res_mpz3474if PyInt_CheckExact(exp) and -100000 < PyInt_AS_LONG(exp) < 100000:3475long_exp = PyInt_AS_LONG(exp)3476elif PY_TYPE_CHECK_EXACT(exp, Integer) and mpz_cmpabs_ui((<Integer>exp).value, 100000) == -1:3477long_exp = mpz_get_si((<Integer>exp).value)3478else:3479sig_on()3480try:3481mpz_init(res_mpz)3482base = self.lift()3483mpz_pow_helper(res_mpz, (<Integer>base).value, exp, self.__modulus.sageInteger.value)3484if mpz_fits_ulong_p(res_mpz):3485res = mpz_get_ui(res_mpz)3486else:3487res = mpz_get_pyintlong(res_mpz)3488return self._new_c(res)3489finally:3490mpz_clear(res_mpz)3491sig_off()34923493if long_exp == 0 and self.ivalue == 0:3494# Return 0 if the modulus is 1, otherwise return 1.3495return self._new_c(self.__modulus.int64 != 1)3496cdef bint invert = False3497if long_exp < 0:3498invert = True3499long_exp = -long_exp3500res = mod_pow_int64(self.ivalue, long_exp, self.__modulus.int64)3501if invert:3502return self._new_c(mod_inverse_int64(res, self.__modulus.int64))3503else:3504return self._new_c(res)35053506def __invert__(IntegerMod_int64 self):3507"""3508Return the multiplicative inverse of self.35093510EXAMPLES::35113512sage: a = mod(7,2^40); type(a)3513<type 'sage.rings.finite_rings.integer_mod.IntegerMod_gmp'>3514sage: ~a35154712192690473516sage: a351773518"""3519return self._new_c(mod_inverse_int64(self.ivalue, self.__modulus.int64))35203521def lift(IntegerMod_int64 self):3522"""3523Lift an integer modulo `n` to the integers.35243525EXAMPLES::35263527sage: a = Mod(8943, 2^25); type(a)3528<type 'sage.rings.finite_rings.integer_mod.IntegerMod_int64'>3529sage: lift(a)353089433531sage: a.lift()353289433533"""3534cdef sage.rings.integer.Integer z3535z = sage.rings.integer.Integer()3536mpz_set_si(z.value, self.ivalue)3537return z35383539def __float__(IntegerMod_int64 self):3540"""3541Coerce self to a float.35423543EXAMPLES::35443545sage: a = Mod(8943, 2^35)3546sage: float(a)35478943.03548"""3549return <double>self.ivalue35503551def __hash__(self):3552"""3553Compute hash of self.35543555EXAMPLES::35563557sage: a = Mod(8943, 2^35)3558sage: hash(a)355989433560"""35613562return hash(self.ivalue)35633564def _balanced_abs(self):3565"""3566This function returns `x` or `-x`, whichever has a3567positive representative in `-n/2 < x \leq n/2`.3568"""3569if self.ivalue > self.__modulus.int64 / 2:3570return -self3571else:3572return self35733574@coerce_binop3575def gcd(self, IntegerMod_int64 other):3576"""3577Greatest common divisor35783579Returns the "smallest" generator in `\ZZ / N\ZZ` of the ideal3580generated by ``self`` and ``other``.35813582INPUT:35833584- ``other`` -- an element of the same ring as this one.35853586EXAMPLES::35873588sage: mod(2^3*3^2*5, 3^3*2^2*17^5).gcd(mod(2^4*3*17, 3^3*2^2*17^5))3589123590sage: mod(0,17^5).gcd(mod(0,17^5))359103592"""3593cdef int_fast64_t g = gcd_int64(self.ivalue, self.__modulus.int64)3594g = gcd_int64(g, other.ivalue)3595if g == self.__modulus.int64: # self = other = 03596g = 03597return self._new_c(g)35983599### Helper functions36003601cdef mpz_pow_helper(mpz_t res, mpz_t base, object exp, mpz_t modulus):3602cdef bint invert = False3603cdef long long_exp36043605if PyInt_CheckExact(exp):3606long_exp = PyInt_AS_LONG(exp)3607if long_exp < 0:3608long_exp = -long_exp3609invert = True3610mpz_powm_ui(res, base, long_exp, modulus)3611else:3612if not PY_TYPE_CHECK_EXACT(exp, Integer):3613exp = Integer(exp)3614if mpz_sgn((<Integer>exp).value) < 0:3615exp = -exp3616invert = True3617mpz_powm(res, base, (<Integer>exp).value, modulus)3618if invert:3619if not mpz_invert(res, res, modulus):3620raise ZeroDivisionError, "Inverse does not exist."36213622cdef int_fast64_t gcd_int64(int_fast64_t a, int_fast64_t b):3623"""3624Returns the gcd of a and b36253626For use with IntegerMod_int6436273628AUTHORS:36293630- Robert Bradshaw3631"""3632cdef int_fast64_t tmp3633if a < b:3634tmp = b3635b = a3636a = tmp3637while b:3638tmp = b3639b = a % b3640a = tmp3641return a364236433644cdef int_fast64_t mod_inverse_int64(int_fast64_t x, int_fast64_t n) except 0:3645"""3646Returns y such that xy=1 mod n36473648For use in IntegerMod_int6436493650AUTHORS:36513652- Robert Bradshaw3653"""3654cdef int_fast64_t tmp, a, b, last_t, t, next_t, q3655a = n3656b = x3657t = 03658next_t = 13659while b:3660# a = s * n + t * x3661if b == 1:3662next_t = next_t % n3663if next_t < 0:3664next_t = next_t + n3665return next_t3666q = a / b3667tmp = b3668b = a % b3669a = tmp3670last_t = t3671t = next_t3672next_t = last_t - q * t3673raise ZeroDivisionError, "Inverse does not exist."367436753676cdef int_fast64_t mod_pow_int64(int_fast64_t base, int_fast64_t exp, int_fast64_t n):3677"""3678Returns base^exp mod n36793680For use in IntegerMod_int6436813682AUTHORS:36833684- Robert Bradshaw3685"""3686cdef int_fast64_t prod, pow23687if exp <= 5:3688if exp == 0: return 13689if exp == 1: return base3690prod = base * base % n3691if exp == 2: return prod3692if exp == 3: return (prod * base) % n3693if exp == 4: return (prod * prod) % n36943695pow2 = base3696if exp % 2: prod = base3697else: prod = 13698exp = exp >> 13699while(exp != 0):3700pow2 = pow2 * pow23701if pow2 >= INTEGER_MOD_INT64_LIMIT: pow2 = pow2 % n3702if exp % 2:3703prod = prod * pow23704if prod >= INTEGER_MOD_INT64_LIMIT: prod = prod % n3705exp = exp >> 137063707if prod >= n:3708prod = prod % n3709return prod371037113712cdef int jacobi_int64(int_fast64_t a, int_fast64_t m) except -2:3713"""3714Calculates the jacobi symbol (a/n)37153716For use in IntegerMod_int6437173718AUTHORS:37193720- Robert Bradshaw3721"""3722cdef int s, jacobi = 13723cdef int_fast64_t b37243725a = a % m37263727while 1:3728if a == 0:3729return 0 # gcd was nontrivial3730elif a == 1:3731return jacobi3732s = 03733while (1 << s) & a == 0:3734s += 13735b = a >> s3736# Now a = 2^s * b37373738# factor out (2/m)^s term3739if s % 2 == 1 and (m % 8 == 3 or m % 8 == 5):3740jacobi = -jacobi37413742if b == 1:3743return jacobi37443745# quadratic reciprocity3746if b % 4 == 3 and m % 4 == 3:3747jacobi = -jacobi3748a = m % b3749m = b375037513752########################3753# Square root functions3754########################37553756def square_root_mod_prime_power(IntegerMod_abstract a, p, e):3757r"""3758Calculates the square root of `a`, where `a` is an3759integer mod `p^e`.37603761ALGORITHM: Perform `p`-adically by stripping off even3762powers of `p` to get a unit and lifting3763`\sqrt{unit} \bmod p` via Newton's method.37643765AUTHORS:37663767- Robert Bradshaw37683769EXAMPLES::37703771sage: from sage.rings.finite_rings.integer_mod import square_root_mod_prime_power3772sage: a=Mod(17,2^20)3773sage: b=square_root_mod_prime_power(a,2,20)3774sage: b^2 == a3775True37763777::37783779sage: a=Mod(72,97^10)3780sage: b=square_root_mod_prime_power(a,97,10)3781sage: b^2 == a3782True3783"""3784if a.is_zero() or a.is_one():3785return a37863787if p == 2:3788if e == 1:3789return a3790# TODO: implement something that isn't totally idiotic.3791for x in a.parent():3792if x**2 == a:3793return x37943795# strip off even powers of p3796cdef int i, val = a.lift().valuation(p)3797if val % 2 == 1:3798raise ValueError, "self must be a square."3799if val > 0:3800unit = a._parent(a.lift() // p**val)3801else:3802unit = a38033804# find square root of unit mod p3805x = unit.parent()(square_root_mod_prime(mod(unit, p), p))38063807# lift p-adically using Newton iteration3808# this is done to higher precision than necessary except at the last step3809one_half = ~(a._new_c_from_long(2))3810for i from 0 <= i < ceil(log(e)/log(2)) - val/2:3811x = (x+unit/x) * one_half38123813# multiply in powers of p (if any)3814if val > 0:3815x *= p**(val // 2)3816return x38173818cpdef square_root_mod_prime(IntegerMod_abstract a, p=None):3819r"""3820Calculates the square root of `a`, where `a` is an3821integer mod `p`; if `a` is not a perfect square,3822this returns an (incorrect) answer without checking.38233824ALGORITHM: Several cases based on residue class of3825`p \bmod 16`.382638273828- `p \bmod 2 = 0`: `p = 2` so3829`\sqrt{a} = a`.38303831- `p \bmod 4 = 3`: `\sqrt{a} = a^{(p+1)/4}`.38323833- `p \bmod 8 = 5`: `\sqrt{a} = \zeta i a` where3834`\zeta = (2a)^{(p-5)/8}`, `i=\sqrt{-1}`.38353836- `p \bmod 16 = 9`: Similar, work in a bi-quadratic3837extension of `\GF{p}` for small `p`, Tonelli3838and Shanks for large `p`.38393840- `p \bmod 16 = 1`: Tonelli and Shanks.384138423843REFERENCES:38443845- Siguna Muller. 'On the Computation of Square Roots in Finite3846Fields' Designs, Codes and Cryptography, Volume 31, Issue 33847(March 2004)38483849- A. Oliver L. Atkin. 'Probabilistic primality testing' (Chapter385030, Section 4) In Ph. Flajolet and P. Zimmermann, editors,3851Algorithms Seminar, 1991-1992. INRIA Research Report 1779, 1992,3852http://www.inria.fr/rrrt/rr-1779.html. Summary by F. Morain.3853http://citeseer.ist.psu.edu/atkin92probabilistic.html38543855- H. Postl. 'Fast evaluation of Dickson Polynomials' Contrib. to3856General Algebra, Vol. 6 (1988) pp. 223-22538573858AUTHORS:38593860- Robert Bradshaw38613862TESTS: Every case appears in the first hundred primes.38633864::38653866sage: from sage.rings.finite_rings.integer_mod import square_root_mod_prime # sqrt() uses brute force for small p3867sage: all([square_root_mod_prime(a*a)^2 == a*a3868... for p in prime_range(100)3869... for a in Integers(p)])3870True3871"""3872if not a or a.is_one():3873return a38743875if p is None:3876p = a._parent.order()3877if p < PyInt_GetMax():3878p = int(p)38793880cdef int p_mod_16 = p % 163881cdef double bits = log(float(p))/log(2)3882cdef long r, m38833884cdef Integer resZ388538863887if p_mod_16 % 2 == 0: # p == 23888return a38893890elif p_mod_16 % 4 == 3:3891return a ** ((p+1)//4)38923893elif p_mod_16 % 8 == 5:3894two_a = a+a3895zeta = two_a ** ((p-5)//8)3896i = zeta**2 * two_a # = two_a ** ((p-1)//4)3897return zeta*a*(i-1)38983899elif p_mod_16 == 9 and bits < 500:3900two_a = a+a3901s = two_a ** ((p-1)//4)3902if s.is_one():3903d = a._parent.quadratic_nonresidue()3904d2 = d*d3905z = (two_a * d2) ** ((p-9)//16)3906i = two_a * d2 * z*z3907return z*d*a*(i-1)3908else:3909z = two_a ** ((p-9)//16)3910i = two_a * z*z3911return z*a*(i-1)39123913else:3914one = a._new_c_from_long(1)3915r, q = (p-one_Z).val_unit(2)3916v = a._parent.quadratic_nonresidue()**q39173918x = a ** ((q-1)//2)3919b = a*x*x # a ^ q3920res = a*x # a ^ ((q-1)/2)39213922while b != one:3923m = 13924bpow = b*b3925while bpow != one:3926bpow *= bpow3927m += 13928g = v**(one_Z << (r-m-1)) # v^(2^(r-m-1))3929res *= g3930b *= g*g3931return res39323933def lucas_q1(mm, IntegerMod_abstract P):3934"""3935Return `V_k(P, 1)` where `V_k` is the Lucas3936function defined by the recursive relation39373938`V_k(P, Q) = PV_{k-1}(P, Q) - QV_{k-2}(P, Q)`39393940with `V_0 = 2, V_1(P_Q) = P`.39413942REFERENCES:39433944.. [Pos88] H. Postl. 'Fast evaluation of Dickson Polynomials' Contrib. to3945General Algebra, Vol. 6 (1988) pp. 223-22539463947AUTHORS:39483949- Robert Bradshaw39503951TESTS::39523953sage: from sage.rings.finite_rings.integer_mod import lucas_q13954sage: all([lucas_q1(k, a) == BinaryRecurrenceSequence(a, -1, 2, a)(k)3955....: for a in Integers(23)3956....: for k in range(13)])3957True3958"""3959if mm == 0:3960return 23961elif mm == 1:3962return P39633964cdef sage.rings.integer.Integer m3965m = <sage.rings.integer.Integer>mm if PY_TYPE_CHECK(mm, sage.rings.integer.Integer) else sage.rings.integer.Integer(mm)3966two = P._new_c_from_long(2)3967d1 = P3968d2 = P*P - two39693970sig_on()3971cdef int j3972for j from mpz_sizeinbase(m.value, 2)-1 > j > 0:3973if mpz_tstbit(m.value, j):3974d1 = d1*d2 - P3975d2 = d2*d2 - two3976else:3977d2 = d1*d2 - P3978d1 = d1*d1 - two3979sig_off()3980if mpz_odd_p(m.value):3981return d1*d2 - P3982else:3983return d1*d1 - two39843985from sage.misc.superseded import deprecated_function_alias3986fast_lucas = deprecated_function_alias(11802, lucas_q1)39873988def slow_lucas(k, P, Q=1):3989"""3990Lucas function defined using the standard definition, for3991consistency testing. This is deprecated in :trac:`11802`. Use3992``BinaryRecurrenceSequence(P, -Q, 2, P)(k)`` instead.39933994.. SEEALSO::39953996:class:`~sage.combinat.binary_recurrence_sequences.BinaryRecurrenceSequence`39973998REFERENCES:39994000- :wikipedia:`Lucas_sequence`40014002TESTS::40034004sage: from sage.rings.finite_rings.integer_mod import slow_lucas4005sage: [slow_lucas(k, 1, -1) for k in range(10)]4006doctest:...: DeprecationWarning: slow_lucas() is deprecated. Use BinaryRecurrenceSequence instead.4007See http://trac.sagemath.org/11802 for details.4008[2, 1, 3, 4, 7, 11, 18, 29, 47, 76]4009"""4010from sage.misc.superseded import deprecation4011deprecation(11802, 'slow_lucas() is deprecated. Use BinaryRecurrenceSequence instead.')4012if k == 0:4013return 24014elif k == 1:4015return P4016from sage.combinat.binary_recurrence_sequences import BinaryRecurrenceSequence4017B = BinaryRecurrenceSequence(P, -Q, 2, P)4018return B(k)40194020def lucas(k, P, Q=1, n=None):4021r"""4022Return `[V_k(P, Q) \mod n, Q^{\lfloor k/2 \rfloor} \mod n]` where `V_k`4023is the Lucas function defined by the recursive relation40244025.. MATH::40264027V_k(P, Q) = P V_{k-1}(P, Q) - Q V_{k-2}(P, Q)40284029with `V_0 = 2, V_1 = P`.40304031INPUT:40324033- ``k`` -- integer; index to compute40344035- ``P``, ``Q`` -- integers or modular integers; initial values40364037- ``n`` -- integer (optional); modulus to use if ``P`` is not a modular4038integer40394040REFERENCES:40414042.. [IEEEP1363] IEEE P1363 / D13 (Draft Version 13). Standard Specifications4043for Public Key Cryptography Annex A (Informative).4044Number-Theoretic Background. Section A.2.440454046AUTHORS:40474048- Somindu Chaya Ramanna, Shashank Singh and Srinivas Vivek Venkatesh4049(2011-09-15, ECC2011 summer school)40504051- Robert Bradshaw40524053TESTS::40544055sage: from sage.rings.finite_rings.integer_mod import lucas4056sage: p = randint(0,100000)4057sage: q = randint(0,100000)4058sage: n = randint(0,100)4059sage: all([lucas(k,p,q,n)[0] == Mod(lucas_number2(k,p,q),n)4060... for k in Integers(20)])4061True4062sage: from sage.rings.finite_rings.integer_mod import lucas4063sage: p = randint(0,100000)4064sage: q = randint(0,100000)4065sage: n = randint(0,100)4066sage: k = randint(0,100)4067sage: lucas(k,p,q,n) == [Mod(lucas_number2(k,p,q),n),Mod(q^(int(k/2)),n)]4068True40694070EXAMPLES::40714072sage: [lucas(k,4,5,11)[0] for k in range(30)]4073[2, 4, 6, 4, 8, 1, 8, 5, 2, 5, 10, 4, 10, 9, 8, 9, 7, 5, 7, 3, 10, 3, 6, 9, 6, 1, 7, 1, 2, 3]40744075sage: lucas(20,4,5,11)4076[10, 1]4077"""4078cdef IntegerMod_abstract p,q40794080if n is None and not is_IntegerMod(P):4081raise ValueError40824083if n is None:4084n = P.modulus()40854086if not is_IntegerMod(P):4087p = Mod(P,n)4088else:4089p = P40904091if not is_IntegerMod(Q):4092q = Mod(Q,n)4093else:4094q = Q40954096if k == 0:4097return [2, 1]4098elif k == 1:4099return [p, 1]41004101cdef sage.rings.integer.Integer m4102m = <sage.rings.integer.Integer>k if PY_TYPE_CHECK(k, sage.rings.integer.Integer) else sage.rings.integer.Integer(k)4103two = p._new_c_from_long(2)41044105v0 = p._new_c_from_long(2)4106v1 = p4107q0 = p._new_c_from_long(1)4108q1 = p._new_c_from_long(1)41094110sig_on()4111cdef int j4112for j from mpz_sizeinbase(m.value, 2)-1 >= j >= 0:4113q0 = q0*q14114if mpz_tstbit(m.value, j):4115q1 = q0*Q4116v0 = v0*v1 - p*q04117v1 = v1*v1 - two*q14118else:4119q1 = q04120v1 = v0*v1 - p*q04121v0 = v0*v0 - two*q04122sig_off()4123return [v0,q0]41244125############# Homomorphisms ###############41264127cdef class IntegerMod_hom(Morphism):4128cdef IntegerMod_abstract zero4129cdef NativeIntStruct modulus4130def __init__(self, parent):4131Morphism.__init__(self, parent)4132# we need to use element constructor so that we can register both coercions and conversions using these morphisms.4133self.zero = self._codomain._element_constructor_(0)4134self.modulus = self._codomain._pyx_order4135cpdef Element _call_(self, x):4136return IntegerMod(self.codomain(), x)41374138cdef class IntegerMod_to_IntegerMod(IntegerMod_hom):4139"""4140Very fast IntegerMod to IntegerMod homomorphism.41414142EXAMPLES::41434144sage: from sage.rings.finite_rings.integer_mod import IntegerMod_to_IntegerMod4145sage: Rs = [Integers(3**k) for k in range(1,30,5)]4146sage: [type(R(0)) for R in Rs]4147[<type 'sage.rings.finite_rings.integer_mod.IntegerMod_int'>, <type 'sage.rings.finite_rings.integer_mod.IntegerMod_int'>, <type 'sage.rings.finite_rings.integer_mod.IntegerMod_int64'>, <type 'sage.rings.finite_rings.integer_mod.IntegerMod_int64'>, <type 'sage.rings.finite_rings.integer_mod.IntegerMod_gmp'>, <type 'sage.rings.finite_rings.integer_mod.IntegerMod_gmp'>]4148sage: fs = [IntegerMod_to_IntegerMod(S, R) for R in Rs for S in Rs if S is not R and S.order() > R.order()]4149sage: all([f(-1) == f.codomain()(-1) for f in fs])4150True4151sage: [f(-1) for f in fs]4152[2, 2, 2, 2, 2, 728, 728, 728, 728, 177146, 177146, 177146, 43046720, 43046720, 10460353202]4153"""4154def __init__(self, R, S):4155if not S.order().divides(R.order()):4156raise TypeError, "No natural coercion from %s to %s" % (R, S)4157import sage.categories.homset4158IntegerMod_hom.__init__(self, sage.categories.homset.Hom(R, S))41594160cpdef Element _call_(self, x):4161cdef IntegerMod_abstract a4162if PY_TYPE_CHECK(x, IntegerMod_int):4163return (<IntegerMod_int>self.zero)._new_c((<IntegerMod_int>x).ivalue % self.modulus.int32)4164elif PY_TYPE_CHECK(x, IntegerMod_int64):4165return self.zero._new_c_from_long((<IntegerMod_int64>x).ivalue % self.modulus.int64)4166else: # PY_TYPE_CHECK(x, IntegerMod_gmp)4167a = self.zero._new_c_from_long(0)4168a.set_from_mpz((<IntegerMod_gmp>x).value)4169return a41704171def _repr_type(self):4172return "Natural"41734174cdef class Integer_to_IntegerMod(IntegerMod_hom):4175r"""4176Fast `\ZZ \rightarrow \ZZ/n\ZZ`4177morphism.41784179EXAMPLES:41804181We make sure it works for every type.41824183::41844185sage: from sage.rings.finite_rings.integer_mod import Integer_to_IntegerMod4186sage: Rs = [Integers(10), Integers(10^5), Integers(10^10)]4187sage: [type(R(0)) for R in Rs]4188[<type 'sage.rings.finite_rings.integer_mod.IntegerMod_int'>, <type 'sage.rings.finite_rings.integer_mod.IntegerMod_int64'>, <type 'sage.rings.finite_rings.integer_mod.IntegerMod_gmp'>]4189sage: fs = [Integer_to_IntegerMod(R) for R in Rs]4190sage: [f(-1) for f in fs]4191[9, 99999, 9999999999]4192"""4193def __init__(self, R):4194import sage.categories.homset4195IntegerMod_hom.__init__(self, sage.categories.homset.Hom(integer_ring.ZZ, R))41964197cpdef Element _call_(self, x):4198cdef IntegerMod_abstract a4199cdef Py_ssize_t res4200if self.modulus.table is not None:4201res = x % self.modulus.int644202if res < 0:4203res += self.modulus.int644204a = self.modulus.lookup(res)4205if a._parent is not self._codomain:4206a._parent = self._codomain4207# print (<Element>a)._parent, " is not ", parent4208return a4209else:4210a = self.zero._new_c_from_long(0)4211a.set_from_mpz((<Integer>x).value)4212return a42134214def _repr_type(self):4215return "Natural"42164217def section(self):4218return IntegerMod_to_Integer(self._codomain)42194220cdef class IntegerMod_to_Integer(Map):4221def __init__(self, R):4222import sage.categories.homset4223from sage.categories.all import Sets4224Morphism.__init__(self, sage.categories.homset.Hom(R, integer_ring.ZZ, Sets()))42254226cpdef Element _call_(self, x):4227cdef Integer ans = PY_NEW(Integer)4228if PY_TYPE_CHECK(x, IntegerMod_gmp):4229mpz_set(ans.value, (<IntegerMod_gmp>x).value)4230elif PY_TYPE_CHECK(x, IntegerMod_int):4231mpz_set_si(ans.value, (<IntegerMod_int>x).ivalue)4232elif PY_TYPE_CHECK(x, IntegerMod_int64):4233mpz_set_si(ans.value, (<IntegerMod_int64>x).ivalue)4234return ans42354236def _repr_type(self):4237return "Lifting"42384239cdef class Int_to_IntegerMod(IntegerMod_hom):4240"""4241EXAMPLES:42424243We make sure it works for every type.42444245::42464247sage: from sage.rings.finite_rings.integer_mod import Int_to_IntegerMod4248sage: Rs = [Integers(2**k) for k in range(1,50,10)]4249sage: [type(R(0)) for R in Rs]4250[<type 'sage.rings.finite_rings.integer_mod.IntegerMod_int'>, <type 'sage.rings.finite_rings.integer_mod.IntegerMod_int'>, <type 'sage.rings.finite_rings.integer_mod.IntegerMod_int64'>, <type 'sage.rings.finite_rings.integer_mod.IntegerMod_gmp'>, <type 'sage.rings.finite_rings.integer_mod.IntegerMod_gmp'>]4251sage: fs = [Int_to_IntegerMod(R) for R in Rs]4252sage: [f(-1) for f in fs]4253[1, 2047, 2097151, 2147483647, 2199023255551]4254"""4255def __init__(self, R):4256import sage.categories.homset4257from sage.structure.parent import Set_PythonType4258IntegerMod_hom.__init__(self, sage.categories.homset.Hom(Set_PythonType(int), R))42594260cpdef Element _call_(self, x):4261cdef IntegerMod_abstract a4262cdef long res = PyInt_AS_LONG(x)4263if PY_TYPE_CHECK(self.zero, IntegerMod_gmp):4264if 0 <= res < INTEGER_MOD_INT64_LIMIT:4265return self.zero._new_c_from_long(res)4266else:4267return IntegerMod_gmp(self.zero._parent, x)4268else:4269res %= self.modulus.int644270if res < 0:4271res += self.modulus.int644272if self.modulus.table is not None:4273a = self.modulus.lookup(res)4274if a._parent is not self._codomain:4275a._parent = self._codomain4276# print (<Element>a)._parent, " is not ", parent4277return a4278else:4279return self.zero._new_c_from_long(res)42804281def _repr_type(self):4282return "Native"428342844285