Path: blob/master/sage/rings/finite_rings/integer_mod.pyx
4058 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 * b5185112752"""5354#################################################################################55# Copyright (C) 2006 Robert Bradshaw <[email protected]>56# 2006 William Stein <[email protected]>57#58# Distributed under the terms of the GNU General Public License (GPL)59#60# http://www.gnu.org/licenses/61#*****************************************************************************626364include "../../ext/interrupt.pxi" # ctrl-c interrupt block support65include "../../ext/stdsage.pxi"66include "../../ext/python_int.pxi"6768cdef extern from "math.h":69double log(double)70int ceil(double)7172cdef extern from "mpz_pylong.h":73cdef mpz_get_pyintlong(mpz_t src)7475import operator7677cdef bint use_32bit_type(int_fast64_t modulus):78return modulus <= INTEGER_MOD_INT32_LIMIT7980## import arith81import sage.rings.rational as rational82from sage.libs.pari.all import pari, PariError83import sage.rings.integer_ring as integer_ring8485import sage.rings.commutative_ring_element as commutative_ring_element86import sage.interfaces.all8788import sage.rings.integer89import sage.rings.integer_ring90cimport sage.rings.integer91from sage.rings.integer cimport Integer9293import sage.structure.element94cimport sage.structure.element95from sage.structure.element cimport RingElement, ModuleElement, Element96from sage.categories.morphism cimport Morphism97from sage.categories.map cimport Map9899from sage.structure.sage_object import register_unpickle_override100101#from sage.structure.parent cimport Parent102103cdef Integer one_Z = Integer(1)104105def Mod(n, m, parent=None):106"""107Return the equivalence class of `n` modulo `m` as108an element of `\ZZ/m\ZZ`.109110EXAMPLES::111112sage: x = Mod(12345678, 32098203845329048)113sage: x11412345678115sage: x^1001161017322209155072117118You can also use the lowercase version::119120sage: mod(12,5)1212122123Illustrates that trac #5971 is fixed. Consider `n` modulo `m` when124`m = 0`. Then `\ZZ/0\ZZ` is isomorphic to `\ZZ` so `n` modulo `0` is125is equivalent to `n` for any integer value of `n`::126127sage: Mod(10, 0)12810129sage: a = randint(-100, 100)130sage: Mod(a, 0) == a131True132"""133# when m is zero, then ZZ/0ZZ is isomorphic to ZZ134if m == 0:135return n136137# m is non-zero, so return n mod m138cdef IntegerMod_abstract x139import integer_mod_ring140x = IntegerMod(integer_mod_ring.IntegerModRing(m), n)141if parent is None:142return x143x._parent = parent144return x145146147mod = Mod148149register_unpickle_override('sage.rings.integer_mod', 'Mod', Mod)150register_unpickle_override('sage.rings.integer_mod', 'mod', mod)151152def IntegerMod(parent, value):153"""154Create an integer modulo `n` with the given parent.155156This is mainly for internal use.157"""158cdef NativeIntStruct modulus159cdef Py_ssize_t res160modulus = parent._pyx_order161if modulus.table is not None:162if PY_TYPE_CHECK(value, sage.rings.integer.Integer) or PY_TYPE_CHECK(value, int) or PY_TYPE_CHECK(value, long):163res = value % modulus.int64164if res < 0:165res = res + modulus.int64166a = modulus.lookup(res)167if (<Element>a)._parent is not parent:168(<Element>a)._parent = parent169# print (<Element>a)._parent, " is not ", parent170return a171if modulus.int32 != -1:172return IntegerMod_int(parent, value)173elif modulus.int64 != -1:174return IntegerMod_int64(parent, value)175else:176return IntegerMod_gmp(parent, value)177178def is_IntegerMod(x):179"""180Return ``True`` if and only if x is an integer modulo181`n`.182183EXAMPLES::184185sage: from sage.rings.finite_rings.integer_mod import is_IntegerMod186sage: is_IntegerMod(5)187False188sage: is_IntegerMod(Mod(5,10))189True190"""191return PY_TYPE_CHECK(x, IntegerMod_abstract)192193def makeNativeIntStruct(sage.rings.integer.Integer z):194"""195Function to convert a Sage Integer into class NativeIntStruct.196197.. note::198199This function seems completely redundant, and is not used200anywhere.201"""202return NativeIntStruct(z)203204register_unpickle_override('sage.rings.integer_mod', 'makeNativeIntStruct', makeNativeIntStruct)205206cdef class NativeIntStruct:207"""208We store the various forms of the modulus here rather than in the209parent for efficiency reasons.210211We may also store a cached table of all elements of a given ring in212this class.213"""214def __init__(NativeIntStruct self, sage.rings.integer.Integer z):215self.int64 = -1216self.int32 = -1217self.table = None # NULL218self.sageInteger = z219if mpz_cmp_si(z.value, INTEGER_MOD_INT64_LIMIT) <= 0:220self.int64 = mpz_get_si(z.value)221if use_32bit_type(self.int64):222self.int32 = self.int64223224def __reduce__(NativeIntStruct self):225return sage.rings.finite_rings.integer_mod.makeNativeIntStruct, (self.sageInteger, )226227def precompute_table(NativeIntStruct self, parent, inverses=True):228"""229Function to compute and cache all elements of this class.230231If inverses==True, also computes and caches the inverses of the232invertible elements233"""234self.table = PyList_New(self.int64)235cdef Py_ssize_t i236if self.int32 != -1:237for i from 0 <= i < self.int32:238z = IntegerMod_int(parent, i)239Py_INCREF(z); PyList_SET_ITEM(self.table, i, z)240else:241for i from 0 <= i < self.int64:242z = IntegerMod_int64(parent, i)243Py_INCREF(z); PyList_SET_ITEM(self.table, i, z)244245if inverses:246tmp = [None] * self.int64247for i from 1 <= i < self.int64:248try:249tmp[i] = ~self.table[i]250except ZeroDivisionError:251pass252self.inverses = tmp253254def _get_table(self):255return self.table256257cdef lookup(NativeIntStruct self, Py_ssize_t value):258return <object>PyList_GET_ITEM(self.table, value)259260261cdef class IntegerMod_abstract(FiniteRingElement):262263def __init__(self, parent):264"""265EXAMPLES::266267sage: a = Mod(10,30^10); a26810269sage: loads(a.dumps()) == a270True271"""272self._parent = parent273self.__modulus = parent._pyx_order274275276cdef _new_c_from_long(self, long value):277cdef IntegerMod_abstract x278x = <IntegerMod_abstract>PY_NEW(<object>PY_TYPE(self))279if PY_TYPE_CHECK(x, IntegerMod_gmp):280mpz_init((<IntegerMod_gmp>x).value) # should be done by the new method281x._parent = self._parent282x.__modulus = self.__modulus283x.set_from_long(value)284return x285286cdef void set_from_mpz(self, mpz_t value):287raise NotImplementedError, "Must be defined in child class."288289cdef void set_from_long(self, long value):290raise NotImplementedError, "Must be defined in child class."291292def __abs__(self):293"""294Raise an error message, since ``abs(x)`` makes no sense295when ``x`` is an integer modulo `n`.296297EXAMPLES::298299sage: abs(Mod(2,3))300Traceback (most recent call last):301...302ArithmeticError: absolute valued not defined on integers modulo n.303"""304raise ArithmeticError, "absolute valued not defined on integers modulo n."305306def __reduce__(IntegerMod_abstract self):307"""308EXAMPLES::309310sage: a = Mod(4,5); a3114312sage: loads(a.dumps()) == a313True314sage: a = Mod(-1,5^30)^25;315sage: loads(a.dumps()) == a316True317"""318return sage.rings.finite_rings.integer_mod.mod, (self.lift(), self.modulus(), self.parent())319320def is_nilpotent(self):321r"""322Return ``True`` if ``self`` is nilpotent,323i.e., some power of ``self`` is zero.324325EXAMPLES::326327sage: a = Integers(90384098234^3)328sage: factor(a.order())3292^3 * 191^3 * 236607587^3330sage: b = a(2*191)331sage: b.is_nilpotent()332False333sage: b = a(2*191*236607587)334sage: b.is_nilpotent()335True336337ALGORITHM: Let `m \geq \log_2(n)`, where `n` is338the modulus. Then `x \in \ZZ/n\ZZ` is339nilpotent if and only if `x^m = 0`.340341PROOF: This is clear if you reduce to the prime power case, which342you can do via the Chinese Remainder Theorem.343344We could alternatively factor `n` and check to see if the345prime divisors of `n` all divide `x`. This is346asymptotically slower :-).347"""348if self.is_zero():349return True350m = self.__modulus.sageInteger.exact_log(2) + 1351return (self**m).is_zero()352353#################################################################354# Interfaces355#################################################################356def _pari_init_(self):357return 'Mod(%s,%s)'%(str(self), self.__modulus.sageInteger)358359def pari(self):360return pari(self._pari_init_()) # TODO: is this called implicitly anywhere?361362def _gap_init_(self):363r"""364Return string representation of corresponding GAP object.365366EXAMPLES::367368sage: a = Mod(2,19)369sage: gap(a)370Z(19)371sage: gap(Mod(3, next_prime(10000)))372Z(10007)^6190373sage: gap(Mod(3, next_prime(100000)))374ZmodpZObj( 3, 100003 )375sage: gap(Mod(4, 48))376ZmodnZObj( 4, 48 )377"""378return '%s*One(ZmodnZ(%s))' % (self, self.__modulus.sageInteger)379380def _magma_init_(self, magma):381"""382Coercion to Magma.383384EXAMPLES::385386sage: a = Integers(15)(4)387sage: b = magma(a) # optional - magma388sage: b.Type() # optional - magma389RngIntResElt390sage: b^2 # optional - magma3911392"""393return '%s!%s'%(self.parent()._magma_init_(magma), self)394395def _axiom_init_(self):396"""397Return a string representation of the corresponding to398(Pan)Axiom object.399400EXAMPLES::401402sage: a = Integers(15)(4)403sage: a._axiom_init_()404'4 :: IntegerMod(15)'405406sage: aa = axiom(a); aa #optional - axiom4074408sage: aa.type() #optional - axiom409IntegerMod 15410411sage: aa = fricas(a); aa #optional - fricas4124413sage: aa.type() #optional - fricas414IntegerMod(15)415416"""417return '%s :: %s'%(self, self.parent()._axiom_init_())418419_fricas_init_ = _axiom_init_420421def _sage_input_(self, sib, coerced):422r"""423Produce an expression which will reproduce this value when424evaluated.425426EXAMPLES::427428sage: K = GF(7)429sage: sage_input(K(5), verify=True)430# Verified431GF(7)(5)432sage: sage_input(K(5) * polygen(K), verify=True)433# Verified434R.<x> = GF(7)[]4355*x436sage: from sage.misc.sage_input import SageInputBuilder437sage: K(5)._sage_input_(SageInputBuilder(), False)438{call: {call: {atomic:GF}({atomic:7})}({atomic:5})}439sage: K(5)._sage_input_(SageInputBuilder(), True)440{atomic:5}441"""442v = sib.int(self.lift())443if coerced:444return v445else:446return sib(self.parent())(v)447448def log(self, b=None):449r"""450Return an integer `x` such that `b^x = a`, where451`a` is ``self``.452453INPUT:454455456- ``self`` - unit modulo `n`457458- ``b`` - a unit modulo `n`. If ``b`` is not given,459``R.multiplicative_generator()`` is used, where460``R`` is the parent of ``self``.461462463OUTPUT: Integer `x` such that `b^x = a`, if this exists; a ValueError otherwise.464465.. note::466467If the modulus is prime and b is a generator, this calls Pari's ``znlog``468function, which is rather fast. If not, it falls back on the generic469discrete log implementation in :meth:`sage.groups.generic.discrete_log`.470471EXAMPLES::472473sage: r = Integers(125)474sage: b = r.multiplicative_generator()^3475sage: a = b^17476sage: a.log(b)47717478sage: a.log()47951480481A bigger example::482483sage: FF = FiniteField(2^32+61)484sage: c = FF(4294967356)485sage: x = FF(2)486sage: a = c.log(x)487sage: a4882147483678489sage: x^a4904294967356491492Things that can go wrong. E.g., if the base is not a generator for493the multiplicative group, or not even a unit.494495::496497sage: Mod(3, 7).log(Mod(2, 7))498Traceback (most recent call last):499...500ValueError: No discrete log of 3 found to base 2501sage: a = Mod(16, 100); b = Mod(4,100)502sage: a.log(b)503Traceback (most recent call last):504...505ZeroDivisionError: Inverse does not exist.506507We check that #9205 is fixed::508509sage: Mod(5,9).log(Mod(2, 9))5105511512We test against a bug (side effect on PARI) fixed in #9438::513514sage: R.<a, b> = QQ[]515sage: pari(b)516b517sage: GF(7)(5).log()5185519sage: pari(b)520b521522AUTHORS:523524- David Joyner and William Stein (2005-11)525526- William Stein (2007-01-27): update to use PARI as requested527by David Kohel.528529- Simon King (2010-07-07): fix a side effect on PARI530"""531if b is None:532b = self._parent.multiplicative_generator()533else:534b = self._parent(b)535536if self.modulus().is_prime() and b.multiplicative_order() == b.parent().unit_group_order():537538# use PARI539540cmd = 'if(znorder(Mod(%s,%s))!=eulerphi(%s),-1,znlog(%s,Mod(%s,%s)))'%(b, self.__modulus.sageInteger,541self.__modulus.sageInteger,542self, b, self.__modulus.sageInteger)543try:544n = Integer(pari(cmd))545return n546except PariError, msg:547raise ValueError, "%s\nPARI failed to compute discrete log (perhaps base is not a generator or is too large)"%msg548549else: # fall back on slower native implementation550551from sage.groups.generic import discrete_log552return discrete_log(self, b)553554def generalised_log(self):555r"""556Return integers `n_i` such that557558..math::559560\prod_i x_i^{n_i} = \text{self},561562where `x_1, \dots, x_d` are the generators of the unit group563returned by ``self.parent().unit_gens()``. See also :meth:`log`.564565EXAMPLES::566567sage: m = Mod(3, 1568)568sage: v = m.generalised_log(); v569[1, 3, 1]570sage: prod([Zmod(1568).unit_gens()[i] ** v[i] for i in [0..2]])5713572573"""574if not self.is_unit():575raise ZeroDivisionError576N = self.modulus()577h = []578for (p, c) in N.factor():579if p != 2 or (p == 2 and c == 2):580h.append((self % p**c).log())581elif c > 2:582m = self % p**c583if m % 4 == 1:584h.append(0)585else:586h.append(1)587m *= -1588h.append(m.log(5))589return h590591def modulus(IntegerMod_abstract self):592"""593EXAMPLES::594595sage: Mod(3,17).modulus()59617597"""598return self.__modulus.sageInteger599600def charpoly(self, var='x'):601"""602Returns the characteristic polynomial of this element.603604EXAMPLES::605606sage: k = GF(3)607sage: a = k.gen()608sage: a.charpoly('x')609x + 2610sage: a + 26110612613AUTHORS:614615- Craig Citro616"""617R = self.parent()[var]618return R([-self,1])619620def minpoly(self, var='x'):621"""622Returns the minimal polynomial of this element.623624EXAMPLES:625sage: GF(241, 'a')(1).minpoly()626x + 240627"""628return self.charpoly(var)629630def minimal_polynomial(self, var='x'):631"""632Returns the minimal polynomial of this element.633634EXAMPLES:635sage: GF(241, 'a')(1).minimal_polynomial(var = 'z')636z + 240637"""638return self.minpoly(var)639640def polynomial(self, var='x'):641"""642Returns a constant polynomial representing this value.643644EXAMPLES::645646sage: k = GF(7)647sage: a = k.gen(); a6481649sage: a.polynomial()6501651sage: type(a.polynomial())652<type 'sage.rings.polynomial.polynomial_zmod_flint.Polynomial_zmod_flint'>653"""654R = self.parent()[var]655return R(self)656657def norm(self):658"""659Returns the norm of this element, which is itself. (This is here660for compatibility with higher order finite fields.)661662EXAMPLES::663664sage: k = GF(691)665sage: a = k(389)666sage: a.norm()667389668669AUTHORS:670671- Craig Citro672"""673return self674675def trace(self):676"""677Returns the trace of this element, which is itself. (This is here678for compatibility with higher order finite fields.)679680EXAMPLES::681682sage: k = GF(691)683sage: a = k(389)684sage: a.trace()685389686687AUTHORS:688689- Craig Citro690"""691return self692693cpdef bint is_one(self):694raise NotImplementedError695696cpdef bint is_unit(self):697raise NotImplementedError698699def is_square(self):700r"""701EXAMPLES::702703sage: Mod(3,17).is_square()704False705sage: Mod(9,17).is_square()706True707sage: Mod(9,17*19^2).is_square()708True709sage: Mod(-1,17^30).is_square()710True711sage: Mod(1/9, next_prime(2^40)).is_square()712True713sage: Mod(1/25, next_prime(2^90)).is_square()714True715716TESTS::717718sage: Mod(1/25, 2^8).is_square()719True720sage: Mod(1/25, 2^40).is_square()721True722723ALGORITHM: Calculate the Jacobi symbol724`(\mathtt{self}/p)` at each prime `p`725dividing `n`. It must be 1 or 0 for each prime, and if it726is 0 mod `p`, where `p^k || n`, then727`ord_p(\mathtt{self})` must be even or greater than728`k`.729730The case `p = 2` is handled separately.731732AUTHORS:733734- Robert Bradshaw735"""736return self.is_square_c()737738cdef bint is_square_c(self) except -2:739if self.is_zero() or self.is_one():740return 1741moduli = self.parent().factored_order()742cdef int val, e743lift = self.lift()744if len(moduli) == 1:745p, e = moduli[0]746if e == 1:747return lift.jacobi(p) != -1748elif p == 2:749return self.pari().issquare() # TODO: implement directly750elif self % p == 0:751val = lift.valuation(p)752return val >= e or (val % 2 == 0 and (lift // p**val).jacobi(p) != -1)753else:754return lift.jacobi(p) != -1755else:756for p, e in moduli:757if p == 2:758if e > 1 and not self.pari().issquare(): # TODO: implement directly759return 0760elif e > 1 and lift % p == 0:761val = lift.valuation(p)762if val < e and (val % 2 == 1 or (lift // p**val).jacobi(p) == -1):763return 0764elif lift.jacobi(p) == -1:765return 0766return 1767768def sqrt(self, extend=True, all=False):769r"""770Returns square root or square roots of ``self`` modulo771`n`.772773INPUT:774775776- ``extend`` - bool (default: ``True``);777if ``True``, return a square root in an extension ring,778if necessary. Otherwise, raise a ``ValueError`` if the779square root is not in the base ring.780781- ``all`` - bool (default: ``False``); if782``True``, return {all} square roots of self, instead of783just one.784785786ALGORITHM: Calculates the square roots mod `p` for each of787the primes `p` dividing the order of the ring, then lifts788them `p`-adically and uses the CRT to find a square root789mod `n`.790791See also ``square_root_mod_prime_power`` and792``square_root_mod_prime`` (in this module) for more793algorithmic details.794795EXAMPLES::796797sage: mod(-1, 17).sqrt()7984799sage: mod(5, 389).sqrt()80086801sage: mod(7, 18).sqrt()8025803sage: a = mod(14, 5^60).sqrt()804sage: a*a80514806sage: mod(15, 389).sqrt(extend=False)807Traceback (most recent call last):808...809ValueError: self must be a square810sage: Mod(1/9, next_prime(2^40)).sqrt()^(-2)8119812sage: Mod(1/25, next_prime(2^90)).sqrt()^(-2)81325814815::816817sage: a = Mod(3,5); a8183819sage: x = Mod(-1, 360)820sage: x.sqrt(extend=False)821Traceback (most recent call last):822...823ValueError: self must be a square824sage: y = x.sqrt(); y825sqrt359826sage: y.parent()827Univariate Quotient Polynomial Ring in sqrt359 over Ring of integers modulo 360 with modulus x^2 + 1828sage: y^2829359830831We compute all square roots in several cases::832833sage: R = Integers(5*2^3*3^2); R834Ring of integers modulo 360835sage: R(40).sqrt(all=True)836[20, 160, 200, 340]837sage: [x for x in R if x^2 == 40] # Brute force verification838[20, 160, 200, 340]839sage: R(1).sqrt(all=True)840[1, 19, 71, 89, 91, 109, 161, 179, 181, 199, 251, 269, 271, 289, 341, 359]841sage: R(0).sqrt(all=True)842[0, 60, 120, 180, 240, 300]843844::845846sage: R = Integers(5*13^3*37); R847Ring of integers modulo 406445848sage: v = R(-1).sqrt(all=True); v849[78853, 111808, 160142, 193097, 213348, 246303, 294637, 327592]850sage: [x^2 for x in v]851[406444, 406444, 406444, 406444, 406444, 406444, 406444, 406444]852sage: v = R(169).sqrt(all=True); min(v), -max(v), len(v)853(13, 13, 104)854sage: all([x^2==169 for x in v])855True856857Modulo a power of 2::858859sage: R = Integers(2^7); R860Ring of integers modulo 128861sage: a = R(17)862sage: a.sqrt()86323864sage: a.sqrt(all=True)865[23, 41, 87, 105]866sage: [x for x in R if x^2==17]867[23, 41, 87, 105]868"""869if self.is_one():870if all:871return list(self.parent().square_roots_of_one())872else:873return self874875if not self.is_square_c():876if extend:877y = 'sqrt%s'%self878R = self.parent()['x']879modulus = R.gen()**2 - R(self)880if self._parent.is_field():881import constructor882Q = constructor.FiniteField(self.__modulus.sageInteger**2, y, modulus)883else:884R = self.parent()['x']885Q = R.quotient(modulus, names=(y,))886z = Q.gen()887if all:888# TODO889raise NotImplementedError890return z891raise ValueError, "self must be a square"892893F = self._parent.factored_order()894cdef long e, exp, val895if len(F) == 1:896p, e = F[0]897898if all and e > 1 and not self.is_unit():899if self.is_zero():900# All multiples of p^ciel(e/2) vanish901return [self._parent(x) for x in xrange(0, self.__modulus.sageInteger, p**((e+1)/2))]902else:903z = self.lift()904val = z.valuation(p)/2 # square => valuation is even905from sage.rings.finite_rings.integer_mod_ring import IntegerModRing906# Find the unit part (mod the ring with appropriate precision)907u = IntegerModRing(p**(e-val))(z // p**(2*val))908# will add multiples of p^exp909exp = e - val910if p == 2:911exp -= 1 # note the factor of 2 below912if 2*exp < e:913exp = (e+1)/2914# For all a^2 = u and all integers b915# (a*p^val + b*p^exp) ^ 2916# = u*p^(2*val) + 2*a*b*p^(val+exp) + b^2*p^(2*exp)917# = u*p^(2*val) mod p^e918# whenever min(val+exp, 2*exp) > e919p_val = p**val920p_exp = p**exp921w = [self._parent(a.lift() * p_val + b)922for a in u.sqrt(all=True)923for b in xrange(0, self.__modulus.sageInteger, p_exp)]924if p == 2:925w = list(set(w))926w.sort()927return w928929if e > 1:930x = square_root_mod_prime_power(mod(self, p**e), p, e)931else:932x = square_root_mod_prime(self, p)933x = x._balanced_abs()934935if not all:936return x937938v = list(set([x*a for a in self._parent.square_roots_of_one()]))939v.sort()940return v941942else:943if not all:944# Use CRT to combine together a square root modulo each prime power945sqrts = [square_root_mod_prime(mod(self, p), p) for p, e in F if e == 1] + \946[square_root_mod_prime_power(mod(self, p**e), p, e) for p, e in F if e != 1]947948x = sqrts.pop()949for y in sqrts:950x = x.crt(y)951return x._balanced_abs()952else:953# Use CRT to combine together all square roots modulo each prime power954vmod = []955moduli = []956P = self.parent()957from sage.rings.finite_rings.integer_mod_ring import IntegerModRing958for p, e in F:959k = p**e960R = IntegerModRing(p**e)961w = [P(x) for x in R(self).sqrt(all=True)]962vmod.append(w)963moduli.append(k)964# Now combine in all possible ways using the CRT965from sage.rings.arith import CRT_basis966basis = CRT_basis(moduli)967from sage.misc.mrange import cartesian_product_iterator968v = []969for x in cartesian_product_iterator(vmod):970# x is a specific choice of roots modulo each prime power divisor971a = sum([basis[i]*x[i] for i in range(len(x))])972v.append(a)973v.sort()974return v975976square_root = sqrt977978def nth_root(self, n, extend = False, all = False, algorithm = None, cunningham = False):979r"""980Returns an `n`\th root of ``self``.981982INPUT:983984- ``n`` - integer `\geq 1`985986- ``extend`` - bool (default: True); if True, return an nth987root in an extension ring, if necessary. Otherwise, raise a988ValueError if the root is not in the base ring. Warning:989this option is not implemented!990991- ``all`` - bool (default: ``False``); if ``True``, return all `n`\th992roots of ``self``, instead of just one.993994- ``algorithm`` - string (default: None); The algorithm for the prime modulus case.995CRT and p-adic log techniques are used to reduce to this case.996'Johnston' is the only currently supported option.997998OUTPUT:9991000If self has an `n`\th root, returns one (if ``all`` is ``False``) or a1001list of all of them (if ``all`` is ``True``). Otherwise, raises a1002``ValueError`` (if ``extend`` is ``False``) or a ``NotImplementedError`` (if1003``extend`` is ``True``).10041005.. warning::1006The 'extend' option is not implemented (yet).10071008NOTES:10091010- If `n = 0`:10111012- if ``all=True``:10131014- if ``self=1``: all nonzero elements of the parent are returned in1015a list. Note that this could be very expensive for large1016parents.10171018- otherwise: an empty list is returned10191020- if ``all=False``:10211022- if ``self=1``: ``self`` is returned10231024- otherwise; a ``ValueError`` is raised10251026- If `n < 0`:10271028- if self is invertible, the `(-n)`\th root of the inverse of self is returned10291030- otherwise a ``ValueError`` is raised or empty list returned.10311032EXAMPLES::103310341035sage: K = GF(31)1036sage: a = K(22)1037sage: K(22).nth_root(7)1038131039sage: K(25).nth_root(5)104051041sage: K(23).nth_root(3)1042291043sage: mod(225,2^5*3^2).nth_root(4, all=True)1044[225, 129, 33, 63, 255, 159, 9, 201, 105, 279, 183, 87, 81, 273, 177, 207, 111, 15, 153, 57, 249, 135, 39, 231]1045sage: mod(275,2^5*7^4).nth_root(7, all=True)1046[58235, 25307, 69211, 36283, 3355, 47259, 14331]1047sage: mod(1,8).nth_root(2,all=True)1048[1, 7, 5, 3]1049sage: mod(4,8).nth_root(2,all=True)1050[2, 6]1051sage: mod(1,16).nth_root(4,all=True)1052[1, 15, 13, 3, 9, 7, 5, 11]1053sage: (mod(22,31)^200).nth_root(200)105451055sage: mod(3,6).nth_root(0,all=True)1056[]1057sage: mod(3,6).nth_root(0)1058Traceback (most recent call last):1059...1060ValueError1061sage: mod(1,6).nth_root(0,all=True)1062[1, 2, 3, 4, 5]10631064TESTS::10651066sage: for p in [1009,2003,10007,100003]:1067... K = GF(p)1068... for r in (p-1).divisors():1069... if r == 1: continue1070... x = K.random_element()1071... y = x^r1072... if y.nth_root(r)**r != y: raise RuntimeError1073... if (y^41).nth_root(41*r)**(41*r) != y^41: raise RuntimeError1074... if (y^307).nth_root(307*r)**(307*r) != y^307: raise RuntimeError10751076sage: for t in xrange(200):1077... n = randint(1,2^63)1078... K = Integers(n)1079... b = K.random_element()1080... e = randint(-2^62, 2^63)1081... try:1082... a = b.nth_root(e)1083... if a^e != b:1084... print n, b, e, a1085... raise NotImplementedError1086... except ValueError:1087... pass10881089ALGORITHMS:10901091- The default for prime modulus is currently an algorithm described in the following paper:10921093Johnston, Anna M. A generalized qth root algorithm. Proceedings of the tenth annual ACM-SIAM symposium on Discrete algorithms. Baltimore, 1999: pp 929-930.10941095AUTHORS:10961097- David Roe (2010-2-13)1098"""1099if extend:1100raise NotImplementedError1101K = self.parent()1102n = Integer(n)1103if n == 0:1104if self == 1:1105if all: return [K(a) for a in range(1,K.order())]1106else: return self1107else:1108if all: return []1109else: raise ValueError1110F = K.factored_order()1111if len(F) == 0:1112if all:1113return [self]1114else:1115return self1116if len(F) != 1:1117if all:1118# 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...1119L = []1120for p, k in F:1121L.append(mod(self, p**k).nth_root(n, all=True, algorithm=algorithm))1122ans = L[0]1123for i in range(1, len(L)):1124ans = [a.crt(b) for a in ans for b in L[i]]1125else:1126ans = mod(0,1)1127for p, k in F:1128ans = ans.crt(mod(self, p**k).nth_root(n, algorithm=algorithm))1129return ans1130p, k = F[0]1131if self.is_zero():1132if n < 0:1133if all: return []1134else: raise ValueError1135if all:1136if k == 1:1137return [self]1138else:1139minval = max(1, (k/n).ceil())1140return [K(a*p**minval) for a in range(p**(k-minval))]1141else:1142return self1143if n < 0:1144try:1145self = ~self1146except ZeroDivisionError:1147if all: return []1148else: raise ValueError1149n = -n1150if p == 2 and k == 1:1151if all: return [self]1152else: return self1153if k > 1:1154pval, upart = self.lift().val_unit(p)1155if not n.divides(pval):1156if all:1157return []1158else:1159raise ValueError, "no nth root"1160if pval > 0:1161if all:1162return [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))]1163else:1164return K(p**(pval // n) * mod(upart, p**(k-pval)).nth_root(n, algorithm=algorithm).lift())1165from sage.rings.padics.all import ZpFM1166R = ZpFM(p,k,print_mode='digits')1167self_orig = self1168if p == 2:1169sign = [1]1170if self % 4 == 3:1171if n % 2 == 0:1172if all: return []1173else: raise ValueError, "no nth root"1174else:1175sign = [-1]1176self = -self1177elif n % 2 == 0:1178if k > 2 and self % 8 == 5:1179if all: return []1180else: raise ValueError, "no nth root"1181sign = [1, -1]1182if k == 2:1183if all: return [K(s) for s in sign[:2]]1184else: return K(sign[0])1185if all: modp = [mod(self,8)]1186else: modp = mod(self,8)1187else:1188sign = [1]1189modp = self % p1190self = self / K(R.teichmuller(modp))1191modp = modp.nth_root(n, all=all, algorithm=algorithm)1192# now self is congruent to 1 mod 4 or 1 mod p (for odd p), so the power series for p-adic log converges.1193# Hensel lifting is probably better, but this is easier at the moment.1194plog = R(self).log()1195nval = n.valuation(p)1196if nval >= plog.valuation() + (-1 if p == 2 else 0):1197if self == 1:1198if all:1199return [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]1200else: return self_orig1201else:1202if all: return []1203else: raise ValueError, "no nth root"1204if all:1205ans = [plog // n + p**(k - nval) * i for i in range(p**nval)]1206ans = [s*K(R.teichmuller(m) * a.exp()) for a in ans for m in modp for s in sign]1207return ans1208else:1209return sign[0] * K(R.teichmuller(modp) * (plog // n).exp())1210return self._nth_root_common(n, all, algorithm, cunningham)12111212def _nth_root_naive(self, n):1213"""1214Computes all nth roots using brute force, for doc-testing.12151216TESTS::12171218sage: for n in range(2,100): # long time1219... K=Integers(n)1220... elist = range(1,min(2*n+2,100))1221... for e in random_sublist(elist, 5/len(elist)):1222... for a in random_sublist(range(1,n), min((n+2)//2,10)/(n-1)):1223... b = K(a)1224... try:1225... L = b.nth_root(e, all=True)1226... if len(L) > 0:1227... c = b.nth_root(e)1228... except:1229... L = [-1]1230... M = b._nth_root_naive(e)1231... if sorted(L) != M:1232... print "mod(%s, %s).nth_root(%s,all=True), mod(%s, %s)._nth_root_naive(%s)"%(a,n,e,a,n,e)1233... raise ValueError1234... if len(L) > 0 and (c not in L):1235... print "mod(%s, %s).nth_root(%s), mod(%s, %s).nth_root(%s,all=True)"%(a,n,e,a,n,e)1236... raise ValueError1237"""1238L = []1239for a in self.parent():1240if a**n == self:1241L.append(a)1242return L12431244def _balanced_abs(self):1245"""1246This function returns `x` or `-x`, whichever has a1247positive representative in `-n/2 < x \leq n/2`.12481249This is used so that the same square root is always returned,1250despite the possibly probabalistic nature of the underlying1251algorithm.1252"""1253if self.lift() > self.__modulus.sageInteger >> 1:1254return -self1255else:1256return self125712581259def rational_reconstruction(self):1260"""1261EXAMPLES::12621263sage: R = IntegerModRing(97)1264sage: a = R(2) / R(3)1265sage: a1266331267sage: a.rational_reconstruction()12682/31269"""1270return self.lift().rational_reconstruction(self.modulus())12711272def crt(IntegerMod_abstract self, IntegerMod_abstract other):1273r"""1274Use the Chinese Remainder Theorem to find an element of the1275integers modulo the product of the moduli that reduces to1276``self`` and to ``other``. The modulus of1277``other`` must be coprime to the modulus of1278``self``.12791280EXAMPLES::12811282sage: a = mod(3,5)1283sage: b = mod(2,7)1284sage: a.crt(b)12852312861287::12881289sage: a = mod(37,10^8)1290sage: b = mod(9,3^8)1291sage: a.crt(b)129212590000003712931294::12951296sage: b = mod(0,1)1297sage: a.crt(b) == a1298True1299sage: a.crt(b).modulus()130010000000013011302TESTS::13031304sage: mod(0,1).crt(mod(4,2^127))130541306sage: mod(4,2^127).crt(mod(0,1))130741308sage: mod(4,2^30).crt(mod(0,1))130941310sage: mod(0,1).crt(mod(4,2^30))131141312sage: mod(0,1).crt(mod(4,2^15))131341314sage: mod(4,2^15).crt(mod(0,1))1315413161317AUTHORS:13181319- Robert Bradshaw1320"""1321cdef int_fast64_t new_modulus1322if not PY_TYPE_CHECK(self, IntegerMod_gmp) and not PY_TYPE_CHECK(other, IntegerMod_gmp):13231324if other.__modulus.int64 == 1: return self1325new_modulus = self.__modulus.int64 * other.__modulus.int641326if new_modulus < INTEGER_MOD_INT32_LIMIT:1327return self.__crt(other)13281329elif new_modulus < INTEGER_MOD_INT64_LIMIT:1330if not PY_TYPE_CHECK(self, IntegerMod_int64):1331self = IntegerMod_int64(self._parent, self.lift())1332if not PY_TYPE_CHECK(other, IntegerMod_int64):1333other = IntegerMod_int64(other._parent, other.lift())1334return self.__crt(other)13351336if not PY_TYPE_CHECK(self, IntegerMod_gmp):1337if self.__modulus.int64 == 1: return other1338self = IntegerMod_gmp(self._parent, self.lift())13391340if not PY_TYPE_CHECK(other, IntegerMod_gmp):1341if other.__modulus.int64 == 1: return self1342other = IntegerMod_gmp(other._parent, other.lift())13431344return self.__crt(other)134513461347def additive_order(self):1348r"""1349Returns the additive order of self.13501351This is the same as ``self.order()``.13521353EXAMPLES::13541355sage: Integers(20)(2).additive_order()1356101357sage: Integers(20)(7).additive_order()1358201359sage: Integers(90308402384902)(2).additive_order()1360451542011924511361"""1362n = self.__modulus.sageInteger1363return sage.rings.integer.Integer(n.__floordiv__(self.lift().gcd(n)))13641365def multiplicative_order(self):1366"""1367Returns the multiplicative order of self.13681369EXAMPLES::13701371sage: Mod(-1,5).multiplicative_order()137221373sage: Mod(1,5).multiplicative_order()137411375sage: Mod(0,5).multiplicative_order()1376Traceback (most recent call last):1377...1378ArithmeticError: multiplicative order of 0 not defined since it is not a unit modulo 51379"""1380try:1381return sage.rings.integer.Integer(self.pari().order()) # pari's "order" is by default multiplicative1382except PariError:1383raise ArithmeticError, "multiplicative order of %s not defined since it is not a unit modulo %s"%(1384self, self.__modulus.sageInteger)13851386def valuation(self, p):1387"""1388The largest power r such that m is in the ideal generated by p^r or infinity if there is not a largest such power.1389However it is an error to take the valuation with respect to a unit.13901391.. NOTE::13921393This is not a valuation in the mathematical sense. As shown with the examples below.13941395EXAMPLES:13961397This example shows that the (a*b).valuation(n) is not always the same as a.valuation(n) + b.valuation(n)13981399::14001401sage: R=ZZ.quo(9)1402sage: a=R(3)1403sage: b=R(6)1404sage: a.valuation(3)140511406sage: a.valuation(3) + b.valuation(3)140721408sage: (a*b).valuation(3)1409+Infinity14101411The valuation with respect to a unit is an error14121413::14141415sage: a.valuation(4)1416Traceback (most recent call last):1417...1418ValueError: Valuation with respect to a unit is not defined.14191420TESTS::14211422sage: R=ZZ.quo(12)1423sage: a=R(2)1424sage: b=R(4)1425sage: a.valuation(2)142611427sage: b.valuation(2)1428+Infinity1429sage: ZZ.quo(1024)(16).valuation(4)1430214311432"""1433p=self.__modulus.sageInteger.gcd(p)1434if p==1:1435raise ValueError("Valuation with respect to a unit is not defined.")1436r = 01437power = p1438while not (self % power): # self % power == 01439r += 11440power *= p1441if not power.divides(self.__modulus.sageInteger):1442from sage.rings.all import infinity1443return infinity1444return r14451446def __floordiv__(self, other):1447"""1448Exact division for prime moduli, for compatibility with other fields.14491450EXAMPLES:1451sage: GF(7)(3) // GF(7)(5)145221453"""1454# needs to be rewritten for coercion1455if other.parent() is not self.parent():1456other = self.parent().coerce(other)1457if self.parent().is_field():1458return self / other1459else:1460raise TypeError, "Floor division not defined for non-prime modulus"14611462def _repr_(self):1463return str(self.lift())14641465def _latex_(self):1466return str(self)14671468def _integer_(self, ZZ=None):1469return self.lift()14701471def _rational_(self):1472return rational.Rational(self.lift())14731474147514761477######################################################################1478# class IntegerMod_gmp1479######################################################################148014811482cdef class IntegerMod_gmp(IntegerMod_abstract):1483"""1484Elements of `\ZZ/n\ZZ` for n not small enough1485to be operated on in word size.14861487AUTHORS:14881489- Robert Bradshaw (2006-08-24)1490"""14911492def __init__(IntegerMod_gmp self, parent, value, empty=False):1493"""1494EXAMPLES::14951496sage: a = mod(5,14^20)1497sage: type(a)1498<type 'sage.rings.finite_rings.integer_mod.IntegerMod_gmp'>1499sage: loads(dumps(a)) == a1500True1501"""1502mpz_init(self.value)1503IntegerMod_abstract.__init__(self, parent)1504if empty:1505return1506cdef sage.rings.integer.Integer z1507if PY_TYPE_CHECK(value, sage.rings.integer.Integer):1508z = value1509elif PY_TYPE_CHECK(value, rational.Rational):1510z = value % self.__modulus.sageInteger1511elif PY_TYPE_CHECK(value, int):1512self.set_from_long(value)1513return1514else:1515z = sage.rings.integer_ring.Z(value)1516self.set_from_mpz(z.value)15171518cdef IntegerMod_gmp _new_c(self):1519cdef IntegerMod_gmp x1520x = PY_NEW(IntegerMod_gmp)1521mpz_init(x.value)1522x.__modulus = self.__modulus1523x._parent = self._parent1524return x15251526def __dealloc__(self):1527mpz_clear(self.value)15281529cdef void set_from_mpz(self, mpz_t value):1530cdef sage.rings.integer.Integer modulus1531modulus = self.__modulus.sageInteger1532if mpz_sgn(value) == -1 or mpz_cmp(value, modulus.value) >= 0:1533mpz_mod(self.value, value, modulus.value)1534else:1535mpz_set(self.value, value)15361537cdef void set_from_long(self, long value):1538cdef sage.rings.integer.Integer modulus1539mpz_set_si(self.value, value)1540if value < 0 or mpz_cmp_si(self.__modulus.sageInteger.value, value) >= 0:1541mpz_mod(self.value, self.value, self.__modulus.sageInteger.value)15421543cdef mpz_t* get_value(IntegerMod_gmp self):1544return &self.value15451546def __lshift__(IntegerMod_gmp self, k):1547r"""1548Performs a left shift by ``k`` bits.15491550For details, see :meth:`shift`.15511552EXAMPLES::15531554sage: e = Mod(19, 10^10)1555sage: e << 102155694436085761557"""1558return self.shift(long(k))15591560def __rshift__(IntegerMod_gmp self, k):1561r"""1562Performs a right shift by ``k`` bits.15631564For details, see :meth:`shift`.15651566EXAMPLES::15671568sage: e = Mod(19, 10^10)1569sage: e >> 1157091571"""1572return self.shift(-long(k))15731574cdef shift(IntegerMod_gmp self, long k):1575r"""1576Performs a bit-shift specified by ``k`` on ``self``.15771578Suppose that ``self`` represents an integer `x` modulo `n`. If `k` is1579`k = 0`, returns `x`. If `k > 0`, shifts `x` to the left, that is,1580multiplies `x` by `2^k` and then returns the representative in the1581range `[0,n)`. If `k < 0`, shifts `x` to the right, that is, returns1582the integral part of `x` divided by `2^k`.15831584Note that, in any case, ``self`` remains unchanged.15851586INPUT:15871588- ``k`` - Integer of type ``long``15891590OUTPUT15911592- Result of type ``IntegerMod_gmp``15931594EXAMPLES::15951596sage: e = Mod(19, 10^10)1597sage: e << 102159894436085761599sage: e >> 1160091601sage: e >> 4160211603"""1604cdef IntegerMod_gmp x1605if k == 0:1606return self1607else:1608x = self._new_c()1609if k > 0:1610mpz_mul_2exp(x.value, self.value, k)1611mpz_fdiv_r(x.value, x.value, self.__modulus.sageInteger.value)1612else:1613mpz_fdiv_q_2exp(x.value, self.value, -k)1614return x16151616cdef int _cmp_c_impl(left, Element right) except -2:1617"""1618EXAMPLES::16191620sage: mod(5,13^20) == mod(5,13^20)1621True1622sage: mod(5,13^20) == mod(-5,13^20)1623False1624sage: mod(5,13^20) == mod(-5,13)1625False1626"""1627cdef int i1628i = mpz_cmp((<IntegerMod_gmp>left).value, (<IntegerMod_gmp>right).value)1629if i < 0:1630return -11631elif i == 0:1632return 01633else:1634return 116351636def __richcmp__(left, right, int op):1637return (<Element>left)._richcmp(right, op)163816391640cpdef bint is_one(IntegerMod_gmp self):1641"""1642Returns ``True`` if this is `1`, otherwise1643``False``.16441645EXAMPLES::16461647sage: mod(1,5^23).is_one()1648True1649sage: mod(0,5^23).is_one()1650False1651"""1652return mpz_cmp_si(self.value, 1) == 016531654def __nonzero__(IntegerMod_gmp self):1655"""1656Returns ``True`` if this is not `0`, otherwise1657``False``.16581659EXAMPLES::16601661sage: mod(13,5^23).is_zero()1662False1663sage: (mod(25,5^23)^23).is_zero()1664True1665"""1666return mpz_cmp_si(self.value, 0) != 016671668cpdef bint is_unit(self):1669"""1670Return True iff this element is a unit.16711672EXAMPLES::16731674sage: mod(13, 5^23).is_unit()1675True1676sage: mod(25, 5^23).is_unit()1677False1678"""1679return self.lift().gcd(self.modulus()) == 116801681def __crt(IntegerMod_gmp self, IntegerMod_gmp other):1682cdef IntegerMod_gmp lift, x1683cdef sage.rings.integer.Integer modulus, other_modulus16841685modulus = self.__modulus.sageInteger1686other_modulus = other.__modulus.sageInteger1687import integer_mod_ring1688lift = IntegerMod_gmp(integer_mod_ring.IntegerModRing(modulus*other_modulus), None, empty=True)1689try:1690if mpz_cmp(self.value, other.value) > 0:1691x = (other - IntegerMod_gmp(other._parent, self.lift())) / IntegerMod_gmp(other._parent, modulus)1692mpz_mul(lift.value, x.value, modulus.value)1693mpz_add(lift.value, lift.value, self.value)1694else:1695x = (self - IntegerMod_gmp(self._parent, other.lift())) / IntegerMod_gmp(self._parent, other_modulus)1696mpz_mul(lift.value, x.value, other_modulus.value)1697mpz_add(lift.value, lift.value, other.value)1698return lift1699except ZeroDivisionError:1700raise ZeroDivisionError, "moduli must be coprime"170117021703def __copy__(IntegerMod_gmp self):1704cdef IntegerMod_gmp x1705x = self._new_c()1706mpz_set(x.value, self.value)1707return x17081709cpdef ModuleElement _add_(self, ModuleElement right):1710"""1711EXAMPLES::17121713sage: R = Integers(10^10)1714sage: R(7) + R(8)1715151716"""1717cdef IntegerMod_gmp x1718x = self._new_c()1719mpz_add(x.value, self.value, (<IntegerMod_gmp>right).value)1720if mpz_cmp(x.value, self.__modulus.sageInteger.value) >= 0:1721mpz_sub(x.value, x.value, self.__modulus.sageInteger.value)1722return x;17231724cpdef ModuleElement _iadd_(self, ModuleElement right):1725"""1726EXAMPLES::17271728sage: R = Integers(10^10)1729sage: R(7) + R(8)1730151731"""1732mpz_add(self.value, self.value, (<IntegerMod_gmp>right).value)1733if mpz_cmp(self.value, self.__modulus.sageInteger.value) >= 0:1734mpz_sub(self.value, self.value, self.__modulus.sageInteger.value)1735return self17361737cpdef ModuleElement _sub_(self, ModuleElement right):1738"""1739EXAMPLES::17401741sage: R = Integers(10^10)1742sage: R(7) - R(8)174399999999991744"""1745cdef IntegerMod_gmp x1746x = self._new_c()1747mpz_sub(x.value, self.value, (<IntegerMod_gmp>right).value)1748if mpz_sgn(x.value) == -1:1749mpz_add(x.value, x.value, self.__modulus.sageInteger.value)1750return x;17511752cpdef ModuleElement _isub_(self, ModuleElement right):1753"""1754EXAMPLES::17551756sage: R = Integers(10^10)1757sage: R(7) - R(8)175899999999991759"""1760mpz_sub(self.value, self.value, (<IntegerMod_gmp>right).value)1761if mpz_sgn(self.value) == -1:1762mpz_add(self.value, self.value, self.__modulus.sageInteger.value)1763return self17641765cpdef ModuleElement _neg_(self):1766"""1767EXAMPLES::17681769sage: -mod(5,10^10)177099999999951771sage: -mod(0,10^10)177201773"""1774if mpz_cmp_si(self.value, 0) == 0:1775return self1776cdef IntegerMod_gmp x1777x = self._new_c()1778mpz_sub(x.value, self.__modulus.sageInteger.value, self.value)1779return x17801781cpdef RingElement _mul_(self, RingElement right):1782"""1783EXAMPLES::17841785sage: R = Integers(10^11)1786sage: R(700000) * R(800000)1787600000000001788"""1789cdef IntegerMod_gmp x1790x = self._new_c()1791mpz_mul(x.value, self.value, (<IntegerMod_gmp>right).value)1792mpz_fdiv_r(x.value, x.value, self.__modulus.sageInteger.value)1793return x17941795cpdef RingElement _imul_(self, RingElement right):1796"""1797EXAMPLES::17981799sage: R = Integers(10^11)1800sage: R(700000) * R(800000)1801600000000001802"""1803mpz_mul(self.value, self.value, (<IntegerMod_gmp>right).value)1804mpz_fdiv_r(self.value, self.value, self.__modulus.sageInteger.value)1805return self18061807cpdef RingElement _div_(self, RingElement right):1808"""1809EXAMPLES::18101811sage: R = Integers(10^11)1812sage: R(3) / R(7)1813714285714291814"""1815return self._mul_(~right)18161817def __int__(self):1818return int(self.lift())18191820def __index__(self):1821"""1822Needed so integers modulo `n` can be used as list indices.18231824EXAMPLES::18251826sage: v = [1,2,3,4,5]1827sage: v[Mod(3,10^20)]182841829"""1830return int(self.lift())18311832def __long__(self):1833return long(self.lift())18341835def __mod__(self, right):1836if self.modulus() % right != 0:1837raise ZeroDivisionError, "reduction modulo right not defined."1838import integer_mod_ring1839return IntegerMod(integer_mod_ring.IntegerModRing(right), self)18401841def __pow__(IntegerMod_gmp self, exp, m): # NOTE: m ignored, always use modulus of parent ring1842"""1843EXAMPLES:1844sage: R = Integers(10^10)1845sage: R(2)^1000184656680693761847sage: p = next_prime(11^10)1848sage: R = Integers(p)1849sage: R(9876)^(p-1)185011851sage: R(0)^01852Traceback (most recent call last):1853...1854ArithmeticError: 0^0 is undefined.1855sage: mod(3, 10^100)^-2185688888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888891857sage: mod(2, 10^100)^-21858Traceback (most recent call last):1859...1860ZeroDivisionError: Inverse does not exist.1861"""1862cdef IntegerMod_gmp x = self._new_c()1863try:1864sig_on()1865mpz_pow_helper(x.value, self.value, exp, self.__modulus.sageInteger.value)1866return x1867finally:1868sig_off()18691870def __invert__(IntegerMod_gmp self):1871"""1872Return the multiplicative inverse of self.18731874EXAMPLES::18751876sage: a = mod(3,10^100); type(a)1877<type 'sage.rings.finite_rings.integer_mod.IntegerMod_gmp'>1878sage: ~a187966666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666671880sage: ~mod(2,10^100)1881Traceback (most recent call last):1882...1883ZeroDivisionError: Inverse does not exist.1884"""1885if self.is_zero():1886raise ZeroDivisionError, "Inverse does not exist."18871888cdef IntegerMod_gmp x1889x = self._new_c()1890if mpz_invert(x.value, self.value, self.__modulus.sageInteger.value):1891return x1892else:1893raise ZeroDivisionError, "Inverse does not exist."18941895def lift(IntegerMod_gmp self):1896"""1897Lift an integer modulo `n` to the integers.18981899EXAMPLES::19001901sage: a = Mod(8943, 2^70); type(a)1902<type 'sage.rings.finite_rings.integer_mod.IntegerMod_gmp'>1903sage: lift(a)190489431905sage: a.lift()190689431907"""1908cdef sage.rings.integer.Integer z1909z = sage.rings.integer.Integer()1910z.set_from_mpz(self.value)1911return z19121913def __float__(self):1914return float(self.lift())19151916def __hash__(self):1917"""1918EXAMPLES::19191920sage: a = Mod(8943, 2^100)1921sage: hash(a)192289431923"""1924# return mpz_pythonhash(self.value)1925return hash(self.lift())1926192719281929######################################################################1930# class IntegerMod_int1931######################################################################193219331934cdef class IntegerMod_int(IntegerMod_abstract):1935"""1936Elements of `\ZZ/n\ZZ` for n small enough to1937be operated on in 32 bits19381939AUTHORS:19401941- Robert Bradshaw (2006-08-24)1942"""19431944def __init__(self, parent, value, empty=False):1945"""1946EXAMPLES::19471948sage: a = Mod(10,30); a1949101950sage: loads(a.dumps()) == a1951True1952"""1953IntegerMod_abstract.__init__(self, parent)1954if empty:1955return1956cdef long x1957if PY_TYPE_CHECK(value, int):1958x = value1959self.ivalue = x % self.__modulus.int321960if self.ivalue < 0:1961self.ivalue = self.ivalue + self.__modulus.int321962return1963elif PY_TYPE_CHECK(value, IntegerMod_int):1964self.ivalue = (<IntegerMod_int>value).ivalue % self.__modulus.int321965return1966cdef sage.rings.integer.Integer z1967if PY_TYPE_CHECK(value, sage.rings.integer.Integer):1968z = value1969elif PY_TYPE_CHECK(value, rational.Rational):1970z = value % self.__modulus.sageInteger1971else:1972z = sage.rings.integer_ring.Z(value)1973self.set_from_mpz(z.value)19741975def _make_new_with_parent_c(self, parent): #ParentWithBase parent):1976cdef IntegerMod_int x = PY_NEW(IntegerMod_int)1977x._parent = parent1978x.__modulus = parent._pyx_order1979x.ivalue = self.ivalue1980return x19811982cdef IntegerMod_int _new_c(self, int_fast32_t value):1983if self.__modulus.table is not None:1984return self.__modulus.lookup(value)1985cdef IntegerMod_int x = PY_NEW(IntegerMod_int)1986x._parent = self._parent1987x.__modulus = self.__modulus1988x.ivalue = value1989return x19901991cdef void set_from_mpz(self, mpz_t value):1992if mpz_sgn(value) == -1 or mpz_cmp_si(value, self.__modulus.int32) >= 0:1993self.ivalue = mpz_fdiv_ui(value, self.__modulus.int32)1994else:1995self.ivalue = mpz_get_si(value)19961997cdef void set_from_long(self, long value):1998self.ivalue = value % self.__modulus.int3219992000cdef void set_from_int(IntegerMod_int self, int_fast32_t ivalue):2001if ivalue < 0:2002self.ivalue = self.__modulus.int32 + (ivalue % self.__modulus.int32)2003elif ivalue >= self.__modulus.int32:2004self.ivalue = ivalue % self.__modulus.int322005else:2006self.ivalue = ivalue20072008cdef int_fast32_t get_int_value(IntegerMod_int self):2009return self.ivalue2010201120122013cdef int _cmp_c_impl(self, Element right) except -2:2014"""2015EXAMPLES::20162017sage: mod(5,13) == mod(-8,13)2018True2019sage: mod(5,13) == mod(8,13)2020False2021sage: mod(5,13) == mod(5,24)2022False2023sage: mod(0, 13) == 02024True2025sage: mod(0, 13) == int(0)2026True2027"""2028if self.ivalue == (<IntegerMod_int>right).ivalue:2029return 02030elif self.ivalue < (<IntegerMod_int>right).ivalue:2031return -12032else:2033return 120342035def __richcmp__(left, right, int op):2036return (<Element>left)._richcmp(right, op)203720382039cpdef bint is_one(IntegerMod_int self):2040"""2041Returns ``True`` if this is `1`, otherwise2042``False``.20432044EXAMPLES::20452046sage: mod(6,5).is_one()2047True2048sage: mod(0,5).is_one()2049False2050"""2051return self.ivalue == 120522053def __nonzero__(IntegerMod_int self):2054"""2055Returns ``True`` if this is not `0`, otherwise2056``False``.20572058EXAMPLES::20592060sage: mod(13,5).is_zero()2061False2062sage: mod(25,5).is_zero()2063True2064"""2065return self.ivalue != 020662067cpdef bint is_unit(IntegerMod_int self):2068"""2069Return True iff this element is a unit20702071EXAMPLES::20722073sage: a=Mod(23,100)2074sage: a.is_unit()2075True2076sage: a=Mod(24,100)2077sage: a.is_unit()2078False2079"""2080return gcd_int(self.ivalue, self.__modulus.int32) == 120812082def __crt(IntegerMod_int self, IntegerMod_int other):2083"""2084Use the Chinese Remainder Theorem to find an element of the2085integers modulo the product of the moduli that reduces to self and2086to other. The modulus of other must be coprime to the modulus of2087self.20882089EXAMPLES::20902091sage: a = mod(3,5)2092sage: b = mod(2,7)2093sage: a.crt(b)20942320952096AUTHORS:20972098- Robert Bradshaw2099"""2100cdef IntegerMod_int lift2101cdef int_fast32_t x21022103import integer_mod_ring2104lift = IntegerMod_int(integer_mod_ring.IntegerModRing(self.__modulus.int32 * other.__modulus.int32), None, empty=True)21052106try:2107x = (other.ivalue - self.ivalue % other.__modulus.int32) * mod_inverse_int(self.__modulus.int32, other.__modulus.int32)2108lift.set_from_int( x * self.__modulus.int32 + self.ivalue )2109return lift2110except ZeroDivisionError:2111raise ZeroDivisionError, "moduli must be coprime"211221132114def __copy__(IntegerMod_int self):2115cdef IntegerMod_int x = PY_NEW(IntegerMod_int)2116x._parent = self._parent2117x.__modulus = self.__modulus2118x.ivalue = self.ivalue2119return x21202121cpdef ModuleElement _add_(self, ModuleElement right):2122"""2123EXAMPLES::21242125sage: R = Integers(10)2126sage: R(7) + R(8)212752128"""2129cdef int_fast32_t x2130x = self.ivalue + (<IntegerMod_int>right).ivalue2131if x >= self.__modulus.int32:2132x = x - self.__modulus.int322133return self._new_c(x)21342135cpdef ModuleElement _iadd_(self, ModuleElement right):2136"""2137EXAMPLES::21382139sage: R = Integers(10)2140sage: R(7) + R(8)214152142"""2143cdef int_fast32_t x2144x = self.ivalue + (<IntegerMod_int>right).ivalue2145if x >= self.__modulus.int32:2146x = x - self.__modulus.int322147self.ivalue = x2148return self21492150cpdef ModuleElement _sub_(self, ModuleElement right):2151"""2152EXAMPLES::21532154sage: R = Integers(10)2155sage: R(7) - R(8)215692157"""2158cdef int_fast32_t x2159x = self.ivalue - (<IntegerMod_int>right).ivalue2160if x < 0:2161x = x + self.__modulus.int322162return self._new_c(x)21632164cpdef ModuleElement _isub_(self, ModuleElement right):2165"""2166EXAMPLES::21672168sage: R = Integers(10)2169sage: R(7) - R(8)217092171"""2172cdef int_fast32_t x2173x = self.ivalue - (<IntegerMod_int>right).ivalue2174if x < 0:2175x = x + self.__modulus.int322176self.ivalue = x2177return self21782179cpdef ModuleElement _neg_(self):2180"""2181EXAMPLES::21822183sage: -mod(7,10)218432185sage: -mod(0,10)218602187"""2188if self.ivalue == 0:2189return self2190return self._new_c(self.__modulus.int32 - self.ivalue)21912192cpdef RingElement _mul_(self, RingElement right):2193"""2194EXAMPLES::21952196sage: R = Integers(10)2197sage: R(7) * R(8)219862199"""2200return self._new_c((self.ivalue * (<IntegerMod_int>right).ivalue) % self.__modulus.int32)22012202cpdef RingElement _imul_(self, RingElement right):2203"""2204EXAMPLES::22052206sage: R = Integers(10)2207sage: R(7) * R(8)220862209"""2210self.ivalue = (self.ivalue * (<IntegerMod_int>right).ivalue) % self.__modulus.int322211return self22122213cpdef RingElement _div_(self, RingElement right):2214"""2215EXAMPLES::22162217sage: R = Integers(10)2218sage: R(2)/3221942220"""2221if self.__modulus.inverses is not None:2222right_inverse = self.__modulus.inverses[(<IntegerMod_int>right).ivalue]2223if right_inverse is None:2224raise ZeroDivisionError, "Inverse does not exist."2225else:2226return self._new_c((self.ivalue * (<IntegerMod_int>right_inverse).ivalue) % self.__modulus.int32)22272228cdef int_fast32_t x2229x = self.ivalue * mod_inverse_int((<IntegerMod_int>right).ivalue, self.__modulus.int32)2230return self._new_c(x% self.__modulus.int32)22312232def __int__(IntegerMod_int self):2233return self.ivalue22342235def __index__(self):2236"""2237Needed so integers modulo `n` can be used as list indices.22382239EXAMPLES::22402241sage: v = [1,2,3,4,5]2242sage: v[Mod(10,7)]224342244"""2245return self.ivalue22462247def __long__(IntegerMod_int self):2248return self.ivalue22492250def __mod__(IntegerMod_int self, right):2251right = int(right)2252if self.__modulus.int32 % right != 0:2253raise ZeroDivisionError, "reduction modulo right not defined."2254import integer_mod_ring2255return integer_mod_ring.IntegerModRing(right)(self)22562257def __lshift__(IntegerMod_int self, k):2258r"""2259Performs a left shift by ``k`` bits.22602261For details, see :meth:`shift`.22622263EXAMPLES::22642265sage: e = Mod(5, 2^10 - 1)2266sage: e << 522671602268sage: e * 2^522691602270"""2271return self.shift(int(k))22722273def __rshift__(IntegerMod_int self, k):2274r"""2275Performs a right shift by ``k`` bits.22762277For details, see :meth:`shift`.22782279EXAMPLES::22802281sage: e = Mod(5, 2^10 - 1)2282sage: e << 522831602284sage: e * 2^522851602286"""2287return self.shift(-int(k))22882289cdef shift(IntegerMod_int self, int k):2290"""2291Performs a bit-shift specified by ``k`` on ``self``.22922293Suppose that ``self`` represents an integer `x` modulo `n`. If `k` is2294`k = 0`, returns `x`. If `k > 0`, shifts `x` to the left, that is,2295multiplies `x` by `2^k` and then returns the representative in the2296range `[0,n)`. If `k < 0`, shifts `x` to the right, that is, returns2297the integral part of `x` divided by `2^k`.22982299Note that, in any case, ``self`` remains unchanged.23002301INPUT:23022303- ``k`` - Integer of type ``int``23042305OUTPUT:23062307- Result of type ``IntegerMod_int``23082309WARNING:23102311For positive ``k``, if ``x << k`` overflows as a 32-bit integer, the2312result is meaningless.23132314EXAMPLES::23152316sage: e = Mod(5, 2^10 - 1)2317sage: e << 523181602319sage: e * 2^523201602321sage: e = Mod(8, 2^5 - 1)2322sage: e >> 3232312324sage: int(e)/int(2^3)232512326"""2327if k == 0:2328return self2329elif k > 0:2330return self._new_c((self.ivalue << k) % self.__modulus.int32)2331else:2332return self._new_c(self.ivalue >> (-k))23332334def __pow__(IntegerMod_int self, exp, m): # NOTE: m ignored, always use modulus of parent ring2335"""2336EXAMPLES:2337sage: R = Integers(10)2338sage: R(2)^10233942340sage: R = Integers(389)2341sage: R(7)^388234212343sage: R(0)^02344Traceback (most recent call last):2345...2346ArithmeticError: 0^0 is undefined.23472348sage: mod(3, 100)^-12349672350sage: mod(3, 100)^-1000000002351123522353sage: mod(2, 100)^-12354Traceback (most recent call last):2355...2356ZeroDivisionError: Inverse does not exist.2357sage: mod(2, 100)^-1000000002358Traceback (most recent call last):2359...2360ZeroDivisionError: Inverse does not exist.2361"""2362cdef long long_exp2363cdef int_fast32_t res2364cdef mpz_t res_mpz2365if PyInt_CheckExact(exp) and -100000 < PyInt_AS_LONG(exp) < 100000:2366long_exp = PyInt_AS_LONG(exp)2367elif PY_TYPE_CHECK_EXACT(exp, Integer) and mpz_cmpabs_ui((<Integer>exp).value, 100000) == -1:2368long_exp = mpz_get_si((<Integer>exp).value)2369else:2370try:2371sig_on()2372mpz_init(res_mpz)2373base = self.lift()2374mpz_pow_helper(res_mpz, (<Integer>base).value, exp, self.__modulus.sageInteger.value)2375return self._new_c(mpz_get_ui(res_mpz))2376finally:2377mpz_clear(res_mpz)2378sig_off()23792380if long_exp == 0 and self.ivalue == 0:2381raise ArithmeticError, "0^0 is undefined."2382cdef bint invert = False2383if long_exp < 0:2384invert = True2385long_exp = -long_exp2386res = mod_pow_int(self.ivalue, long_exp, self.__modulus.int32)2387if invert:2388return ~self._new_c(res)2389else:2390return self._new_c(res)23912392def __invert__(IntegerMod_int self):2393"""2394Return the multiplicative inverse of self.23952396EXAMPLES::23972398sage: ~mod(7,100)2399432400"""2401if self.__modulus.inverses is not None:2402x = self.__modulus.inverses[self.ivalue]2403if x is None:2404raise ZeroDivisionError, "Inverse does not exist."2405else:2406return x2407else:2408return self._new_c(mod_inverse_int(self.ivalue, self.__modulus.int32))24092410def lift(IntegerMod_int self):2411"""2412Lift an integer modulo `n` to the integers.24132414EXAMPLES::24152416sage: a = Mod(8943, 2^10); type(a)2417<type 'sage.rings.finite_rings.integer_mod.IntegerMod_int'>2418sage: lift(a)24197512420sage: a.lift()24217512422"""2423cdef sage.rings.integer.Integer z2424z = sage.rings.integer.Integer()2425mpz_set_si(z.value, self.ivalue)2426return z24272428def __float__(IntegerMod_int self):2429return <double>self.ivalue24302431def __hash__(self):2432"""2433EXAMPLES::24342435sage: a = Mod(89, 2^10)2436sage: hash(a)2437892438"""2439return hash(self.ivalue)24402441cdef bint is_square_c(self) except -2:2442if self.ivalue <= 1:2443return 12444moduli = self._parent.factored_order()2445cdef int val, e2446cdef int_fast32_t p2447if len(moduli) == 1:2448sage_p, e = moduli[0]2449p = sage_p2450if e == 1:2451return jacobi_int(self.ivalue, p) != -12452elif p == 2:2453return self.pari().issquare() # TODO: implement directly2454elif self.ivalue % p == 0:2455val = self.lift().valuation(sage_p)2456return val >= e or (val % 2 == 0 and jacobi_int(self.ivalue / int(sage_p**val), p) != -1)2457else:2458return jacobi_int(self.ivalue, p) != -12459else:2460for sage_p, e in moduli:2461p = sage_p2462if p == 2:2463if e > 1 and not self.pari().issquare(): # TODO: implement directly2464return 02465elif e > 1 and self.ivalue % p == 0:2466val = self.lift().valuation(sage_p)2467if val < e and (val % 2 == 1 or jacobi_int(self.ivalue / int(sage_p**val), p) == -1):2468return 02469elif jacobi_int(self.ivalue, p) == -1:2470return 02471return 124722473def sqrt(self, extend=True, all=False):2474r"""2475Returns square root or square roots of ``self`` modulo2476`n`.24772478INPUT:247924802481- ``extend`` - bool (default: ``True``);2482if ``True``, return a square root in an extension ring,2483if necessary. Otherwise, raise a ``ValueError`` if the2484square root is not in the base ring.24852486- ``all`` - bool (default: ``False``); if2487``True``, return {all} square roots of self, instead of2488just one.248924902491ALGORITHM: Calculates the square roots mod `p` for each of2492the primes `p` dividing the order of the ring, then lifts2493them `p`-adically and uses the CRT to find a square root2494mod `n`.24952496See also ``square_root_mod_prime_power`` and2497``square_root_mod_prime`` (in this module) for more2498algorithmic details.24992500EXAMPLES::25012502sage: mod(-1, 17).sqrt()250342504sage: mod(5, 389).sqrt()2505862506sage: mod(7, 18).sqrt()250752508sage: a = mod(14, 5^60).sqrt()2509sage: a*a2510142511sage: mod(15, 389).sqrt(extend=False)2512Traceback (most recent call last):2513...2514ValueError: self must be a square2515sage: Mod(1/9, next_prime(2^40)).sqrt()^(-2)251692517sage: Mod(1/25, next_prime(2^90)).sqrt()^(-2)25182525192520::25212522sage: a = Mod(3,5); a252332524sage: x = Mod(-1, 360)2525sage: x.sqrt(extend=False)2526Traceback (most recent call last):2527...2528ValueError: self must be a square2529sage: y = x.sqrt(); y2530sqrt3592531sage: y.parent()2532Univariate Quotient Polynomial Ring in sqrt359 over Ring of integers modulo 360 with modulus x^2 + 12533sage: y^2253435925352536We compute all square roots in several cases::25372538sage: R = Integers(5*2^3*3^2); R2539Ring of integers modulo 3602540sage: R(40).sqrt(all=True)2541[20, 160, 200, 340]2542sage: [x for x in R if x^2 == 40] # Brute force verification2543[20, 160, 200, 340]2544sage: R(1).sqrt(all=True)2545[1, 19, 71, 89, 91, 109, 161, 179, 181, 199, 251, 269, 271, 289, 341, 359]2546sage: R(0).sqrt(all=True)2547[0, 60, 120, 180, 240, 300]2548sage: GF(107)(0).sqrt(all=True)2549[0]25502551::25522553sage: R = Integers(5*13^3*37); R2554Ring of integers modulo 4064452555sage: v = R(-1).sqrt(all=True); v2556[78853, 111808, 160142, 193097, 213348, 246303, 294637, 327592]2557sage: [x^2 for x in v]2558[406444, 406444, 406444, 406444, 406444, 406444, 406444, 406444]2559sage: v = R(169).sqrt(all=True); min(v), -max(v), len(v)2560(13, 13, 104)2561sage: all([x^2==169 for x in v])2562True25632564Modulo a power of 2::25652566sage: R = Integers(2^7); R2567Ring of integers modulo 1282568sage: a = R(17)2569sage: a.sqrt()2570232571sage: a.sqrt(all=True)2572[23, 41, 87, 105]2573sage: [x for x in R if x^2==17]2574[23, 41, 87, 105]2575"""2576cdef int_fast32_t i, n = self.__modulus.int322577if n > 100:2578moduli = self._parent.factored_order()2579# Unless the modulus is tiny, test to see if we're in the really2580# easy case of n prime, n = 3 mod 4.2581if n > 100 and n % 4 == 3 and len(moduli) == 1 and moduli[0][1] == 1:2582if jacobi_int(self.ivalue, self.__modulus.int32) == 1:2583# it's a non-zero square, sqrt(a) = a^(p+1)/42584i = mod_pow_int(self.ivalue, (self.__modulus.int32+1)/4, n)2585if i > n/2:2586i = n-i2587if all:2588return [self._new_c(i), self._new_c(n-i)]2589else:2590return self._new_c(i)2591elif self.ivalue == 0:2592return [self] if all else self2593elif not extend:2594raise ValueError, "self must be a square"2595# Now we use a heuristic to guess whether or not it will2596# be faster to just brute-force search for squares in a c loop...2597# TODO: more tuning?2598elif n <= 100 or n / (1 << len(moduli)) < 5000:2599if all:2600return [self._new_c(i) for i from 0 <= i < n if (i*i) % n == self.ivalue]2601else:2602for i from 0 <= i <= n/2:2603if (i*i) % n == self.ivalue:2604return self._new_c(i)2605if not extend:2606raise ValueError, "self must be a square"2607# Either it failed but extend was True, or the generic algorithm is better2608return IntegerMod_abstract.sqrt(self, extend=extend, all=all)260926102611def _balanced_abs(self):2612"""2613This function returns `x` or `-x`, whichever has a2614positive representative in `-n/2 < x \leq n/2`.2615"""2616if self.ivalue > self.__modulus.int32 / 2:2617return -self2618else:2619return self2620262126222623### End of class262426252626cdef int_fast32_t gcd_int(int_fast32_t a, int_fast32_t b):2627"""2628Returns the gcd of a and b26292630For use with IntegerMod_int26312632AUTHORS:26332634- Robert Bradshaw2635"""2636cdef int_fast32_t tmp2637if a < b:2638tmp = b2639b = a2640a = tmp2641while b:2642tmp = b2643b = a % b2644a = tmp2645return a264626472648cdef int_fast32_t mod_inverse_int(int_fast32_t x, int_fast32_t n) except 0:2649"""2650Returns y such that xy=1 mod n26512652For use in IntegerMod_int26532654AUTHORS:26552656- Robert Bradshaw2657"""2658cdef int_fast32_t tmp, a, b, last_t, t, next_t, q2659a = n2660b = x2661t = 02662next_t = 12663while b:2664# a = s * n + t * x2665if b == 1:2666next_t = next_t % n2667if next_t < 0:2668next_t = next_t + n2669return next_t2670q = a / b2671tmp = b2672b = a % b2673a = tmp2674last_t = t2675t = next_t2676next_t = last_t - q * t2677raise ZeroDivisionError, "Inverse does not exist."267826792680cdef int_fast32_t mod_pow_int(int_fast32_t base, int_fast32_t exp, int_fast32_t n):2681"""2682Returns base^exp mod n26832684For use in IntegerMod_int26852686EXAMPLES::26872688sage: z = Mod(2, 256)2689sage: z^82690026912692AUTHORS:26932694- Robert Bradshaw2695"""2696cdef int_fast32_t prod, pow22697if exp <= 5:2698if exp == 0: return 12699if exp == 1: return base2700prod = base * base % n2701if exp == 2: return prod2702if exp == 3: return (prod * base) % n2703if exp == 4: return (prod * prod) % n27042705pow2 = base2706if exp % 2: prod = base2707else: prod = 12708exp = exp >> 12709while(exp != 0):2710pow2 = pow2 * pow22711if pow2 >= INTEGER_MOD_INT32_LIMIT: pow2 = pow2 % n2712if exp % 2:2713prod = prod * pow22714if prod >= INTEGER_MOD_INT32_LIMIT: prod = prod % n2715exp = exp >> 127162717if prod >= n:2718prod = prod % n2719return prod272027212722cdef int jacobi_int(int_fast32_t a, int_fast32_t m) except -2:2723"""2724Calculates the jacobi symbol (a/n)27252726For use in IntegerMod_int27272728AUTHORS:27292730- Robert Bradshaw2731"""2732cdef int s, jacobi = 12733cdef int_fast32_t b27342735a = a % m27362737while 1:2738if a == 0:2739return 0 # gcd was nontrivial2740elif a == 1:2741return jacobi2742s = 02743while (1 << s) & a == 0:2744s += 12745b = a >> s2746# Now a = 2^s * b27472748# factor out (2/m)^s term2749if s % 2 == 1 and (m % 8 == 3 or m % 8 == 5):2750jacobi = -jacobi27512752if b == 1:2753return jacobi27542755# quadratic reciprocity2756if b % 4 == 3 and m % 4 == 3:2757jacobi = -jacobi2758a = m % b2759m = b2760#2761# These two functions are never used:2762#2763#def test_gcd(a, b):2764# return gcd_int(int(a), int(b))2765#2766#def test_mod_inverse(a, b):2767# return mod_inverse_int(int(a), int(b))2768#276927702771######################################################################2772# class IntegerMod_int642773######################################################################27742775cdef class IntegerMod_int64(IntegerMod_abstract):2776"""2777Elements of `\ZZ/n\ZZ` for n small enough to2778be operated on in 64 bits27792780AUTHORS:27812782- Robert Bradshaw (2006-09-14)2783"""27842785def __init__(self, parent, value, empty=False):2786"""2787EXAMPLES::27882789sage: a = Mod(10,3^10); a2790102791sage: type(a)2792<type 'sage.rings.finite_rings.integer_mod.IntegerMod_int64'>2793sage: loads(a.dumps()) == a2794True2795sage: Mod(5, 2^31)279652797"""2798IntegerMod_abstract.__init__(self, parent)2799if empty:2800return2801cdef int_fast64_t x2802if PY_TYPE_CHECK(value, int):2803x = value2804self.ivalue = x % self.__modulus.int642805if self.ivalue < 0:2806self.ivalue = self.ivalue + self.__modulus.int642807return2808cdef sage.rings.integer.Integer z2809if PY_TYPE_CHECK(value, sage.rings.integer.Integer):2810z = value2811elif PY_TYPE_CHECK(value, rational.Rational):2812z = value % self.__modulus.sageInteger2813else:2814z = sage.rings.integer_ring.Z(value)2815self.set_from_mpz(z.value)28162817cdef IntegerMod_int64 _new_c(self, int_fast64_t value):2818cdef IntegerMod_int64 x2819x = PY_NEW(IntegerMod_int64)2820x.__modulus = self.__modulus2821x._parent = self._parent2822x.ivalue = value2823return x28242825cdef void set_from_mpz(self, mpz_t value):2826if mpz_sgn(value) == -1 or mpz_cmp_si(value, self.__modulus.int64) >= 0:2827self.ivalue = mpz_fdiv_ui(value, self.__modulus.int64)2828else:2829self.ivalue = mpz_get_si(value)28302831cdef void set_from_long(self, long value):2832self.ivalue = value % self.__modulus.int6428332834cdef void set_from_int(IntegerMod_int64 self, int_fast64_t ivalue):2835if ivalue < 0:2836self.ivalue = self.__modulus.int64 + (ivalue % self.__modulus.int64) # Is ivalue % self.__modulus.int64 actually negative?2837elif ivalue >= self.__modulus.int64:2838self.ivalue = ivalue % self.__modulus.int642839else:2840self.ivalue = ivalue28412842cdef int_fast64_t get_int_value(IntegerMod_int64 self):2843return self.ivalue284428452846cdef int _cmp_c_impl(self, Element right) except -2:2847"""2848EXAMPLES::28492850sage: mod(5,13^5) == mod(13^5+5,13^5)2851True2852sage: mod(5,13^5) == mod(8,13^5)2853False2854sage: mod(5,13^5) == mod(5,13)2855True2856sage: mod(0, 13^5) == 02857True2858sage: mod(0, 13^5) == int(0)2859True2860"""2861if self.ivalue == (<IntegerMod_int64>right).ivalue: return 02862elif self.ivalue < (<IntegerMod_int64>right).ivalue: return -12863else: return 128642865def __richcmp__(left, right, int op):2866return (<Element>left)._richcmp(right, op)286728682869cpdef bint is_one(IntegerMod_int64 self):2870"""2871Returns ``True`` if this is `1`, otherwise2872``False``.28732874EXAMPLES::28752876sage: (mod(-1,5^10)^2).is_one()2877True2878sage: mod(0,5^10).is_one()2879False2880"""2881return self.ivalue == 128822883def __nonzero__(IntegerMod_int64 self):2884"""2885Returns ``True`` if this is not `0`, otherwise2886``False``.28872888EXAMPLES::28892890sage: mod(13,5^10).is_zero()2891False2892sage: mod(5^12,5^10).is_zero()2893True2894"""2895return self.ivalue != 028962897cpdef bint is_unit(IntegerMod_int64 self):2898"""2899Return True iff this element is a unit.29002901EXAMPLES::29022903sage: mod(13, 5^10).is_unit()2904True2905sage: mod(25, 5^10).is_unit()2906False2907"""2908return gcd_int64(self.ivalue, self.__modulus.int64) == 129092910def __crt(IntegerMod_int64 self, IntegerMod_int64 other):2911"""2912Use the Chinese Remainder Theorem to find an element of the2913integers modulo the product of the moduli that reduces to self and2914to other. The modulus of other must be coprime to the modulus of2915self.29162917EXAMPLES::29182919sage: a = mod(3,5^10)2920sage: b = mod(2,7)2921sage: a.crt(b)2922292968782923sage: type(a.crt(b)) == type(b.crt(a)) and type(a.crt(b)) == type(mod(1, 7 * 5^10))2924True29252926::29272928sage: a = mod(3,10^10)2929sage: b = mod(2,9)2930sage: a.crt(b)2931800000000032932sage: type(a.crt(b)) == type(b.crt(a)) and type(a.crt(b)) == type(mod(1, 9 * 10^10))2933True29342935AUTHORS:29362937- Robert Bradshaw2938"""2939cdef IntegerMod_int64 lift2940cdef int_fast64_t x29412942import integer_mod_ring2943lift = IntegerMod_int64(integer_mod_ring.IntegerModRing(self.__modulus.int64 * other.__modulus.int64), None, empty=True)29442945try:2946x = (other.ivalue - self.ivalue % other.__modulus.int64) * mod_inverse_int64(self.__modulus.int64, other.__modulus.int64)2947lift.set_from_int( x * self.__modulus.int64 + self.ivalue )2948return lift2949except ZeroDivisionError:2950raise ZeroDivisionError, "moduli must be coprime"29512952def __copy__(IntegerMod_int64 self):2953return self._new_c(self.ivalue)29542955cpdef ModuleElement _add_(self, ModuleElement right):2956"""2957EXAMPLES::29582959sage: R = Integers(10^5)2960sage: R(7) + R(8)2961152962"""2963cdef int_fast64_t x2964x = self.ivalue + (<IntegerMod_int64>right).ivalue2965if x >= self.__modulus.int64:2966x = x - self.__modulus.int642967return self._new_c(x)29682969cpdef ModuleElement _iadd_(self, ModuleElement right):2970"""2971EXAMPLES::29722973sage: R = Integers(10^5)2974sage: R(7) + R(8)2975152976"""2977cdef int_fast64_t x2978x = self.ivalue + (<IntegerMod_int64>right).ivalue2979if x >= self.__modulus.int64:2980x = x - self.__modulus.int642981self.ivalue = x2982return self29832984cpdef ModuleElement _sub_(self, ModuleElement right):2985"""2986EXAMPLES::29872988sage: R = Integers(10^5)2989sage: R(7) - R(8)2990999992991"""2992cdef int_fast64_t x2993x = self.ivalue - (<IntegerMod_int64>right).ivalue2994if x < 0:2995x = x + self.__modulus.int642996return self._new_c(x)29972998cpdef ModuleElement _isub_(self, ModuleElement right):2999"""3000EXAMPLES::30013002sage: R = Integers(10^5)3003sage: R(7) - R(8)3004999993005"""3006cdef int_fast64_t x3007x = self.ivalue - (<IntegerMod_int64>right).ivalue3008if x < 0:3009x = x + self.__modulus.int643010self.ivalue = x3011return self30123013cpdef ModuleElement _neg_(self):3014"""3015EXAMPLES::30163017sage: -mod(7,10^5)3018999933019sage: -mod(0,10^6)302003021"""3022if self.ivalue == 0:3023return self3024return self._new_c(self.__modulus.int64 - self.ivalue)30253026cpdef RingElement _mul_(self, RingElement right):3027"""3028EXAMPLES::30293030sage: R = Integers(10^5)3031sage: R(700) * R(800)3032600003033"""3034return self._new_c((self.ivalue * (<IntegerMod_int64>right).ivalue) % self.__modulus.int64)303530363037cpdef RingElement _imul_(self, RingElement right):3038"""3039EXAMPLES::30403041sage: R = Integers(10^5)3042sage: R(700) * R(800)3043600003044"""3045self.ivalue = (self.ivalue * (<IntegerMod_int64>right).ivalue) % self.__modulus.int643046return self30473048cpdef RingElement _div_(self, RingElement right):3049"""3050EXAMPLES::30513052sage: R = Integers(10^5)3053sage: R(2)/33054333343055"""3056return self._new_c((self.ivalue * mod_inverse_int64((<IntegerMod_int64>right).ivalue,3057self.__modulus.int64) ) % self.__modulus.int64)30583059def __int__(IntegerMod_int64 self):3060return self.ivalue30613062def __index__(self):3063"""3064Needed so integers modulo `n` can be used as list indices.30653066EXAMPLES::30673068sage: v = [1,2,3,4,5]3069sage: v[Mod(3, 2^20)]307043071"""3072return self.ivalue30733074def __long__(IntegerMod_int64 self):3075return self.ivalue30763077def __mod__(IntegerMod_int64 self, right):3078right = int(right)3079if self.__modulus.int64 % right != 0:3080raise ZeroDivisionError, "reduction modulo right not defined."3081import integer_mod_ring3082return integer_mod_ring.IntegerModRing(right)(self)30833084def __lshift__(IntegerMod_int64 self, k):3085r"""3086Performs a left shift by ``k`` bits.30873088For details, see :meth:`shift`.30893090EXAMPLES::30913092sage: e = Mod(5, 2^31 - 1)3093sage: e << 323094103095sage: e * 2^323096103097"""3098return self.shift(int(k))30993100def __rshift__(IntegerMod_int64 self, k):3101r"""3102Performs a right shift by ``k`` bits.31033104For details, see :meth:`shift`.31053106EXAMPLES::31073108sage: e = Mod(5, 2^31 - 1)3109sage: e >> 1311023111"""3112return self.shift(-int(k))31133114cdef shift(IntegerMod_int64 self, int k):3115"""3116Performs a bit-shift specified by ``k`` on ``self``.31173118Suppose that ``self`` represents an integer `x` modulo `n`. If `k` is3119`k = 0`, returns `x`. If `k > 0`, shifts `x` to the left, that is,3120multiplies `x` by `2^k` and then returns the representative in the3121range `[0,n)`. If `k < 0`, shifts `x` to the right, that is, returns3122the integral part of `x` divided by `2^k`.31233124Note that, in any case, ``self`` remains unchanged.31253126INPUT:31273128- ``k`` - Integer of type ``int``31293130OUTPUT:31313132- Result of type ``IntegerMod_int64``31333134WARNING:31353136For positive ``k``, if ``x << k`` overflows as a 64-bit integer, the3137result is meaningless.31383139EXAMPLES::31403141sage: e = Mod(5, 2^31 - 1)3142sage: e << 323143103144sage: e * 2^323145103146sage: e = Mod(5, 2^31 - 1)3147sage: e >> 1314823149"""3150if k == 0:3151return self3152elif k > 0:3153return self._new_c((self.ivalue << k) % self.__modulus.int64)3154else:3155return self._new_c(self.ivalue >> (-k))31563157def __pow__(IntegerMod_int64 self, exp, m): # NOTE: m ignored, always use modulus of parent ring3158"""3159EXAMPLES:3160sage: R = Integers(10)3161sage: R(2)^10316243163sage: p = next_prime(10^5)3164sage: R = Integers(p)3165sage: R(1234)^(p-1)316613167sage: R(0)^03168Traceback (most recent call last):3169...3170ArithmeticError: 0^0 is undefined.3171sage: R = Integers(17^5)3172sage: R(17)^53173031743175sage: R(2)^-1 * 2317613177sage: R(2)^-1000000 * 2^1000000317813179sage: R(17)^-13180Traceback (most recent call last):3181...3182ZeroDivisionError: Inverse does not exist.3183sage: R(17)^-1000000003184Traceback (most recent call last):3185...3186ZeroDivisionError: Inverse does not exist.31873188TESTS::31893190sage: type(R(0))3191<type 'sage.rings.finite_rings.integer_mod.IntegerMod_int64'>3192"""3193cdef long long_exp3194cdef int_fast64_t res3195cdef mpz_t res_mpz3196if PyInt_CheckExact(exp) and -100000 < PyInt_AS_LONG(exp) < 100000:3197long_exp = PyInt_AS_LONG(exp)3198elif PY_TYPE_CHECK_EXACT(exp, Integer) and mpz_cmpabs_ui((<Integer>exp).value, 100000) == -1:3199long_exp = mpz_get_si((<Integer>exp).value)3200else:3201try:3202sig_on()3203mpz_init(res_mpz)3204base = self.lift()3205mpz_pow_helper(res_mpz, (<Integer>base).value, exp, self.__modulus.sageInteger.value)3206if mpz_fits_ulong_p(res_mpz):3207res = mpz_get_ui(res_mpz)3208else:3209res = mpz_get_pyintlong(res_mpz)3210return self._new_c(res)3211finally:3212mpz_clear(res_mpz)3213sig_off()32143215if long_exp == 0 and self.ivalue == 0:3216raise ArithmeticError, "0^0 is undefined."3217cdef bint invert = False3218if long_exp < 0:3219invert = True3220long_exp = -long_exp3221res = mod_pow_int64(self.ivalue, long_exp, self.__modulus.int64)3222if invert:3223return self._new_c(mod_inverse_int64(res, self.__modulus.int64))3224else:3225return self._new_c(res)32263227def __invert__(IntegerMod_int64 self):3228"""3229Return the multiplicative inverse of self.32303231EXAMPLES::32323233sage: a = mod(7,2^40); type(a)3234<type 'sage.rings.finite_rings.integer_mod.IntegerMod_gmp'>3235sage: ~a32364712192690473237sage: a323873239"""3240return self._new_c(mod_inverse_int64(self.ivalue, self.__modulus.int64))32413242def lift(IntegerMod_int64 self):3243"""3244Lift an integer modulo `n` to the integers.32453246EXAMPLES::32473248sage: a = Mod(8943, 2^25); type(a)3249<type 'sage.rings.finite_rings.integer_mod.IntegerMod_int64'>3250sage: lift(a)325189433252sage: a.lift()325389433254"""3255cdef sage.rings.integer.Integer z3256z = sage.rings.integer.Integer()3257mpz_set_si(z.value, self.ivalue)3258return z32593260def __float__(IntegerMod_int64 self):3261"""3262Coerce self to a float.32633264EXAMPLES::32653266sage: a = Mod(8943, 2^35)3267sage: float(a)32688943.03269"""3270return <double>self.ivalue32713272def __hash__(self):3273"""3274Compute hash of self.32753276EXAMPLES::32773278sage: a = Mod(8943, 2^35)3279sage: hash(a)328089433281"""32823283return hash(self.ivalue)32843285def _balanced_abs(self):3286"""3287This function returns `x` or `-x`, whichever has a3288positive representative in `-n/2 < x \leq n/2`.3289"""3290if self.ivalue > self.__modulus.int64 / 2:3291return -self3292else:3293return self329432953296### Helper functions32973298cdef mpz_pow_helper(mpz_t res, mpz_t base, object exp, mpz_t modulus):3299cdef bint invert = False3300cdef long long_exp3301if mpz_sgn(base) == 0 and not exp:3302raise ArithmeticError, "0^0 is undefined."3303if PyInt_CheckExact(exp):3304long_exp = PyInt_AS_LONG(exp)3305if long_exp < 0:3306long_exp = -long_exp3307invert = True3308mpz_powm_ui(res, base, long_exp, modulus)3309else:3310if not PY_TYPE_CHECK_EXACT(exp, Integer):3311exp = Integer(exp)3312if mpz_sgn((<Integer>exp).value) < 0:3313exp = -exp3314invert = True3315mpz_powm(res, base, (<Integer>exp).value, modulus)3316if invert:3317if not mpz_invert(res, res, modulus):3318raise ZeroDivisionError, "Inverse does not exist."33193320cdef int_fast64_t gcd_int64(int_fast64_t a, int_fast64_t b):3321"""3322Returns the gcd of a and b33233324For use with IntegerMod_int6433253326AUTHORS:33273328- Robert Bradshaw3329"""3330cdef int_fast64_t tmp3331if a < b:3332tmp = b3333b = a3334a = tmp3335while b:3336tmp = b3337b = a % b3338a = tmp3339return a334033413342cdef int_fast64_t mod_inverse_int64(int_fast64_t x, int_fast64_t n) except 0:3343"""3344Returns y such that xy=1 mod n33453346For use in IntegerMod_int6433473348AUTHORS:33493350- Robert Bradshaw3351"""3352cdef int_fast64_t tmp, a, b, last_t, t, next_t, q3353a = n3354b = x3355t = 03356next_t = 13357while b:3358# a = s * n + t * x3359if b == 1:3360next_t = next_t % n3361if next_t < 0:3362next_t = next_t + n3363return next_t3364q = a / b3365tmp = b3366b = a % b3367a = tmp3368last_t = t3369t = next_t3370next_t = last_t - q * t3371raise ZeroDivisionError, "Inverse does not exist."337233733374cdef int_fast64_t mod_pow_int64(int_fast64_t base, int_fast64_t exp, int_fast64_t n):3375"""3376Returns base^exp mod n33773378For use in IntegerMod_int6433793380AUTHORS:33813382- Robert Bradshaw3383"""3384cdef int_fast64_t prod, pow23385if exp <= 5:3386if exp == 0: return 13387if exp == 1: return base3388prod = base * base % n3389if exp == 2: return prod3390if exp == 3: return (prod * base) % n3391if exp == 4: return (prod * prod) % n33923393pow2 = base3394if exp % 2: prod = base3395else: prod = 13396exp = exp >> 13397while(exp != 0):3398pow2 = pow2 * pow23399if pow2 >= INTEGER_MOD_INT64_LIMIT: pow2 = pow2 % n3400if exp % 2:3401prod = prod * pow23402if prod >= INTEGER_MOD_INT64_LIMIT: prod = prod % n3403exp = exp >> 134043405if prod >= n:3406prod = prod % n3407return prod340834093410cdef int jacobi_int64(int_fast64_t a, int_fast64_t m) except -2:3411"""3412Calculates the jacobi symbol (a/n)34133414For use in IntegerMod_int6434153416AUTHORS:34173418- Robert Bradshaw3419"""3420cdef int s, jacobi = 13421cdef int_fast64_t b34223423a = a % m34243425while 1:3426if a == 0:3427return 0 # gcd was nontrivial3428elif a == 1:3429return jacobi3430s = 03431while (1 << s) & a == 0:3432s += 13433b = a >> s3434# Now a = 2^s * b34353436# factor out (2/m)^s term3437if s % 2 == 1 and (m % 8 == 3 or m % 8 == 5):3438jacobi = -jacobi34393440if b == 1:3441return jacobi34423443# quadratic reciprocity3444if b % 4 == 3 and m % 4 == 3:3445jacobi = -jacobi3446a = m % b3447m = b344834493450########################3451# Square root functions3452########################34533454def square_root_mod_prime_power(IntegerMod_abstract a, p, e):3455r"""3456Calculates the square root of `a`, where `a` is an3457integer mod `p^e`.34583459ALGORITHM: Perform `p`-adically by stripping off even3460powers of `p` to get a unit and lifting3461`\sqrt{unit} \bmod p` via Newton's method.34623463AUTHORS:34643465- Robert Bradshaw34663467EXAMPLES::34683469sage: from sage.rings.finite_rings.integer_mod import square_root_mod_prime_power3470sage: a=Mod(17,2^20)3471sage: b=square_root_mod_prime_power(a,2,20)3472sage: b^2 == a3473True34743475::34763477sage: a=Mod(72,97^10)3478sage: b=square_root_mod_prime_power(a,97,10)3479sage: b^2 == a3480True3481"""3482if a.is_zero() or a.is_one():3483return a34843485if p == 2:3486if e == 1:3487return a3488# TODO: implement something that isn't totally idiotic.3489for x in a.parent():3490if x**2 == a:3491return x34923493# strip off even powers of p3494cdef int i, val = a.lift().valuation(p)3495if val % 2 == 1:3496raise ValueError, "self must be a square."3497if val > 0:3498unit = a._parent(a.lift() // p**val)3499else:3500unit = a35013502# find square root of unit mod p3503x = unit.parent()(square_root_mod_prime(mod(unit, p), p))35043505# lift p-adically using Newton iteration3506# this is done to higher precision than necessary except at the last step3507one_half = ~(a._new_c_from_long(2))3508for i from 0 <= i < ceil(log(e)/log(2)) - val/2:3509x = (x+unit/x) * one_half35103511# multiply in powers of p (if any)3512if val > 0:3513x *= p**(val // 2)3514return x35153516cpdef square_root_mod_prime(IntegerMod_abstract a, p=None):3517r"""3518Calculates the square root of `a`, where `a` is an3519integer mod `p`; if `a` is not a perfect square,3520this returns an (incorrect) answer without checking.35213522ALGORITHM: Several cases based on residue class of3523`p \bmod 16`.352435253526- `p \bmod 2 = 0`: `p = 2` so3527`\sqrt{a} = a`.35283529- `p \bmod 4 = 3`: `\sqrt{a} = a^{(p+1)/4}`.35303531- `p \bmod 8 = 5`: `\sqrt{a} = \zeta i a` where3532`\zeta = (2a)^{(p-5)/8}`, `i=\sqrt{-1}`.35333534- `p \bmod 16 = 9`: Similar, work in a bi-quadratic3535extension of `\GF{p}` for small `p`, Tonelli3536and Shanks for large `p`.35373538- `p \bmod 16 = 1`: Tonelli and Shanks.353935403541REFERENCES:35423543- Siguna Muller. 'On the Computation of Square Roots in Finite3544Fields' Designs, Codes and Cryptography, Volume 31, Issue 33545(March 2004)35463547- A. Oliver L. Atkin. 'Probabilistic primality testing' (Chapter354830, Section 4) In Ph. Flajolet and P. Zimmermann, editors,3549Algorithms Seminar, 1991-1992. INRIA Research Report 1779, 1992,3550http://www.inria.fr/rrrt/rr-1779.html. Summary by F. Morain.3551http://citeseer.ist.psu.edu/atkin92probabilistic.html35523553- H. Postl. 'Fast evaluation of Dickson Polynomials' Contrib. to3554General Algebra, Vol. 6 (1988) pp. 223-22535553556AUTHORS:35573558- Robert Bradshaw35593560TESTS: Every case appears in the first hundred primes.35613562::35633564sage: from sage.rings.finite_rings.integer_mod import square_root_mod_prime # sqrt() uses brute force for small p3565sage: all([square_root_mod_prime(a*a)^2 == a*a3566... for p in prime_range(100)3567... for a in Integers(p)])3568True3569"""3570if not a or a.is_one():3571return a35723573if p is None:3574p = a._parent.order()3575if p < PyInt_GetMax():3576p = int(p)35773578cdef int p_mod_16 = p % 163579cdef double bits = log(float(p))/log(2)3580cdef long r, m35813582cdef Integer resZ358335843585if p_mod_16 % 2 == 0: # p == 23586return a35873588elif p_mod_16 % 4 == 3:3589return a ** ((p+1)//4)35903591elif p_mod_16 % 8 == 5:3592two_a = a+a3593zeta = two_a ** ((p-5)//8)3594i = zeta**2 * two_a # = two_a ** ((p-1)//4)3595return zeta*a*(i-1)35963597elif p_mod_16 == 9 and bits < 500:3598two_a = a+a3599s = two_a ** ((p-1)//4)3600if s.is_one():3601d = a._parent.quadratic_nonresidue()3602d2 = d*d3603z = (two_a * d2) ** ((p-9)//16)3604i = two_a * d2 * z*z3605return z*d*a*(i-1)3606else:3607z = two_a ** ((p-9)//16)3608i = two_a * z*z3609return z*a*(i-1)36103611else:3612one = a._new_c_from_long(1)3613r, q = (p-one_Z).val_unit(2)3614v = a._parent.quadratic_nonresidue()**q36153616x = a ** ((q-1)//2)3617b = a*x*x # a ^ q3618res = a*x # a ^ ((q-1)/2)36193620while b != one:3621m = 13622bpow = b*b3623while bpow != one:3624bpow *= bpow3625m += 13626g = v**(one_Z << (r-m-1)) # v^(2^(r-m-1))3627res *= g3628b *= g*g3629return res363036313632def fast_lucas(mm, IntegerMod_abstract P):3633"""3634Return `V_k(P, 1)` where `V_k` is the Lucas3635function defined by the recursive relation36363637`V_k(P, Q) = PV_{k-1}(P, Q) - QV_{k-2}(P, Q)`36383639with `V_0 = 2, V_1(P_Q) = P`.36403641REFERENCES:36423643- H. Postl. 'Fast evaluation of Dickson Polynomials' Contrib. to3644General Algebra, Vol. 6 (1988) pp. 223-22536453646AUTHORS:36473648- Robert Bradshaw36493650TESTS::36513652sage: from sage.rings.finite_rings.integer_mod import fast_lucas, slow_lucas3653sage: all([fast_lucas(k, a) == slow_lucas(k, a)3654... for a in Integers(23)3655... for k in range(13)])3656True3657"""3658if mm == 0:3659return 23660elif mm == 1:3661return P36623663cdef sage.rings.integer.Integer m3664m = <sage.rings.integer.Integer>mm if PY_TYPE_CHECK(mm, sage.rings.integer.Integer) else sage.rings.integer.Integer(mm)3665two = P._new_c_from_long(2)3666d1 = P3667d2 = P*P - two36683669sig_on()3670cdef int j3671for j from mpz_sizeinbase(m.value, 2)-1 > j > 0:3672if mpz_tstbit(m.value, j):3673d1 = d1*d2 - P3674d2 = d2*d2 - two3675else:3676d2 = d1*d2 - P3677d1 = d1*d1 - two3678sig_off()3679if mpz_odd_p(m.value):3680return d1*d2 - P3681else:3682return d1*d1 - two36833684def slow_lucas(k, P, Q=1):3685"""3686Lucas function defined using the standard definition, for3687consistency testing.3688"""3689if k == 0:3690return 23691elif k == 1:3692return P3693else:3694return P*slow_lucas(k-1, P, Q) - Q*slow_lucas(k-2, P, Q)369536963697############# Homomorphisms ###############36983699cdef class IntegerMod_hom(Morphism):3700cdef IntegerMod_abstract zero3701cdef NativeIntStruct modulus3702def __init__(self, parent):3703Morphism.__init__(self, parent)3704# we need to use element constructor so that we can register both coercions and conversions using these morphisms.3705self.zero = self._codomain._element_constructor_(0)3706self.modulus = self._codomain._pyx_order3707cpdef Element _call_(self, x):3708return IntegerMod(self.codomain(), x)37093710cdef class IntegerMod_to_IntegerMod(IntegerMod_hom):3711"""3712Very fast IntegerMod to IntegerMod homomorphism.37133714EXAMPLES::37153716sage: from sage.rings.finite_rings.integer_mod import IntegerMod_to_IntegerMod3717sage: Rs = [Integers(3**k) for k in range(1,30,5)]3718sage: [type(R(0)) for R in Rs]3719[<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'>]3720sage: fs = [IntegerMod_to_IntegerMod(S, R) for R in Rs for S in Rs if S is not R and S.order() > R.order()]3721sage: all([f(-1) == f.codomain()(-1) for f in fs])3722True3723sage: [f(-1) for f in fs]3724[2, 2, 2, 2, 2, 728, 728, 728, 728, 177146, 177146, 177146, 43046720, 43046720, 10460353202]3725"""3726def __init__(self, R, S):3727if not S.order().divides(R.order()):3728raise TypeError, "No natural coercion from %s to %s" % (R, S)3729import sage.categories.homset3730IntegerMod_hom.__init__(self, sage.categories.homset.Hom(R, S))37313732cpdef Element _call_(self, x):3733cdef IntegerMod_abstract a3734if PY_TYPE_CHECK(x, IntegerMod_int):3735return (<IntegerMod_int>self.zero)._new_c((<IntegerMod_int>x).ivalue % self.modulus.int32)3736elif PY_TYPE_CHECK(x, IntegerMod_int64):3737return self.zero._new_c_from_long((<IntegerMod_int64>x).ivalue % self.modulus.int64)3738else: # PY_TYPE_CHECK(x, IntegerMod_gmp)3739a = self.zero._new_c_from_long(0)3740a.set_from_mpz((<IntegerMod_gmp>x).value)3741return a37423743def _repr_type(self):3744return "Natural"37453746cdef class Integer_to_IntegerMod(IntegerMod_hom):3747r"""3748Fast `\ZZ \rightarrow \ZZ/n\ZZ`3749morphism.37503751EXAMPLES:37523753We make sure it works for every type.37543755::37563757sage: from sage.rings.finite_rings.integer_mod import Integer_to_IntegerMod3758sage: Rs = [Integers(10), Integers(10^5), Integers(10^10)]3759sage: [type(R(0)) for R in Rs]3760[<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'>]3761sage: fs = [Integer_to_IntegerMod(R) for R in Rs]3762sage: [f(-1) for f in fs]3763[9, 99999, 9999999999]3764"""3765def __init__(self, R):3766import sage.categories.homset3767IntegerMod_hom.__init__(self, sage.categories.homset.Hom(integer_ring.ZZ, R))37683769cpdef Element _call_(self, x):3770cdef IntegerMod_abstract a3771cdef Py_ssize_t res3772if self.modulus.table is not None:3773res = x % self.modulus.int643774if res < 0:3775res += self.modulus.int643776a = self.modulus.lookup(res)3777if a._parent is not self._codomain:3778a._parent = self._codomain3779# print (<Element>a)._parent, " is not ", parent3780return a3781else:3782a = self.zero._new_c_from_long(0)3783a.set_from_mpz((<Integer>x).value)3784return a37853786def _repr_type(self):3787return "Natural"37883789def section(self):3790return IntegerMod_to_Integer(self._codomain)37913792cdef class IntegerMod_to_Integer(Map):3793def __init__(self, R):3794import sage.categories.homset3795from sage.categories.all import Sets3796Morphism.__init__(self, sage.categories.homset.Hom(R, integer_ring.ZZ, Sets()))37973798cpdef Element _call_(self, x):3799cdef Integer ans = PY_NEW(Integer)3800if PY_TYPE_CHECK(x, IntegerMod_gmp):3801mpz_set(ans.value, (<IntegerMod_gmp>x).value)3802elif PY_TYPE_CHECK(x, IntegerMod_int):3803mpz_set_si(ans.value, (<IntegerMod_int>x).ivalue)3804elif PY_TYPE_CHECK(x, IntegerMod_int64):3805mpz_set_si(ans.value, (<IntegerMod_int64>x).ivalue)3806return ans38073808def _repr_type(self):3809return "Lifting"38103811cdef class Int_to_IntegerMod(IntegerMod_hom):3812"""3813EXAMPLES:38143815We make sure it works for every type.38163817::38183819sage: from sage.rings.finite_rings.integer_mod import Int_to_IntegerMod3820sage: Rs = [Integers(2**k) for k in range(1,50,10)]3821sage: [type(R(0)) for R in Rs]3822[<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'>]3823sage: fs = [Int_to_IntegerMod(R) for R in Rs]3824sage: [f(-1) for f in fs]3825[1, 2047, 2097151, 2147483647, 2199023255551]3826"""3827def __init__(self, R):3828import sage.categories.homset3829from sage.structure.parent import Set_PythonType3830IntegerMod_hom.__init__(self, sage.categories.homset.Hom(Set_PythonType(int), R))38313832cpdef Element _call_(self, x):3833cdef IntegerMod_abstract a3834cdef long res = PyInt_AS_LONG(x)3835if PY_TYPE_CHECK(self.zero, IntegerMod_gmp):3836if 0 <= res < INTEGER_MOD_INT64_LIMIT:3837return self.zero._new_c_from_long(res)3838else:3839return IntegerMod_gmp(self.zero._parent, x)3840else:3841res %= self.modulus.int643842if res < 0:3843res += self.modulus.int643844if self.modulus.table is not None:3845a = self.modulus.lookup(res)3846if a._parent is not self._codomain:3847a._parent = self._codomain3848# print (<Element>a)._parent, " is not ", parent3849return a3850else:3851return self.zero._new_c_from_long(res)38523853def _repr_type(self):3854return "Native"385538563857