Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemath
GitHub Repository: sagemath/sagelib
Path: blob/master/sage/rings/finite_rings/integer_mod.pyx
4058 views
1
r"""
2
Elements of `\ZZ/n\ZZ`
3
4
An element of the integers modulo `n`.
5
6
There are three types of integer_mod classes, depending on the
7
size of the modulus.
8
9
10
- ``IntegerMod_int`` stores its value in a
11
``int_fast32_t`` (typically an ``int``);
12
this is used if the modulus is less than
13
`\sqrt{2^{31}-1}`.
14
15
- ``IntegerMod_int64`` stores its value in a
16
``int_fast64_t`` (typically a ``long
17
long``); this is used if the modulus is less than
18
`2^{31}-1`.
19
20
- ``IntegerMod_gmp`` stores its value in a
21
``mpz_t``; this can be used for an arbitrarily large
22
modulus.
23
24
25
All extend ``IntegerMod_abstract``.
26
27
For efficiency reasons, it stores the modulus (in all three forms,
28
if possible) in a common (cdef) class
29
``NativeIntStruct`` rather than in the parent.
30
31
AUTHORS:
32
33
- Robert Bradshaw: most of the work
34
35
- Didier Deshommes: bit shifting
36
37
- William Stein: editing and polishing; new arith architecture
38
39
- Robert Bradshaw: implement native is_square and square_root
40
41
- William Stein: sqrt
42
43
- Maarten Derickx: moved the valuation code from the global
44
valuation function to here
45
46
47
TESTS::
48
49
sage: R = Integers(101^3)
50
sage: a = R(824362); b = R(205942)
51
sage: a * b
52
851127
53
"""
54
55
#################################################################################
56
# Copyright (C) 2006 Robert Bradshaw <[email protected]>
57
# 2006 William Stein <[email protected]>
58
#
59
# Distributed under the terms of the GNU General Public License (GPL)
60
#
61
# http://www.gnu.org/licenses/
62
#*****************************************************************************
63
64
65
include "../../ext/interrupt.pxi" # ctrl-c interrupt block support
66
include "../../ext/stdsage.pxi"
67
include "../../ext/python_int.pxi"
68
69
cdef extern from "math.h":
70
double log(double)
71
int ceil(double)
72
73
cdef extern from "mpz_pylong.h":
74
cdef mpz_get_pyintlong(mpz_t src)
75
76
import operator
77
78
cdef bint use_32bit_type(int_fast64_t modulus):
79
return modulus <= INTEGER_MOD_INT32_LIMIT
80
81
## import arith
82
import sage.rings.rational as rational
83
from sage.libs.pari.all import pari, PariError
84
import sage.rings.integer_ring as integer_ring
85
86
import sage.rings.commutative_ring_element as commutative_ring_element
87
import sage.interfaces.all
88
89
import sage.rings.integer
90
import sage.rings.integer_ring
91
cimport sage.rings.integer
92
from sage.rings.integer cimport Integer
93
94
import sage.structure.element
95
cimport sage.structure.element
96
from sage.structure.element cimport RingElement, ModuleElement, Element
97
from sage.categories.morphism cimport Morphism
98
from sage.categories.map cimport Map
99
100
from sage.structure.sage_object import register_unpickle_override
101
102
#from sage.structure.parent cimport Parent
103
104
cdef Integer one_Z = Integer(1)
105
106
def Mod(n, m, parent=None):
107
"""
108
Return the equivalence class of `n` modulo `m` as
109
an element of `\ZZ/m\ZZ`.
110
111
EXAMPLES::
112
113
sage: x = Mod(12345678, 32098203845329048)
114
sage: x
115
12345678
116
sage: x^100
117
1017322209155072
118
119
You can also use the lowercase version::
120
121
sage: mod(12,5)
122
2
123
124
Illustrates that trac #5971 is fixed. Consider `n` modulo `m` when
125
`m = 0`. Then `\ZZ/0\ZZ` is isomorphic to `\ZZ` so `n` modulo `0` is
126
is equivalent to `n` for any integer value of `n`::
127
128
sage: Mod(10, 0)
129
10
130
sage: a = randint(-100, 100)
131
sage: Mod(a, 0) == a
132
True
133
"""
134
# when m is zero, then ZZ/0ZZ is isomorphic to ZZ
135
if m == 0:
136
return n
137
138
# m is non-zero, so return n mod m
139
cdef IntegerMod_abstract x
140
import integer_mod_ring
141
x = IntegerMod(integer_mod_ring.IntegerModRing(m), n)
142
if parent is None:
143
return x
144
x._parent = parent
145
return x
146
147
148
mod = Mod
149
150
register_unpickle_override('sage.rings.integer_mod', 'Mod', Mod)
151
register_unpickle_override('sage.rings.integer_mod', 'mod', mod)
152
153
def IntegerMod(parent, value):
154
"""
155
Create an integer modulo `n` with the given parent.
156
157
This is mainly for internal use.
158
"""
159
cdef NativeIntStruct modulus
160
cdef Py_ssize_t res
161
modulus = parent._pyx_order
162
if modulus.table is not None:
163
if PY_TYPE_CHECK(value, sage.rings.integer.Integer) or PY_TYPE_CHECK(value, int) or PY_TYPE_CHECK(value, long):
164
res = value % modulus.int64
165
if res < 0:
166
res = res + modulus.int64
167
a = modulus.lookup(res)
168
if (<Element>a)._parent is not parent:
169
(<Element>a)._parent = parent
170
# print (<Element>a)._parent, " is not ", parent
171
return a
172
if modulus.int32 != -1:
173
return IntegerMod_int(parent, value)
174
elif modulus.int64 != -1:
175
return IntegerMod_int64(parent, value)
176
else:
177
return IntegerMod_gmp(parent, value)
178
179
def is_IntegerMod(x):
180
"""
181
Return ``True`` if and only if x is an integer modulo
182
`n`.
183
184
EXAMPLES::
185
186
sage: from sage.rings.finite_rings.integer_mod import is_IntegerMod
187
sage: is_IntegerMod(5)
188
False
189
sage: is_IntegerMod(Mod(5,10))
190
True
191
"""
192
return PY_TYPE_CHECK(x, IntegerMod_abstract)
193
194
def makeNativeIntStruct(sage.rings.integer.Integer z):
195
"""
196
Function to convert a Sage Integer into class NativeIntStruct.
197
198
.. note::
199
200
This function seems completely redundant, and is not used
201
anywhere.
202
"""
203
return NativeIntStruct(z)
204
205
register_unpickle_override('sage.rings.integer_mod', 'makeNativeIntStruct', makeNativeIntStruct)
206
207
cdef class NativeIntStruct:
208
"""
209
We store the various forms of the modulus here rather than in the
210
parent for efficiency reasons.
211
212
We may also store a cached table of all elements of a given ring in
213
this class.
214
"""
215
def __init__(NativeIntStruct self, sage.rings.integer.Integer z):
216
self.int64 = -1
217
self.int32 = -1
218
self.table = None # NULL
219
self.sageInteger = z
220
if mpz_cmp_si(z.value, INTEGER_MOD_INT64_LIMIT) <= 0:
221
self.int64 = mpz_get_si(z.value)
222
if use_32bit_type(self.int64):
223
self.int32 = self.int64
224
225
def __reduce__(NativeIntStruct self):
226
return sage.rings.finite_rings.integer_mod.makeNativeIntStruct, (self.sageInteger, )
227
228
def precompute_table(NativeIntStruct self, parent, inverses=True):
229
"""
230
Function to compute and cache all elements of this class.
231
232
If inverses==True, also computes and caches the inverses of the
233
invertible elements
234
"""
235
self.table = PyList_New(self.int64)
236
cdef Py_ssize_t i
237
if self.int32 != -1:
238
for i from 0 <= i < self.int32:
239
z = IntegerMod_int(parent, i)
240
Py_INCREF(z); PyList_SET_ITEM(self.table, i, z)
241
else:
242
for i from 0 <= i < self.int64:
243
z = IntegerMod_int64(parent, i)
244
Py_INCREF(z); PyList_SET_ITEM(self.table, i, z)
245
246
if inverses:
247
tmp = [None] * self.int64
248
for i from 1 <= i < self.int64:
249
try:
250
tmp[i] = ~self.table[i]
251
except ZeroDivisionError:
252
pass
253
self.inverses = tmp
254
255
def _get_table(self):
256
return self.table
257
258
cdef lookup(NativeIntStruct self, Py_ssize_t value):
259
return <object>PyList_GET_ITEM(self.table, value)
260
261
262
cdef class IntegerMod_abstract(FiniteRingElement):
263
264
def __init__(self, parent):
265
"""
266
EXAMPLES::
267
268
sage: a = Mod(10,30^10); a
269
10
270
sage: loads(a.dumps()) == a
271
True
272
"""
273
self._parent = parent
274
self.__modulus = parent._pyx_order
275
276
277
cdef _new_c_from_long(self, long value):
278
cdef IntegerMod_abstract x
279
x = <IntegerMod_abstract>PY_NEW(<object>PY_TYPE(self))
280
if PY_TYPE_CHECK(x, IntegerMod_gmp):
281
mpz_init((<IntegerMod_gmp>x).value) # should be done by the new method
282
x._parent = self._parent
283
x.__modulus = self.__modulus
284
x.set_from_long(value)
285
return x
286
287
cdef void set_from_mpz(self, mpz_t value):
288
raise NotImplementedError, "Must be defined in child class."
289
290
cdef void set_from_long(self, long value):
291
raise NotImplementedError, "Must be defined in child class."
292
293
def __abs__(self):
294
"""
295
Raise an error message, since ``abs(x)`` makes no sense
296
when ``x`` is an integer modulo `n`.
297
298
EXAMPLES::
299
300
sage: abs(Mod(2,3))
301
Traceback (most recent call last):
302
...
303
ArithmeticError: absolute valued not defined on integers modulo n.
304
"""
305
raise ArithmeticError, "absolute valued not defined on integers modulo n."
306
307
def __reduce__(IntegerMod_abstract self):
308
"""
309
EXAMPLES::
310
311
sage: a = Mod(4,5); a
312
4
313
sage: loads(a.dumps()) == a
314
True
315
sage: a = Mod(-1,5^30)^25;
316
sage: loads(a.dumps()) == a
317
True
318
"""
319
return sage.rings.finite_rings.integer_mod.mod, (self.lift(), self.modulus(), self.parent())
320
321
def is_nilpotent(self):
322
r"""
323
Return ``True`` if ``self`` is nilpotent,
324
i.e., some power of ``self`` is zero.
325
326
EXAMPLES::
327
328
sage: a = Integers(90384098234^3)
329
sage: factor(a.order())
330
2^3 * 191^3 * 236607587^3
331
sage: b = a(2*191)
332
sage: b.is_nilpotent()
333
False
334
sage: b = a(2*191*236607587)
335
sage: b.is_nilpotent()
336
True
337
338
ALGORITHM: Let `m \geq \log_2(n)`, where `n` is
339
the modulus. Then `x \in \ZZ/n\ZZ` is
340
nilpotent if and only if `x^m = 0`.
341
342
PROOF: This is clear if you reduce to the prime power case, which
343
you can do via the Chinese Remainder Theorem.
344
345
We could alternatively factor `n` and check to see if the
346
prime divisors of `n` all divide `x`. This is
347
asymptotically slower :-).
348
"""
349
if self.is_zero():
350
return True
351
m = self.__modulus.sageInteger.exact_log(2) + 1
352
return (self**m).is_zero()
353
354
#################################################################
355
# Interfaces
356
#################################################################
357
def _pari_init_(self):
358
return 'Mod(%s,%s)'%(str(self), self.__modulus.sageInteger)
359
360
def pari(self):
361
return pari(self._pari_init_()) # TODO: is this called implicitly anywhere?
362
363
def _gap_init_(self):
364
r"""
365
Return string representation of corresponding GAP object.
366
367
EXAMPLES::
368
369
sage: a = Mod(2,19)
370
sage: gap(a)
371
Z(19)
372
sage: gap(Mod(3, next_prime(10000)))
373
Z(10007)^6190
374
sage: gap(Mod(3, next_prime(100000)))
375
ZmodpZObj( 3, 100003 )
376
sage: gap(Mod(4, 48))
377
ZmodnZObj( 4, 48 )
378
"""
379
return '%s*One(ZmodnZ(%s))' % (self, self.__modulus.sageInteger)
380
381
def _magma_init_(self, magma):
382
"""
383
Coercion to Magma.
384
385
EXAMPLES::
386
387
sage: a = Integers(15)(4)
388
sage: b = magma(a) # optional - magma
389
sage: b.Type() # optional - magma
390
RngIntResElt
391
sage: b^2 # optional - magma
392
1
393
"""
394
return '%s!%s'%(self.parent()._magma_init_(magma), self)
395
396
def _axiom_init_(self):
397
"""
398
Return a string representation of the corresponding to
399
(Pan)Axiom object.
400
401
EXAMPLES::
402
403
sage: a = Integers(15)(4)
404
sage: a._axiom_init_()
405
'4 :: IntegerMod(15)'
406
407
sage: aa = axiom(a); aa #optional - axiom
408
4
409
sage: aa.type() #optional - axiom
410
IntegerMod 15
411
412
sage: aa = fricas(a); aa #optional - fricas
413
4
414
sage: aa.type() #optional - fricas
415
IntegerMod(15)
416
417
"""
418
return '%s :: %s'%(self, self.parent()._axiom_init_())
419
420
_fricas_init_ = _axiom_init_
421
422
def _sage_input_(self, sib, coerced):
423
r"""
424
Produce an expression which will reproduce this value when
425
evaluated.
426
427
EXAMPLES::
428
429
sage: K = GF(7)
430
sage: sage_input(K(5), verify=True)
431
# Verified
432
GF(7)(5)
433
sage: sage_input(K(5) * polygen(K), verify=True)
434
# Verified
435
R.<x> = GF(7)[]
436
5*x
437
sage: from sage.misc.sage_input import SageInputBuilder
438
sage: K(5)._sage_input_(SageInputBuilder(), False)
439
{call: {call: {atomic:GF}({atomic:7})}({atomic:5})}
440
sage: K(5)._sage_input_(SageInputBuilder(), True)
441
{atomic:5}
442
"""
443
v = sib.int(self.lift())
444
if coerced:
445
return v
446
else:
447
return sib(self.parent())(v)
448
449
def log(self, b=None):
450
r"""
451
Return an integer `x` such that `b^x = a`, where
452
`a` is ``self``.
453
454
INPUT:
455
456
457
- ``self`` - unit modulo `n`
458
459
- ``b`` - a unit modulo `n`. If ``b`` is not given,
460
``R.multiplicative_generator()`` is used, where
461
``R`` is the parent of ``self``.
462
463
464
OUTPUT: Integer `x` such that `b^x = a`, if this exists; a ValueError otherwise.
465
466
.. note::
467
468
If the modulus is prime and b is a generator, this calls Pari's ``znlog``
469
function, which is rather fast. If not, it falls back on the generic
470
discrete log implementation in :meth:`sage.groups.generic.discrete_log`.
471
472
EXAMPLES::
473
474
sage: r = Integers(125)
475
sage: b = r.multiplicative_generator()^3
476
sage: a = b^17
477
sage: a.log(b)
478
17
479
sage: a.log()
480
51
481
482
A bigger example::
483
484
sage: FF = FiniteField(2^32+61)
485
sage: c = FF(4294967356)
486
sage: x = FF(2)
487
sage: a = c.log(x)
488
sage: a
489
2147483678
490
sage: x^a
491
4294967356
492
493
Things that can go wrong. E.g., if the base is not a generator for
494
the multiplicative group, or not even a unit.
495
496
::
497
498
sage: Mod(3, 7).log(Mod(2, 7))
499
Traceback (most recent call last):
500
...
501
ValueError: No discrete log of 3 found to base 2
502
sage: a = Mod(16, 100); b = Mod(4,100)
503
sage: a.log(b)
504
Traceback (most recent call last):
505
...
506
ZeroDivisionError: Inverse does not exist.
507
508
We check that #9205 is fixed::
509
510
sage: Mod(5,9).log(Mod(2, 9))
511
5
512
513
We test against a bug (side effect on PARI) fixed in #9438::
514
515
sage: R.<a, b> = QQ[]
516
sage: pari(b)
517
b
518
sage: GF(7)(5).log()
519
5
520
sage: pari(b)
521
b
522
523
AUTHORS:
524
525
- David Joyner and William Stein (2005-11)
526
527
- William Stein (2007-01-27): update to use PARI as requested
528
by David Kohel.
529
530
- Simon King (2010-07-07): fix a side effect on PARI
531
"""
532
if b is None:
533
b = self._parent.multiplicative_generator()
534
else:
535
b = self._parent(b)
536
537
if self.modulus().is_prime() and b.multiplicative_order() == b.parent().unit_group_order():
538
539
# use PARI
540
541
cmd = 'if(znorder(Mod(%s,%s))!=eulerphi(%s),-1,znlog(%s,Mod(%s,%s)))'%(b, self.__modulus.sageInteger,
542
self.__modulus.sageInteger,
543
self, b, self.__modulus.sageInteger)
544
try:
545
n = Integer(pari(cmd))
546
return n
547
except PariError, msg:
548
raise ValueError, "%s\nPARI failed to compute discrete log (perhaps base is not a generator or is too large)"%msg
549
550
else: # fall back on slower native implementation
551
552
from sage.groups.generic import discrete_log
553
return discrete_log(self, b)
554
555
def generalised_log(self):
556
r"""
557
Return integers `n_i` such that
558
559
..math::
560
561
\prod_i x_i^{n_i} = \text{self},
562
563
where `x_1, \dots, x_d` are the generators of the unit group
564
returned by ``self.parent().unit_gens()``. See also :meth:`log`.
565
566
EXAMPLES::
567
568
sage: m = Mod(3, 1568)
569
sage: v = m.generalised_log(); v
570
[1, 3, 1]
571
sage: prod([Zmod(1568).unit_gens()[i] ** v[i] for i in [0..2]])
572
3
573
574
"""
575
if not self.is_unit():
576
raise ZeroDivisionError
577
N = self.modulus()
578
h = []
579
for (p, c) in N.factor():
580
if p != 2 or (p == 2 and c == 2):
581
h.append((self % p**c).log())
582
elif c > 2:
583
m = self % p**c
584
if m % 4 == 1:
585
h.append(0)
586
else:
587
h.append(1)
588
m *= -1
589
h.append(m.log(5))
590
return h
591
592
def modulus(IntegerMod_abstract self):
593
"""
594
EXAMPLES::
595
596
sage: Mod(3,17).modulus()
597
17
598
"""
599
return self.__modulus.sageInteger
600
601
def charpoly(self, var='x'):
602
"""
603
Returns the characteristic polynomial of this element.
604
605
EXAMPLES::
606
607
sage: k = GF(3)
608
sage: a = k.gen()
609
sage: a.charpoly('x')
610
x + 2
611
sage: a + 2
612
0
613
614
AUTHORS:
615
616
- Craig Citro
617
"""
618
R = self.parent()[var]
619
return R([-self,1])
620
621
def minpoly(self, var='x'):
622
"""
623
Returns the minimal polynomial of this element.
624
625
EXAMPLES:
626
sage: GF(241, 'a')(1).minpoly()
627
x + 240
628
"""
629
return self.charpoly(var)
630
631
def minimal_polynomial(self, var='x'):
632
"""
633
Returns the minimal polynomial of this element.
634
635
EXAMPLES:
636
sage: GF(241, 'a')(1).minimal_polynomial(var = 'z')
637
z + 240
638
"""
639
return self.minpoly(var)
640
641
def polynomial(self, var='x'):
642
"""
643
Returns a constant polynomial representing this value.
644
645
EXAMPLES::
646
647
sage: k = GF(7)
648
sage: a = k.gen(); a
649
1
650
sage: a.polynomial()
651
1
652
sage: type(a.polynomial())
653
<type 'sage.rings.polynomial.polynomial_zmod_flint.Polynomial_zmod_flint'>
654
"""
655
R = self.parent()[var]
656
return R(self)
657
658
def norm(self):
659
"""
660
Returns the norm of this element, which is itself. (This is here
661
for compatibility with higher order finite fields.)
662
663
EXAMPLES::
664
665
sage: k = GF(691)
666
sage: a = k(389)
667
sage: a.norm()
668
389
669
670
AUTHORS:
671
672
- Craig Citro
673
"""
674
return self
675
676
def trace(self):
677
"""
678
Returns the trace of this element, which is itself. (This is here
679
for compatibility with higher order finite fields.)
680
681
EXAMPLES::
682
683
sage: k = GF(691)
684
sage: a = k(389)
685
sage: a.trace()
686
389
687
688
AUTHORS:
689
690
- Craig Citro
691
"""
692
return self
693
694
cpdef bint is_one(self):
695
raise NotImplementedError
696
697
cpdef bint is_unit(self):
698
raise NotImplementedError
699
700
def is_square(self):
701
r"""
702
EXAMPLES::
703
704
sage: Mod(3,17).is_square()
705
False
706
sage: Mod(9,17).is_square()
707
True
708
sage: Mod(9,17*19^2).is_square()
709
True
710
sage: Mod(-1,17^30).is_square()
711
True
712
sage: Mod(1/9, next_prime(2^40)).is_square()
713
True
714
sage: Mod(1/25, next_prime(2^90)).is_square()
715
True
716
717
TESTS::
718
719
sage: Mod(1/25, 2^8).is_square()
720
True
721
sage: Mod(1/25, 2^40).is_square()
722
True
723
724
ALGORITHM: Calculate the Jacobi symbol
725
`(\mathtt{self}/p)` at each prime `p`
726
dividing `n`. It must be 1 or 0 for each prime, and if it
727
is 0 mod `p`, where `p^k || n`, then
728
`ord_p(\mathtt{self})` must be even or greater than
729
`k`.
730
731
The case `p = 2` is handled separately.
732
733
AUTHORS:
734
735
- Robert Bradshaw
736
"""
737
return self.is_square_c()
738
739
cdef bint is_square_c(self) except -2:
740
if self.is_zero() or self.is_one():
741
return 1
742
moduli = self.parent().factored_order()
743
cdef int val, e
744
lift = self.lift()
745
if len(moduli) == 1:
746
p, e = moduli[0]
747
if e == 1:
748
return lift.jacobi(p) != -1
749
elif p == 2:
750
return self.pari().issquare() # TODO: implement directly
751
elif self % p == 0:
752
val = lift.valuation(p)
753
return val >= e or (val % 2 == 0 and (lift // p**val).jacobi(p) != -1)
754
else:
755
return lift.jacobi(p) != -1
756
else:
757
for p, e in moduli:
758
if p == 2:
759
if e > 1 and not self.pari().issquare(): # TODO: implement directly
760
return 0
761
elif e > 1 and lift % p == 0:
762
val = lift.valuation(p)
763
if val < e and (val % 2 == 1 or (lift // p**val).jacobi(p) == -1):
764
return 0
765
elif lift.jacobi(p) == -1:
766
return 0
767
return 1
768
769
def sqrt(self, extend=True, all=False):
770
r"""
771
Returns square root or square roots of ``self`` modulo
772
`n`.
773
774
INPUT:
775
776
777
- ``extend`` - bool (default: ``True``);
778
if ``True``, return a square root in an extension ring,
779
if necessary. Otherwise, raise a ``ValueError`` if the
780
square root is not in the base ring.
781
782
- ``all`` - bool (default: ``False``); if
783
``True``, return {all} square roots of self, instead of
784
just one.
785
786
787
ALGORITHM: Calculates the square roots mod `p` for each of
788
the primes `p` dividing the order of the ring, then lifts
789
them `p`-adically and uses the CRT to find a square root
790
mod `n`.
791
792
See also ``square_root_mod_prime_power`` and
793
``square_root_mod_prime`` (in this module) for more
794
algorithmic details.
795
796
EXAMPLES::
797
798
sage: mod(-1, 17).sqrt()
799
4
800
sage: mod(5, 389).sqrt()
801
86
802
sage: mod(7, 18).sqrt()
803
5
804
sage: a = mod(14, 5^60).sqrt()
805
sage: a*a
806
14
807
sage: mod(15, 389).sqrt(extend=False)
808
Traceback (most recent call last):
809
...
810
ValueError: self must be a square
811
sage: Mod(1/9, next_prime(2^40)).sqrt()^(-2)
812
9
813
sage: Mod(1/25, next_prime(2^90)).sqrt()^(-2)
814
25
815
816
::
817
818
sage: a = Mod(3,5); a
819
3
820
sage: x = Mod(-1, 360)
821
sage: x.sqrt(extend=False)
822
Traceback (most recent call last):
823
...
824
ValueError: self must be a square
825
sage: y = x.sqrt(); y
826
sqrt359
827
sage: y.parent()
828
Univariate Quotient Polynomial Ring in sqrt359 over Ring of integers modulo 360 with modulus x^2 + 1
829
sage: y^2
830
359
831
832
We compute all square roots in several cases::
833
834
sage: R = Integers(5*2^3*3^2); R
835
Ring of integers modulo 360
836
sage: R(40).sqrt(all=True)
837
[20, 160, 200, 340]
838
sage: [x for x in R if x^2 == 40] # Brute force verification
839
[20, 160, 200, 340]
840
sage: R(1).sqrt(all=True)
841
[1, 19, 71, 89, 91, 109, 161, 179, 181, 199, 251, 269, 271, 289, 341, 359]
842
sage: R(0).sqrt(all=True)
843
[0, 60, 120, 180, 240, 300]
844
845
::
846
847
sage: R = Integers(5*13^3*37); R
848
Ring of integers modulo 406445
849
sage: v = R(-1).sqrt(all=True); v
850
[78853, 111808, 160142, 193097, 213348, 246303, 294637, 327592]
851
sage: [x^2 for x in v]
852
[406444, 406444, 406444, 406444, 406444, 406444, 406444, 406444]
853
sage: v = R(169).sqrt(all=True); min(v), -max(v), len(v)
854
(13, 13, 104)
855
sage: all([x^2==169 for x in v])
856
True
857
858
Modulo a power of 2::
859
860
sage: R = Integers(2^7); R
861
Ring of integers modulo 128
862
sage: a = R(17)
863
sage: a.sqrt()
864
23
865
sage: a.sqrt(all=True)
866
[23, 41, 87, 105]
867
sage: [x for x in R if x^2==17]
868
[23, 41, 87, 105]
869
"""
870
if self.is_one():
871
if all:
872
return list(self.parent().square_roots_of_one())
873
else:
874
return self
875
876
if not self.is_square_c():
877
if extend:
878
y = 'sqrt%s'%self
879
R = self.parent()['x']
880
modulus = R.gen()**2 - R(self)
881
if self._parent.is_field():
882
import constructor
883
Q = constructor.FiniteField(self.__modulus.sageInteger**2, y, modulus)
884
else:
885
R = self.parent()['x']
886
Q = R.quotient(modulus, names=(y,))
887
z = Q.gen()
888
if all:
889
# TODO
890
raise NotImplementedError
891
return z
892
raise ValueError, "self must be a square"
893
894
F = self._parent.factored_order()
895
cdef long e, exp, val
896
if len(F) == 1:
897
p, e = F[0]
898
899
if all and e > 1 and not self.is_unit():
900
if self.is_zero():
901
# All multiples of p^ciel(e/2) vanish
902
return [self._parent(x) for x in xrange(0, self.__modulus.sageInteger, p**((e+1)/2))]
903
else:
904
z = self.lift()
905
val = z.valuation(p)/2 # square => valuation is even
906
from sage.rings.finite_rings.integer_mod_ring import IntegerModRing
907
# Find the unit part (mod the ring with appropriate precision)
908
u = IntegerModRing(p**(e-val))(z // p**(2*val))
909
# will add multiples of p^exp
910
exp = e - val
911
if p == 2:
912
exp -= 1 # note the factor of 2 below
913
if 2*exp < e:
914
exp = (e+1)/2
915
# For all a^2 = u and all integers b
916
# (a*p^val + b*p^exp) ^ 2
917
# = u*p^(2*val) + 2*a*b*p^(val+exp) + b^2*p^(2*exp)
918
# = u*p^(2*val) mod p^e
919
# whenever min(val+exp, 2*exp) > e
920
p_val = p**val
921
p_exp = p**exp
922
w = [self._parent(a.lift() * p_val + b)
923
for a in u.sqrt(all=True)
924
for b in xrange(0, self.__modulus.sageInteger, p_exp)]
925
if p == 2:
926
w = list(set(w))
927
w.sort()
928
return w
929
930
if e > 1:
931
x = square_root_mod_prime_power(mod(self, p**e), p, e)
932
else:
933
x = square_root_mod_prime(self, p)
934
x = x._balanced_abs()
935
936
if not all:
937
return x
938
939
v = list(set([x*a for a in self._parent.square_roots_of_one()]))
940
v.sort()
941
return v
942
943
else:
944
if not all:
945
# Use CRT to combine together a square root modulo each prime power
946
sqrts = [square_root_mod_prime(mod(self, p), p) for p, e in F if e == 1] + \
947
[square_root_mod_prime_power(mod(self, p**e), p, e) for p, e in F if e != 1]
948
949
x = sqrts.pop()
950
for y in sqrts:
951
x = x.crt(y)
952
return x._balanced_abs()
953
else:
954
# Use CRT to combine together all square roots modulo each prime power
955
vmod = []
956
moduli = []
957
P = self.parent()
958
from sage.rings.finite_rings.integer_mod_ring import IntegerModRing
959
for p, e in F:
960
k = p**e
961
R = IntegerModRing(p**e)
962
w = [P(x) for x in R(self).sqrt(all=True)]
963
vmod.append(w)
964
moduli.append(k)
965
# Now combine in all possible ways using the CRT
966
from sage.rings.arith import CRT_basis
967
basis = CRT_basis(moduli)
968
from sage.misc.mrange import cartesian_product_iterator
969
v = []
970
for x in cartesian_product_iterator(vmod):
971
# x is a specific choice of roots modulo each prime power divisor
972
a = sum([basis[i]*x[i] for i in range(len(x))])
973
v.append(a)
974
v.sort()
975
return v
976
977
square_root = sqrt
978
979
def nth_root(self, n, extend = False, all = False, algorithm = None, cunningham = False):
980
r"""
981
Returns an `n`\th root of ``self``.
982
983
INPUT:
984
985
- ``n`` - integer `\geq 1`
986
987
- ``extend`` - bool (default: True); if True, return an nth
988
root in an extension ring, if necessary. Otherwise, raise a
989
ValueError if the root is not in the base ring. Warning:
990
this option is not implemented!
991
992
- ``all`` - bool (default: ``False``); if ``True``, return all `n`\th
993
roots of ``self``, instead of just one.
994
995
- ``algorithm`` - string (default: None); The algorithm for the prime modulus case.
996
CRT and p-adic log techniques are used to reduce to this case.
997
'Johnston' is the only currently supported option.
998
999
OUTPUT:
1000
1001
If self has an `n`\th root, returns one (if ``all`` is ``False``) or a
1002
list of all of them (if ``all`` is ``True``). Otherwise, raises a
1003
``ValueError`` (if ``extend`` is ``False``) or a ``NotImplementedError`` (if
1004
``extend`` is ``True``).
1005
1006
.. warning::
1007
The 'extend' option is not implemented (yet).
1008
1009
NOTES:
1010
1011
- If `n = 0`:
1012
1013
- if ``all=True``:
1014
1015
- if ``self=1``: all nonzero elements of the parent are returned in
1016
a list. Note that this could be very expensive for large
1017
parents.
1018
1019
- otherwise: an empty list is returned
1020
1021
- if ``all=False``:
1022
1023
- if ``self=1``: ``self`` is returned
1024
1025
- otherwise; a ``ValueError`` is raised
1026
1027
- If `n < 0`:
1028
1029
- if self is invertible, the `(-n)`\th root of the inverse of self is returned
1030
1031
- otherwise a ``ValueError`` is raised or empty list returned.
1032
1033
EXAMPLES::
1034
1035
1036
sage: K = GF(31)
1037
sage: a = K(22)
1038
sage: K(22).nth_root(7)
1039
13
1040
sage: K(25).nth_root(5)
1041
5
1042
sage: K(23).nth_root(3)
1043
29
1044
sage: mod(225,2^5*3^2).nth_root(4, all=True)
1045
[225, 129, 33, 63, 255, 159, 9, 201, 105, 279, 183, 87, 81, 273, 177, 207, 111, 15, 153, 57, 249, 135, 39, 231]
1046
sage: mod(275,2^5*7^4).nth_root(7, all=True)
1047
[58235, 25307, 69211, 36283, 3355, 47259, 14331]
1048
sage: mod(1,8).nth_root(2,all=True)
1049
[1, 7, 5, 3]
1050
sage: mod(4,8).nth_root(2,all=True)
1051
[2, 6]
1052
sage: mod(1,16).nth_root(4,all=True)
1053
[1, 15, 13, 3, 9, 7, 5, 11]
1054
sage: (mod(22,31)^200).nth_root(200)
1055
5
1056
sage: mod(3,6).nth_root(0,all=True)
1057
[]
1058
sage: mod(3,6).nth_root(0)
1059
Traceback (most recent call last):
1060
...
1061
ValueError
1062
sage: mod(1,6).nth_root(0,all=True)
1063
[1, 2, 3, 4, 5]
1064
1065
TESTS::
1066
1067
sage: for p in [1009,2003,10007,100003]:
1068
... K = GF(p)
1069
... for r in (p-1).divisors():
1070
... if r == 1: continue
1071
... x = K.random_element()
1072
... y = x^r
1073
... if y.nth_root(r)**r != y: raise RuntimeError
1074
... if (y^41).nth_root(41*r)**(41*r) != y^41: raise RuntimeError
1075
... if (y^307).nth_root(307*r)**(307*r) != y^307: raise RuntimeError
1076
1077
sage: for t in xrange(200):
1078
... n = randint(1,2^63)
1079
... K = Integers(n)
1080
... b = K.random_element()
1081
... e = randint(-2^62, 2^63)
1082
... try:
1083
... a = b.nth_root(e)
1084
... if a^e != b:
1085
... print n, b, e, a
1086
... raise NotImplementedError
1087
... except ValueError:
1088
... pass
1089
1090
ALGORITHMS:
1091
1092
- The default for prime modulus is currently an algorithm described in the following paper:
1093
1094
Johnston, Anna M. A generalized qth root algorithm. Proceedings of the tenth annual ACM-SIAM symposium on Discrete algorithms. Baltimore, 1999: pp 929-930.
1095
1096
AUTHORS:
1097
1098
- David Roe (2010-2-13)
1099
"""
1100
if extend:
1101
raise NotImplementedError
1102
K = self.parent()
1103
n = Integer(n)
1104
if n == 0:
1105
if self == 1:
1106
if all: return [K(a) for a in range(1,K.order())]
1107
else: return self
1108
else:
1109
if all: return []
1110
else: raise ValueError
1111
F = K.factored_order()
1112
if len(F) == 0:
1113
if all:
1114
return [self]
1115
else:
1116
return self
1117
if len(F) != 1:
1118
if all:
1119
# 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...
1120
L = []
1121
for p, k in F:
1122
L.append(mod(self, p**k).nth_root(n, all=True, algorithm=algorithm))
1123
ans = L[0]
1124
for i in range(1, len(L)):
1125
ans = [a.crt(b) for a in ans for b in L[i]]
1126
else:
1127
ans = mod(0,1)
1128
for p, k in F:
1129
ans = ans.crt(mod(self, p**k).nth_root(n, algorithm=algorithm))
1130
return ans
1131
p, k = F[0]
1132
if self.is_zero():
1133
if n < 0:
1134
if all: return []
1135
else: raise ValueError
1136
if all:
1137
if k == 1:
1138
return [self]
1139
else:
1140
minval = max(1, (k/n).ceil())
1141
return [K(a*p**minval) for a in range(p**(k-minval))]
1142
else:
1143
return self
1144
if n < 0:
1145
try:
1146
self = ~self
1147
except ZeroDivisionError:
1148
if all: return []
1149
else: raise ValueError
1150
n = -n
1151
if p == 2 and k == 1:
1152
if all: return [self]
1153
else: return self
1154
if k > 1:
1155
pval, upart = self.lift().val_unit(p)
1156
if not n.divides(pval):
1157
if all:
1158
return []
1159
else:
1160
raise ValueError, "no nth root"
1161
if pval > 0:
1162
if all:
1163
return [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))]
1164
else:
1165
return K(p**(pval // n) * mod(upart, p**(k-pval)).nth_root(n, algorithm=algorithm).lift())
1166
from sage.rings.padics.all import ZpFM
1167
R = ZpFM(p,k,print_mode='digits')
1168
self_orig = self
1169
if p == 2:
1170
sign = [1]
1171
if self % 4 == 3:
1172
if n % 2 == 0:
1173
if all: return []
1174
else: raise ValueError, "no nth root"
1175
else:
1176
sign = [-1]
1177
self = -self
1178
elif n % 2 == 0:
1179
if k > 2 and self % 8 == 5:
1180
if all: return []
1181
else: raise ValueError, "no nth root"
1182
sign = [1, -1]
1183
if k == 2:
1184
if all: return [K(s) for s in sign[:2]]
1185
else: return K(sign[0])
1186
if all: modp = [mod(self,8)]
1187
else: modp = mod(self,8)
1188
else:
1189
sign = [1]
1190
modp = self % p
1191
self = self / K(R.teichmuller(modp))
1192
modp = modp.nth_root(n, all=all, algorithm=algorithm)
1193
# now self is congruent to 1 mod 4 or 1 mod p (for odd p), so the power series for p-adic log converges.
1194
# Hensel lifting is probably better, but this is easier at the moment.
1195
plog = R(self).log()
1196
nval = n.valuation(p)
1197
if nval >= plog.valuation() + (-1 if p == 2 else 0):
1198
if self == 1:
1199
if all:
1200
return [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]
1201
else: return self_orig
1202
else:
1203
if all: return []
1204
else: raise ValueError, "no nth root"
1205
if all:
1206
ans = [plog // n + p**(k - nval) * i for i in range(p**nval)]
1207
ans = [s*K(R.teichmuller(m) * a.exp()) for a in ans for m in modp for s in sign]
1208
return ans
1209
else:
1210
return sign[0] * K(R.teichmuller(modp) * (plog // n).exp())
1211
return self._nth_root_common(n, all, algorithm, cunningham)
1212
1213
def _nth_root_naive(self, n):
1214
"""
1215
Computes all nth roots using brute force, for doc-testing.
1216
1217
TESTS::
1218
1219
sage: for n in range(2,100): # long time
1220
... K=Integers(n)
1221
... elist = range(1,min(2*n+2,100))
1222
... for e in random_sublist(elist, 5/len(elist)):
1223
... for a in random_sublist(range(1,n), min((n+2)//2,10)/(n-1)):
1224
... b = K(a)
1225
... try:
1226
... L = b.nth_root(e, all=True)
1227
... if len(L) > 0:
1228
... c = b.nth_root(e)
1229
... except:
1230
... L = [-1]
1231
... M = b._nth_root_naive(e)
1232
... if sorted(L) != M:
1233
... print "mod(%s, %s).nth_root(%s,all=True), mod(%s, %s)._nth_root_naive(%s)"%(a,n,e,a,n,e)
1234
... raise ValueError
1235
... if len(L) > 0 and (c not in L):
1236
... print "mod(%s, %s).nth_root(%s), mod(%s, %s).nth_root(%s,all=True)"%(a,n,e,a,n,e)
1237
... raise ValueError
1238
"""
1239
L = []
1240
for a in self.parent():
1241
if a**n == self:
1242
L.append(a)
1243
return L
1244
1245
def _balanced_abs(self):
1246
"""
1247
This function returns `x` or `-x`, whichever has a
1248
positive representative in `-n/2 < x \leq n/2`.
1249
1250
This is used so that the same square root is always returned,
1251
despite the possibly probabalistic nature of the underlying
1252
algorithm.
1253
"""
1254
if self.lift() > self.__modulus.sageInteger >> 1:
1255
return -self
1256
else:
1257
return self
1258
1259
1260
def rational_reconstruction(self):
1261
"""
1262
EXAMPLES::
1263
1264
sage: R = IntegerModRing(97)
1265
sage: a = R(2) / R(3)
1266
sage: a
1267
33
1268
sage: a.rational_reconstruction()
1269
2/3
1270
"""
1271
return self.lift().rational_reconstruction(self.modulus())
1272
1273
def crt(IntegerMod_abstract self, IntegerMod_abstract other):
1274
r"""
1275
Use the Chinese Remainder Theorem to find an element of the
1276
integers modulo the product of the moduli that reduces to
1277
``self`` and to ``other``. The modulus of
1278
``other`` must be coprime to the modulus of
1279
``self``.
1280
1281
EXAMPLES::
1282
1283
sage: a = mod(3,5)
1284
sage: b = mod(2,7)
1285
sage: a.crt(b)
1286
23
1287
1288
::
1289
1290
sage: a = mod(37,10^8)
1291
sage: b = mod(9,3^8)
1292
sage: a.crt(b)
1293
125900000037
1294
1295
::
1296
1297
sage: b = mod(0,1)
1298
sage: a.crt(b) == a
1299
True
1300
sage: a.crt(b).modulus()
1301
100000000
1302
1303
TESTS::
1304
1305
sage: mod(0,1).crt(mod(4,2^127))
1306
4
1307
sage: mod(4,2^127).crt(mod(0,1))
1308
4
1309
sage: mod(4,2^30).crt(mod(0,1))
1310
4
1311
sage: mod(0,1).crt(mod(4,2^30))
1312
4
1313
sage: mod(0,1).crt(mod(4,2^15))
1314
4
1315
sage: mod(4,2^15).crt(mod(0,1))
1316
4
1317
1318
AUTHORS:
1319
1320
- Robert Bradshaw
1321
"""
1322
cdef int_fast64_t new_modulus
1323
if not PY_TYPE_CHECK(self, IntegerMod_gmp) and not PY_TYPE_CHECK(other, IntegerMod_gmp):
1324
1325
if other.__modulus.int64 == 1: return self
1326
new_modulus = self.__modulus.int64 * other.__modulus.int64
1327
if new_modulus < INTEGER_MOD_INT32_LIMIT:
1328
return self.__crt(other)
1329
1330
elif new_modulus < INTEGER_MOD_INT64_LIMIT:
1331
if not PY_TYPE_CHECK(self, IntegerMod_int64):
1332
self = IntegerMod_int64(self._parent, self.lift())
1333
if not PY_TYPE_CHECK(other, IntegerMod_int64):
1334
other = IntegerMod_int64(other._parent, other.lift())
1335
return self.__crt(other)
1336
1337
if not PY_TYPE_CHECK(self, IntegerMod_gmp):
1338
if self.__modulus.int64 == 1: return other
1339
self = IntegerMod_gmp(self._parent, self.lift())
1340
1341
if not PY_TYPE_CHECK(other, IntegerMod_gmp):
1342
if other.__modulus.int64 == 1: return self
1343
other = IntegerMod_gmp(other._parent, other.lift())
1344
1345
return self.__crt(other)
1346
1347
1348
def additive_order(self):
1349
r"""
1350
Returns the additive order of self.
1351
1352
This is the same as ``self.order()``.
1353
1354
EXAMPLES::
1355
1356
sage: Integers(20)(2).additive_order()
1357
10
1358
sage: Integers(20)(7).additive_order()
1359
20
1360
sage: Integers(90308402384902)(2).additive_order()
1361
45154201192451
1362
"""
1363
n = self.__modulus.sageInteger
1364
return sage.rings.integer.Integer(n.__floordiv__(self.lift().gcd(n)))
1365
1366
def multiplicative_order(self):
1367
"""
1368
Returns the multiplicative order of self.
1369
1370
EXAMPLES::
1371
1372
sage: Mod(-1,5).multiplicative_order()
1373
2
1374
sage: Mod(1,5).multiplicative_order()
1375
1
1376
sage: Mod(0,5).multiplicative_order()
1377
Traceback (most recent call last):
1378
...
1379
ArithmeticError: multiplicative order of 0 not defined since it is not a unit modulo 5
1380
"""
1381
try:
1382
return sage.rings.integer.Integer(self.pari().order()) # pari's "order" is by default multiplicative
1383
except PariError:
1384
raise ArithmeticError, "multiplicative order of %s not defined since it is not a unit modulo %s"%(
1385
self, self.__modulus.sageInteger)
1386
1387
def valuation(self, p):
1388
"""
1389
The largest power r such that m is in the ideal generated by p^r or infinity if there is not a largest such power.
1390
However it is an error to take the valuation with respect to a unit.
1391
1392
.. NOTE::
1393
1394
This is not a valuation in the mathematical sense. As shown with the examples below.
1395
1396
EXAMPLES:
1397
1398
This example shows that the (a*b).valuation(n) is not always the same as a.valuation(n) + b.valuation(n)
1399
1400
::
1401
1402
sage: R=ZZ.quo(9)
1403
sage: a=R(3)
1404
sage: b=R(6)
1405
sage: a.valuation(3)
1406
1
1407
sage: a.valuation(3) + b.valuation(3)
1408
2
1409
sage: (a*b).valuation(3)
1410
+Infinity
1411
1412
The valuation with respect to a unit is an error
1413
1414
::
1415
1416
sage: a.valuation(4)
1417
Traceback (most recent call last):
1418
...
1419
ValueError: Valuation with respect to a unit is not defined.
1420
1421
TESTS::
1422
1423
sage: R=ZZ.quo(12)
1424
sage: a=R(2)
1425
sage: b=R(4)
1426
sage: a.valuation(2)
1427
1
1428
sage: b.valuation(2)
1429
+Infinity
1430
sage: ZZ.quo(1024)(16).valuation(4)
1431
2
1432
1433
"""
1434
p=self.__modulus.sageInteger.gcd(p)
1435
if p==1:
1436
raise ValueError("Valuation with respect to a unit is not defined.")
1437
r = 0
1438
power = p
1439
while not (self % power): # self % power == 0
1440
r += 1
1441
power *= p
1442
if not power.divides(self.__modulus.sageInteger):
1443
from sage.rings.all import infinity
1444
return infinity
1445
return r
1446
1447
def __floordiv__(self, other):
1448
"""
1449
Exact division for prime moduli, for compatibility with other fields.
1450
1451
EXAMPLES:
1452
sage: GF(7)(3) // GF(7)(5)
1453
2
1454
"""
1455
# needs to be rewritten for coercion
1456
if other.parent() is not self.parent():
1457
other = self.parent().coerce(other)
1458
if self.parent().is_field():
1459
return self / other
1460
else:
1461
raise TypeError, "Floor division not defined for non-prime modulus"
1462
1463
def _repr_(self):
1464
return str(self.lift())
1465
1466
def _latex_(self):
1467
return str(self)
1468
1469
def _integer_(self, ZZ=None):
1470
return self.lift()
1471
1472
def _rational_(self):
1473
return rational.Rational(self.lift())
1474
1475
1476
1477
1478
######################################################################
1479
# class IntegerMod_gmp
1480
######################################################################
1481
1482
1483
cdef class IntegerMod_gmp(IntegerMod_abstract):
1484
"""
1485
Elements of `\ZZ/n\ZZ` for n not small enough
1486
to be operated on in word size.
1487
1488
AUTHORS:
1489
1490
- Robert Bradshaw (2006-08-24)
1491
"""
1492
1493
def __init__(IntegerMod_gmp self, parent, value, empty=False):
1494
"""
1495
EXAMPLES::
1496
1497
sage: a = mod(5,14^20)
1498
sage: type(a)
1499
<type 'sage.rings.finite_rings.integer_mod.IntegerMod_gmp'>
1500
sage: loads(dumps(a)) == a
1501
True
1502
"""
1503
mpz_init(self.value)
1504
IntegerMod_abstract.__init__(self, parent)
1505
if empty:
1506
return
1507
cdef sage.rings.integer.Integer z
1508
if PY_TYPE_CHECK(value, sage.rings.integer.Integer):
1509
z = value
1510
elif PY_TYPE_CHECK(value, rational.Rational):
1511
z = value % self.__modulus.sageInteger
1512
elif PY_TYPE_CHECK(value, int):
1513
self.set_from_long(value)
1514
return
1515
else:
1516
z = sage.rings.integer_ring.Z(value)
1517
self.set_from_mpz(z.value)
1518
1519
cdef IntegerMod_gmp _new_c(self):
1520
cdef IntegerMod_gmp x
1521
x = PY_NEW(IntegerMod_gmp)
1522
mpz_init(x.value)
1523
x.__modulus = self.__modulus
1524
x._parent = self._parent
1525
return x
1526
1527
def __dealloc__(self):
1528
mpz_clear(self.value)
1529
1530
cdef void set_from_mpz(self, mpz_t value):
1531
cdef sage.rings.integer.Integer modulus
1532
modulus = self.__modulus.sageInteger
1533
if mpz_sgn(value) == -1 or mpz_cmp(value, modulus.value) >= 0:
1534
mpz_mod(self.value, value, modulus.value)
1535
else:
1536
mpz_set(self.value, value)
1537
1538
cdef void set_from_long(self, long value):
1539
cdef sage.rings.integer.Integer modulus
1540
mpz_set_si(self.value, value)
1541
if value < 0 or mpz_cmp_si(self.__modulus.sageInteger.value, value) >= 0:
1542
mpz_mod(self.value, self.value, self.__modulus.sageInteger.value)
1543
1544
cdef mpz_t* get_value(IntegerMod_gmp self):
1545
return &self.value
1546
1547
def __lshift__(IntegerMod_gmp self, k):
1548
r"""
1549
Performs a left shift by ``k`` bits.
1550
1551
For details, see :meth:`shift`.
1552
1553
EXAMPLES::
1554
1555
sage: e = Mod(19, 10^10)
1556
sage: e << 102
1557
9443608576
1558
"""
1559
return self.shift(long(k))
1560
1561
def __rshift__(IntegerMod_gmp self, k):
1562
r"""
1563
Performs a right shift by ``k`` bits.
1564
1565
For details, see :meth:`shift`.
1566
1567
EXAMPLES::
1568
1569
sage: e = Mod(19, 10^10)
1570
sage: e >> 1
1571
9
1572
"""
1573
return self.shift(-long(k))
1574
1575
cdef shift(IntegerMod_gmp self, long k):
1576
r"""
1577
Performs a bit-shift specified by ``k`` on ``self``.
1578
1579
Suppose that ``self`` represents an integer `x` modulo `n`. If `k` is
1580
`k = 0`, returns `x`. If `k > 0`, shifts `x` to the left, that is,
1581
multiplies `x` by `2^k` and then returns the representative in the
1582
range `[0,n)`. If `k < 0`, shifts `x` to the right, that is, returns
1583
the integral part of `x` divided by `2^k`.
1584
1585
Note that, in any case, ``self`` remains unchanged.
1586
1587
INPUT:
1588
1589
- ``k`` - Integer of type ``long``
1590
1591
OUTPUT
1592
1593
- Result of type ``IntegerMod_gmp``
1594
1595
EXAMPLES::
1596
1597
sage: e = Mod(19, 10^10)
1598
sage: e << 102
1599
9443608576
1600
sage: e >> 1
1601
9
1602
sage: e >> 4
1603
1
1604
"""
1605
cdef IntegerMod_gmp x
1606
if k == 0:
1607
return self
1608
else:
1609
x = self._new_c()
1610
if k > 0:
1611
mpz_mul_2exp(x.value, self.value, k)
1612
mpz_fdiv_r(x.value, x.value, self.__modulus.sageInteger.value)
1613
else:
1614
mpz_fdiv_q_2exp(x.value, self.value, -k)
1615
return x
1616
1617
cdef int _cmp_c_impl(left, Element right) except -2:
1618
"""
1619
EXAMPLES::
1620
1621
sage: mod(5,13^20) == mod(5,13^20)
1622
True
1623
sage: mod(5,13^20) == mod(-5,13^20)
1624
False
1625
sage: mod(5,13^20) == mod(-5,13)
1626
False
1627
"""
1628
cdef int i
1629
i = mpz_cmp((<IntegerMod_gmp>left).value, (<IntegerMod_gmp>right).value)
1630
if i < 0:
1631
return -1
1632
elif i == 0:
1633
return 0
1634
else:
1635
return 1
1636
1637
def __richcmp__(left, right, int op):
1638
return (<Element>left)._richcmp(right, op)
1639
1640
1641
cpdef bint is_one(IntegerMod_gmp self):
1642
"""
1643
Returns ``True`` if this is `1`, otherwise
1644
``False``.
1645
1646
EXAMPLES::
1647
1648
sage: mod(1,5^23).is_one()
1649
True
1650
sage: mod(0,5^23).is_one()
1651
False
1652
"""
1653
return mpz_cmp_si(self.value, 1) == 0
1654
1655
def __nonzero__(IntegerMod_gmp self):
1656
"""
1657
Returns ``True`` if this is not `0`, otherwise
1658
``False``.
1659
1660
EXAMPLES::
1661
1662
sage: mod(13,5^23).is_zero()
1663
False
1664
sage: (mod(25,5^23)^23).is_zero()
1665
True
1666
"""
1667
return mpz_cmp_si(self.value, 0) != 0
1668
1669
cpdef bint is_unit(self):
1670
"""
1671
Return True iff this element is a unit.
1672
1673
EXAMPLES::
1674
1675
sage: mod(13, 5^23).is_unit()
1676
True
1677
sage: mod(25, 5^23).is_unit()
1678
False
1679
"""
1680
return self.lift().gcd(self.modulus()) == 1
1681
1682
def __crt(IntegerMod_gmp self, IntegerMod_gmp other):
1683
cdef IntegerMod_gmp lift, x
1684
cdef sage.rings.integer.Integer modulus, other_modulus
1685
1686
modulus = self.__modulus.sageInteger
1687
other_modulus = other.__modulus.sageInteger
1688
import integer_mod_ring
1689
lift = IntegerMod_gmp(integer_mod_ring.IntegerModRing(modulus*other_modulus), None, empty=True)
1690
try:
1691
if mpz_cmp(self.value, other.value) > 0:
1692
x = (other - IntegerMod_gmp(other._parent, self.lift())) / IntegerMod_gmp(other._parent, modulus)
1693
mpz_mul(lift.value, x.value, modulus.value)
1694
mpz_add(lift.value, lift.value, self.value)
1695
else:
1696
x = (self - IntegerMod_gmp(self._parent, other.lift())) / IntegerMod_gmp(self._parent, other_modulus)
1697
mpz_mul(lift.value, x.value, other_modulus.value)
1698
mpz_add(lift.value, lift.value, other.value)
1699
return lift
1700
except ZeroDivisionError:
1701
raise ZeroDivisionError, "moduli must be coprime"
1702
1703
1704
def __copy__(IntegerMod_gmp self):
1705
cdef IntegerMod_gmp x
1706
x = self._new_c()
1707
mpz_set(x.value, self.value)
1708
return x
1709
1710
cpdef ModuleElement _add_(self, ModuleElement right):
1711
"""
1712
EXAMPLES::
1713
1714
sage: R = Integers(10^10)
1715
sage: R(7) + R(8)
1716
15
1717
"""
1718
cdef IntegerMod_gmp x
1719
x = self._new_c()
1720
mpz_add(x.value, self.value, (<IntegerMod_gmp>right).value)
1721
if mpz_cmp(x.value, self.__modulus.sageInteger.value) >= 0:
1722
mpz_sub(x.value, x.value, self.__modulus.sageInteger.value)
1723
return x;
1724
1725
cpdef ModuleElement _iadd_(self, ModuleElement right):
1726
"""
1727
EXAMPLES::
1728
1729
sage: R = Integers(10^10)
1730
sage: R(7) + R(8)
1731
15
1732
"""
1733
mpz_add(self.value, self.value, (<IntegerMod_gmp>right).value)
1734
if mpz_cmp(self.value, self.__modulus.sageInteger.value) >= 0:
1735
mpz_sub(self.value, self.value, self.__modulus.sageInteger.value)
1736
return self
1737
1738
cpdef ModuleElement _sub_(self, ModuleElement right):
1739
"""
1740
EXAMPLES::
1741
1742
sage: R = Integers(10^10)
1743
sage: R(7) - R(8)
1744
9999999999
1745
"""
1746
cdef IntegerMod_gmp x
1747
x = self._new_c()
1748
mpz_sub(x.value, self.value, (<IntegerMod_gmp>right).value)
1749
if mpz_sgn(x.value) == -1:
1750
mpz_add(x.value, x.value, self.__modulus.sageInteger.value)
1751
return x;
1752
1753
cpdef ModuleElement _isub_(self, ModuleElement right):
1754
"""
1755
EXAMPLES::
1756
1757
sage: R = Integers(10^10)
1758
sage: R(7) - R(8)
1759
9999999999
1760
"""
1761
mpz_sub(self.value, self.value, (<IntegerMod_gmp>right).value)
1762
if mpz_sgn(self.value) == -1:
1763
mpz_add(self.value, self.value, self.__modulus.sageInteger.value)
1764
return self
1765
1766
cpdef ModuleElement _neg_(self):
1767
"""
1768
EXAMPLES::
1769
1770
sage: -mod(5,10^10)
1771
9999999995
1772
sage: -mod(0,10^10)
1773
0
1774
"""
1775
if mpz_cmp_si(self.value, 0) == 0:
1776
return self
1777
cdef IntegerMod_gmp x
1778
x = self._new_c()
1779
mpz_sub(x.value, self.__modulus.sageInteger.value, self.value)
1780
return x
1781
1782
cpdef RingElement _mul_(self, RingElement right):
1783
"""
1784
EXAMPLES::
1785
1786
sage: R = Integers(10^11)
1787
sage: R(700000) * R(800000)
1788
60000000000
1789
"""
1790
cdef IntegerMod_gmp x
1791
x = self._new_c()
1792
mpz_mul(x.value, self.value, (<IntegerMod_gmp>right).value)
1793
mpz_fdiv_r(x.value, x.value, self.__modulus.sageInteger.value)
1794
return x
1795
1796
cpdef RingElement _imul_(self, RingElement right):
1797
"""
1798
EXAMPLES::
1799
1800
sage: R = Integers(10^11)
1801
sage: R(700000) * R(800000)
1802
60000000000
1803
"""
1804
mpz_mul(self.value, self.value, (<IntegerMod_gmp>right).value)
1805
mpz_fdiv_r(self.value, self.value, self.__modulus.sageInteger.value)
1806
return self
1807
1808
cpdef RingElement _div_(self, RingElement right):
1809
"""
1810
EXAMPLES::
1811
1812
sage: R = Integers(10^11)
1813
sage: R(3) / R(7)
1814
71428571429
1815
"""
1816
return self._mul_(~right)
1817
1818
def __int__(self):
1819
return int(self.lift())
1820
1821
def __index__(self):
1822
"""
1823
Needed so integers modulo `n` can be used as list indices.
1824
1825
EXAMPLES::
1826
1827
sage: v = [1,2,3,4,5]
1828
sage: v[Mod(3,10^20)]
1829
4
1830
"""
1831
return int(self.lift())
1832
1833
def __long__(self):
1834
return long(self.lift())
1835
1836
def __mod__(self, right):
1837
if self.modulus() % right != 0:
1838
raise ZeroDivisionError, "reduction modulo right not defined."
1839
import integer_mod_ring
1840
return IntegerMod(integer_mod_ring.IntegerModRing(right), self)
1841
1842
def __pow__(IntegerMod_gmp self, exp, m): # NOTE: m ignored, always use modulus of parent ring
1843
"""
1844
EXAMPLES:
1845
sage: R = Integers(10^10)
1846
sage: R(2)^1000
1847
5668069376
1848
sage: p = next_prime(11^10)
1849
sage: R = Integers(p)
1850
sage: R(9876)^(p-1)
1851
1
1852
sage: R(0)^0
1853
Traceback (most recent call last):
1854
...
1855
ArithmeticError: 0^0 is undefined.
1856
sage: mod(3, 10^100)^-2
1857
8888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888889
1858
sage: mod(2, 10^100)^-2
1859
Traceback (most recent call last):
1860
...
1861
ZeroDivisionError: Inverse does not exist.
1862
"""
1863
cdef IntegerMod_gmp x = self._new_c()
1864
try:
1865
sig_on()
1866
mpz_pow_helper(x.value, self.value, exp, self.__modulus.sageInteger.value)
1867
return x
1868
finally:
1869
sig_off()
1870
1871
def __invert__(IntegerMod_gmp self):
1872
"""
1873
Return the multiplicative inverse of self.
1874
1875
EXAMPLES::
1876
1877
sage: a = mod(3,10^100); type(a)
1878
<type 'sage.rings.finite_rings.integer_mod.IntegerMod_gmp'>
1879
sage: ~a
1880
6666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666667
1881
sage: ~mod(2,10^100)
1882
Traceback (most recent call last):
1883
...
1884
ZeroDivisionError: Inverse does not exist.
1885
"""
1886
if self.is_zero():
1887
raise ZeroDivisionError, "Inverse does not exist."
1888
1889
cdef IntegerMod_gmp x
1890
x = self._new_c()
1891
if mpz_invert(x.value, self.value, self.__modulus.sageInteger.value):
1892
return x
1893
else:
1894
raise ZeroDivisionError, "Inverse does not exist."
1895
1896
def lift(IntegerMod_gmp self):
1897
"""
1898
Lift an integer modulo `n` to the integers.
1899
1900
EXAMPLES::
1901
1902
sage: a = Mod(8943, 2^70); type(a)
1903
<type 'sage.rings.finite_rings.integer_mod.IntegerMod_gmp'>
1904
sage: lift(a)
1905
8943
1906
sage: a.lift()
1907
8943
1908
"""
1909
cdef sage.rings.integer.Integer z
1910
z = sage.rings.integer.Integer()
1911
z.set_from_mpz(self.value)
1912
return z
1913
1914
def __float__(self):
1915
return float(self.lift())
1916
1917
def __hash__(self):
1918
"""
1919
EXAMPLES::
1920
1921
sage: a = Mod(8943, 2^100)
1922
sage: hash(a)
1923
8943
1924
"""
1925
# return mpz_pythonhash(self.value)
1926
return hash(self.lift())
1927
1928
1929
1930
######################################################################
1931
# class IntegerMod_int
1932
######################################################################
1933
1934
1935
cdef class IntegerMod_int(IntegerMod_abstract):
1936
"""
1937
Elements of `\ZZ/n\ZZ` for n small enough to
1938
be operated on in 32 bits
1939
1940
AUTHORS:
1941
1942
- Robert Bradshaw (2006-08-24)
1943
"""
1944
1945
def __init__(self, parent, value, empty=False):
1946
"""
1947
EXAMPLES::
1948
1949
sage: a = Mod(10,30); a
1950
10
1951
sage: loads(a.dumps()) == a
1952
True
1953
"""
1954
IntegerMod_abstract.__init__(self, parent)
1955
if empty:
1956
return
1957
cdef long x
1958
if PY_TYPE_CHECK(value, int):
1959
x = value
1960
self.ivalue = x % self.__modulus.int32
1961
if self.ivalue < 0:
1962
self.ivalue = self.ivalue + self.__modulus.int32
1963
return
1964
elif PY_TYPE_CHECK(value, IntegerMod_int):
1965
self.ivalue = (<IntegerMod_int>value).ivalue % self.__modulus.int32
1966
return
1967
cdef sage.rings.integer.Integer z
1968
if PY_TYPE_CHECK(value, sage.rings.integer.Integer):
1969
z = value
1970
elif PY_TYPE_CHECK(value, rational.Rational):
1971
z = value % self.__modulus.sageInteger
1972
else:
1973
z = sage.rings.integer_ring.Z(value)
1974
self.set_from_mpz(z.value)
1975
1976
def _make_new_with_parent_c(self, parent): #ParentWithBase parent):
1977
cdef IntegerMod_int x = PY_NEW(IntegerMod_int)
1978
x._parent = parent
1979
x.__modulus = parent._pyx_order
1980
x.ivalue = self.ivalue
1981
return x
1982
1983
cdef IntegerMod_int _new_c(self, int_fast32_t value):
1984
if self.__modulus.table is not None:
1985
return self.__modulus.lookup(value)
1986
cdef IntegerMod_int x = PY_NEW(IntegerMod_int)
1987
x._parent = self._parent
1988
x.__modulus = self.__modulus
1989
x.ivalue = value
1990
return x
1991
1992
cdef void set_from_mpz(self, mpz_t value):
1993
if mpz_sgn(value) == -1 or mpz_cmp_si(value, self.__modulus.int32) >= 0:
1994
self.ivalue = mpz_fdiv_ui(value, self.__modulus.int32)
1995
else:
1996
self.ivalue = mpz_get_si(value)
1997
1998
cdef void set_from_long(self, long value):
1999
self.ivalue = value % self.__modulus.int32
2000
2001
cdef void set_from_int(IntegerMod_int self, int_fast32_t ivalue):
2002
if ivalue < 0:
2003
self.ivalue = self.__modulus.int32 + (ivalue % self.__modulus.int32)
2004
elif ivalue >= self.__modulus.int32:
2005
self.ivalue = ivalue % self.__modulus.int32
2006
else:
2007
self.ivalue = ivalue
2008
2009
cdef int_fast32_t get_int_value(IntegerMod_int self):
2010
return self.ivalue
2011
2012
2013
2014
cdef int _cmp_c_impl(self, Element right) except -2:
2015
"""
2016
EXAMPLES::
2017
2018
sage: mod(5,13) == mod(-8,13)
2019
True
2020
sage: mod(5,13) == mod(8,13)
2021
False
2022
sage: mod(5,13) == mod(5,24)
2023
False
2024
sage: mod(0, 13) == 0
2025
True
2026
sage: mod(0, 13) == int(0)
2027
True
2028
"""
2029
if self.ivalue == (<IntegerMod_int>right).ivalue:
2030
return 0
2031
elif self.ivalue < (<IntegerMod_int>right).ivalue:
2032
return -1
2033
else:
2034
return 1
2035
2036
def __richcmp__(left, right, int op):
2037
return (<Element>left)._richcmp(right, op)
2038
2039
2040
cpdef bint is_one(IntegerMod_int self):
2041
"""
2042
Returns ``True`` if this is `1`, otherwise
2043
``False``.
2044
2045
EXAMPLES::
2046
2047
sage: mod(6,5).is_one()
2048
True
2049
sage: mod(0,5).is_one()
2050
False
2051
"""
2052
return self.ivalue == 1
2053
2054
def __nonzero__(IntegerMod_int self):
2055
"""
2056
Returns ``True`` if this is not `0`, otherwise
2057
``False``.
2058
2059
EXAMPLES::
2060
2061
sage: mod(13,5).is_zero()
2062
False
2063
sage: mod(25,5).is_zero()
2064
True
2065
"""
2066
return self.ivalue != 0
2067
2068
cpdef bint is_unit(IntegerMod_int self):
2069
"""
2070
Return True iff this element is a unit
2071
2072
EXAMPLES::
2073
2074
sage: a=Mod(23,100)
2075
sage: a.is_unit()
2076
True
2077
sage: a=Mod(24,100)
2078
sage: a.is_unit()
2079
False
2080
"""
2081
return gcd_int(self.ivalue, self.__modulus.int32) == 1
2082
2083
def __crt(IntegerMod_int self, IntegerMod_int other):
2084
"""
2085
Use the Chinese Remainder Theorem to find an element of the
2086
integers modulo the product of the moduli that reduces to self and
2087
to other. The modulus of other must be coprime to the modulus of
2088
self.
2089
2090
EXAMPLES::
2091
2092
sage: a = mod(3,5)
2093
sage: b = mod(2,7)
2094
sage: a.crt(b)
2095
23
2096
2097
AUTHORS:
2098
2099
- Robert Bradshaw
2100
"""
2101
cdef IntegerMod_int lift
2102
cdef int_fast32_t x
2103
2104
import integer_mod_ring
2105
lift = IntegerMod_int(integer_mod_ring.IntegerModRing(self.__modulus.int32 * other.__modulus.int32), None, empty=True)
2106
2107
try:
2108
x = (other.ivalue - self.ivalue % other.__modulus.int32) * mod_inverse_int(self.__modulus.int32, other.__modulus.int32)
2109
lift.set_from_int( x * self.__modulus.int32 + self.ivalue )
2110
return lift
2111
except ZeroDivisionError:
2112
raise ZeroDivisionError, "moduli must be coprime"
2113
2114
2115
def __copy__(IntegerMod_int self):
2116
cdef IntegerMod_int x = PY_NEW(IntegerMod_int)
2117
x._parent = self._parent
2118
x.__modulus = self.__modulus
2119
x.ivalue = self.ivalue
2120
return x
2121
2122
cpdef ModuleElement _add_(self, ModuleElement right):
2123
"""
2124
EXAMPLES::
2125
2126
sage: R = Integers(10)
2127
sage: R(7) + R(8)
2128
5
2129
"""
2130
cdef int_fast32_t x
2131
x = self.ivalue + (<IntegerMod_int>right).ivalue
2132
if x >= self.__modulus.int32:
2133
x = x - self.__modulus.int32
2134
return self._new_c(x)
2135
2136
cpdef ModuleElement _iadd_(self, ModuleElement right):
2137
"""
2138
EXAMPLES::
2139
2140
sage: R = Integers(10)
2141
sage: R(7) + R(8)
2142
5
2143
"""
2144
cdef int_fast32_t x
2145
x = self.ivalue + (<IntegerMod_int>right).ivalue
2146
if x >= self.__modulus.int32:
2147
x = x - self.__modulus.int32
2148
self.ivalue = x
2149
return self
2150
2151
cpdef ModuleElement _sub_(self, ModuleElement right):
2152
"""
2153
EXAMPLES::
2154
2155
sage: R = Integers(10)
2156
sage: R(7) - R(8)
2157
9
2158
"""
2159
cdef int_fast32_t x
2160
x = self.ivalue - (<IntegerMod_int>right).ivalue
2161
if x < 0:
2162
x = x + self.__modulus.int32
2163
return self._new_c(x)
2164
2165
cpdef ModuleElement _isub_(self, ModuleElement right):
2166
"""
2167
EXAMPLES::
2168
2169
sage: R = Integers(10)
2170
sage: R(7) - R(8)
2171
9
2172
"""
2173
cdef int_fast32_t x
2174
x = self.ivalue - (<IntegerMod_int>right).ivalue
2175
if x < 0:
2176
x = x + self.__modulus.int32
2177
self.ivalue = x
2178
return self
2179
2180
cpdef ModuleElement _neg_(self):
2181
"""
2182
EXAMPLES::
2183
2184
sage: -mod(7,10)
2185
3
2186
sage: -mod(0,10)
2187
0
2188
"""
2189
if self.ivalue == 0:
2190
return self
2191
return self._new_c(self.__modulus.int32 - self.ivalue)
2192
2193
cpdef RingElement _mul_(self, RingElement right):
2194
"""
2195
EXAMPLES::
2196
2197
sage: R = Integers(10)
2198
sage: R(7) * R(8)
2199
6
2200
"""
2201
return self._new_c((self.ivalue * (<IntegerMod_int>right).ivalue) % self.__modulus.int32)
2202
2203
cpdef RingElement _imul_(self, RingElement right):
2204
"""
2205
EXAMPLES::
2206
2207
sage: R = Integers(10)
2208
sage: R(7) * R(8)
2209
6
2210
"""
2211
self.ivalue = (self.ivalue * (<IntegerMod_int>right).ivalue) % self.__modulus.int32
2212
return self
2213
2214
cpdef RingElement _div_(self, RingElement right):
2215
"""
2216
EXAMPLES::
2217
2218
sage: R = Integers(10)
2219
sage: R(2)/3
2220
4
2221
"""
2222
if self.__modulus.inverses is not None:
2223
right_inverse = self.__modulus.inverses[(<IntegerMod_int>right).ivalue]
2224
if right_inverse is None:
2225
raise ZeroDivisionError, "Inverse does not exist."
2226
else:
2227
return self._new_c((self.ivalue * (<IntegerMod_int>right_inverse).ivalue) % self.__modulus.int32)
2228
2229
cdef int_fast32_t x
2230
x = self.ivalue * mod_inverse_int((<IntegerMod_int>right).ivalue, self.__modulus.int32)
2231
return self._new_c(x% self.__modulus.int32)
2232
2233
def __int__(IntegerMod_int self):
2234
return self.ivalue
2235
2236
def __index__(self):
2237
"""
2238
Needed so integers modulo `n` can be used as list indices.
2239
2240
EXAMPLES::
2241
2242
sage: v = [1,2,3,4,5]
2243
sage: v[Mod(10,7)]
2244
4
2245
"""
2246
return self.ivalue
2247
2248
def __long__(IntegerMod_int self):
2249
return self.ivalue
2250
2251
def __mod__(IntegerMod_int self, right):
2252
right = int(right)
2253
if self.__modulus.int32 % right != 0:
2254
raise ZeroDivisionError, "reduction modulo right not defined."
2255
import integer_mod_ring
2256
return integer_mod_ring.IntegerModRing(right)(self)
2257
2258
def __lshift__(IntegerMod_int self, k):
2259
r"""
2260
Performs a left shift by ``k`` bits.
2261
2262
For details, see :meth:`shift`.
2263
2264
EXAMPLES::
2265
2266
sage: e = Mod(5, 2^10 - 1)
2267
sage: e << 5
2268
160
2269
sage: e * 2^5
2270
160
2271
"""
2272
return self.shift(int(k))
2273
2274
def __rshift__(IntegerMod_int self, k):
2275
r"""
2276
Performs a right shift by ``k`` bits.
2277
2278
For details, see :meth:`shift`.
2279
2280
EXAMPLES::
2281
2282
sage: e = Mod(5, 2^10 - 1)
2283
sage: e << 5
2284
160
2285
sage: e * 2^5
2286
160
2287
"""
2288
return self.shift(-int(k))
2289
2290
cdef shift(IntegerMod_int self, int k):
2291
"""
2292
Performs a bit-shift specified by ``k`` on ``self``.
2293
2294
Suppose that ``self`` represents an integer `x` modulo `n`. If `k` is
2295
`k = 0`, returns `x`. If `k > 0`, shifts `x` to the left, that is,
2296
multiplies `x` by `2^k` and then returns the representative in the
2297
range `[0,n)`. If `k < 0`, shifts `x` to the right, that is, returns
2298
the integral part of `x` divided by `2^k`.
2299
2300
Note that, in any case, ``self`` remains unchanged.
2301
2302
INPUT:
2303
2304
- ``k`` - Integer of type ``int``
2305
2306
OUTPUT:
2307
2308
- Result of type ``IntegerMod_int``
2309
2310
WARNING:
2311
2312
For positive ``k``, if ``x << k`` overflows as a 32-bit integer, the
2313
result is meaningless.
2314
2315
EXAMPLES::
2316
2317
sage: e = Mod(5, 2^10 - 1)
2318
sage: e << 5
2319
160
2320
sage: e * 2^5
2321
160
2322
sage: e = Mod(8, 2^5 - 1)
2323
sage: e >> 3
2324
1
2325
sage: int(e)/int(2^3)
2326
1
2327
"""
2328
if k == 0:
2329
return self
2330
elif k > 0:
2331
return self._new_c((self.ivalue << k) % self.__modulus.int32)
2332
else:
2333
return self._new_c(self.ivalue >> (-k))
2334
2335
def __pow__(IntegerMod_int self, exp, m): # NOTE: m ignored, always use modulus of parent ring
2336
"""
2337
EXAMPLES:
2338
sage: R = Integers(10)
2339
sage: R(2)^10
2340
4
2341
sage: R = Integers(389)
2342
sage: R(7)^388
2343
1
2344
sage: R(0)^0
2345
Traceback (most recent call last):
2346
...
2347
ArithmeticError: 0^0 is undefined.
2348
2349
sage: mod(3, 100)^-1
2350
67
2351
sage: mod(3, 100)^-100000000
2352
1
2353
2354
sage: mod(2, 100)^-1
2355
Traceback (most recent call last):
2356
...
2357
ZeroDivisionError: Inverse does not exist.
2358
sage: mod(2, 100)^-100000000
2359
Traceback (most recent call last):
2360
...
2361
ZeroDivisionError: Inverse does not exist.
2362
"""
2363
cdef long long_exp
2364
cdef int_fast32_t res
2365
cdef mpz_t res_mpz
2366
if PyInt_CheckExact(exp) and -100000 < PyInt_AS_LONG(exp) < 100000:
2367
long_exp = PyInt_AS_LONG(exp)
2368
elif PY_TYPE_CHECK_EXACT(exp, Integer) and mpz_cmpabs_ui((<Integer>exp).value, 100000) == -1:
2369
long_exp = mpz_get_si((<Integer>exp).value)
2370
else:
2371
try:
2372
sig_on()
2373
mpz_init(res_mpz)
2374
base = self.lift()
2375
mpz_pow_helper(res_mpz, (<Integer>base).value, exp, self.__modulus.sageInteger.value)
2376
return self._new_c(mpz_get_ui(res_mpz))
2377
finally:
2378
mpz_clear(res_mpz)
2379
sig_off()
2380
2381
if long_exp == 0 and self.ivalue == 0:
2382
raise ArithmeticError, "0^0 is undefined."
2383
cdef bint invert = False
2384
if long_exp < 0:
2385
invert = True
2386
long_exp = -long_exp
2387
res = mod_pow_int(self.ivalue, long_exp, self.__modulus.int32)
2388
if invert:
2389
return ~self._new_c(res)
2390
else:
2391
return self._new_c(res)
2392
2393
def __invert__(IntegerMod_int self):
2394
"""
2395
Return the multiplicative inverse of self.
2396
2397
EXAMPLES::
2398
2399
sage: ~mod(7,100)
2400
43
2401
"""
2402
if self.__modulus.inverses is not None:
2403
x = self.__modulus.inverses[self.ivalue]
2404
if x is None:
2405
raise ZeroDivisionError, "Inverse does not exist."
2406
else:
2407
return x
2408
else:
2409
return self._new_c(mod_inverse_int(self.ivalue, self.__modulus.int32))
2410
2411
def lift(IntegerMod_int self):
2412
"""
2413
Lift an integer modulo `n` to the integers.
2414
2415
EXAMPLES::
2416
2417
sage: a = Mod(8943, 2^10); type(a)
2418
<type 'sage.rings.finite_rings.integer_mod.IntegerMod_int'>
2419
sage: lift(a)
2420
751
2421
sage: a.lift()
2422
751
2423
"""
2424
cdef sage.rings.integer.Integer z
2425
z = sage.rings.integer.Integer()
2426
mpz_set_si(z.value, self.ivalue)
2427
return z
2428
2429
def __float__(IntegerMod_int self):
2430
return <double>self.ivalue
2431
2432
def __hash__(self):
2433
"""
2434
EXAMPLES::
2435
2436
sage: a = Mod(89, 2^10)
2437
sage: hash(a)
2438
89
2439
"""
2440
return hash(self.ivalue)
2441
2442
cdef bint is_square_c(self) except -2:
2443
if self.ivalue <= 1:
2444
return 1
2445
moduli = self._parent.factored_order()
2446
cdef int val, e
2447
cdef int_fast32_t p
2448
if len(moduli) == 1:
2449
sage_p, e = moduli[0]
2450
p = sage_p
2451
if e == 1:
2452
return jacobi_int(self.ivalue, p) != -1
2453
elif p == 2:
2454
return self.pari().issquare() # TODO: implement directly
2455
elif self.ivalue % p == 0:
2456
val = self.lift().valuation(sage_p)
2457
return val >= e or (val % 2 == 0 and jacobi_int(self.ivalue / int(sage_p**val), p) != -1)
2458
else:
2459
return jacobi_int(self.ivalue, p) != -1
2460
else:
2461
for sage_p, e in moduli:
2462
p = sage_p
2463
if p == 2:
2464
if e > 1 and not self.pari().issquare(): # TODO: implement directly
2465
return 0
2466
elif e > 1 and self.ivalue % p == 0:
2467
val = self.lift().valuation(sage_p)
2468
if val < e and (val % 2 == 1 or jacobi_int(self.ivalue / int(sage_p**val), p) == -1):
2469
return 0
2470
elif jacobi_int(self.ivalue, p) == -1:
2471
return 0
2472
return 1
2473
2474
def sqrt(self, extend=True, all=False):
2475
r"""
2476
Returns square root or square roots of ``self`` modulo
2477
`n`.
2478
2479
INPUT:
2480
2481
2482
- ``extend`` - bool (default: ``True``);
2483
if ``True``, return a square root in an extension ring,
2484
if necessary. Otherwise, raise a ``ValueError`` if the
2485
square root is not in the base ring.
2486
2487
- ``all`` - bool (default: ``False``); if
2488
``True``, return {all} square roots of self, instead of
2489
just one.
2490
2491
2492
ALGORITHM: Calculates the square roots mod `p` for each of
2493
the primes `p` dividing the order of the ring, then lifts
2494
them `p`-adically and uses the CRT to find a square root
2495
mod `n`.
2496
2497
See also ``square_root_mod_prime_power`` and
2498
``square_root_mod_prime`` (in this module) for more
2499
algorithmic details.
2500
2501
EXAMPLES::
2502
2503
sage: mod(-1, 17).sqrt()
2504
4
2505
sage: mod(5, 389).sqrt()
2506
86
2507
sage: mod(7, 18).sqrt()
2508
5
2509
sage: a = mod(14, 5^60).sqrt()
2510
sage: a*a
2511
14
2512
sage: mod(15, 389).sqrt(extend=False)
2513
Traceback (most recent call last):
2514
...
2515
ValueError: self must be a square
2516
sage: Mod(1/9, next_prime(2^40)).sqrt()^(-2)
2517
9
2518
sage: Mod(1/25, next_prime(2^90)).sqrt()^(-2)
2519
25
2520
2521
::
2522
2523
sage: a = Mod(3,5); a
2524
3
2525
sage: x = Mod(-1, 360)
2526
sage: x.sqrt(extend=False)
2527
Traceback (most recent call last):
2528
...
2529
ValueError: self must be a square
2530
sage: y = x.sqrt(); y
2531
sqrt359
2532
sage: y.parent()
2533
Univariate Quotient Polynomial Ring in sqrt359 over Ring of integers modulo 360 with modulus x^2 + 1
2534
sage: y^2
2535
359
2536
2537
We compute all square roots in several cases::
2538
2539
sage: R = Integers(5*2^3*3^2); R
2540
Ring of integers modulo 360
2541
sage: R(40).sqrt(all=True)
2542
[20, 160, 200, 340]
2543
sage: [x for x in R if x^2 == 40] # Brute force verification
2544
[20, 160, 200, 340]
2545
sage: R(1).sqrt(all=True)
2546
[1, 19, 71, 89, 91, 109, 161, 179, 181, 199, 251, 269, 271, 289, 341, 359]
2547
sage: R(0).sqrt(all=True)
2548
[0, 60, 120, 180, 240, 300]
2549
sage: GF(107)(0).sqrt(all=True)
2550
[0]
2551
2552
::
2553
2554
sage: R = Integers(5*13^3*37); R
2555
Ring of integers modulo 406445
2556
sage: v = R(-1).sqrt(all=True); v
2557
[78853, 111808, 160142, 193097, 213348, 246303, 294637, 327592]
2558
sage: [x^2 for x in v]
2559
[406444, 406444, 406444, 406444, 406444, 406444, 406444, 406444]
2560
sage: v = R(169).sqrt(all=True); min(v), -max(v), len(v)
2561
(13, 13, 104)
2562
sage: all([x^2==169 for x in v])
2563
True
2564
2565
Modulo a power of 2::
2566
2567
sage: R = Integers(2^7); R
2568
Ring of integers modulo 128
2569
sage: a = R(17)
2570
sage: a.sqrt()
2571
23
2572
sage: a.sqrt(all=True)
2573
[23, 41, 87, 105]
2574
sage: [x for x in R if x^2==17]
2575
[23, 41, 87, 105]
2576
"""
2577
cdef int_fast32_t i, n = self.__modulus.int32
2578
if n > 100:
2579
moduli = self._parent.factored_order()
2580
# Unless the modulus is tiny, test to see if we're in the really
2581
# easy case of n prime, n = 3 mod 4.
2582
if n > 100 and n % 4 == 3 and len(moduli) == 1 and moduli[0][1] == 1:
2583
if jacobi_int(self.ivalue, self.__modulus.int32) == 1:
2584
# it's a non-zero square, sqrt(a) = a^(p+1)/4
2585
i = mod_pow_int(self.ivalue, (self.__modulus.int32+1)/4, n)
2586
if i > n/2:
2587
i = n-i
2588
if all:
2589
return [self._new_c(i), self._new_c(n-i)]
2590
else:
2591
return self._new_c(i)
2592
elif self.ivalue == 0:
2593
return [self] if all else self
2594
elif not extend:
2595
raise ValueError, "self must be a square"
2596
# Now we use a heuristic to guess whether or not it will
2597
# be faster to just brute-force search for squares in a c loop...
2598
# TODO: more tuning?
2599
elif n <= 100 or n / (1 << len(moduli)) < 5000:
2600
if all:
2601
return [self._new_c(i) for i from 0 <= i < n if (i*i) % n == self.ivalue]
2602
else:
2603
for i from 0 <= i <= n/2:
2604
if (i*i) % n == self.ivalue:
2605
return self._new_c(i)
2606
if not extend:
2607
raise ValueError, "self must be a square"
2608
# Either it failed but extend was True, or the generic algorithm is better
2609
return IntegerMod_abstract.sqrt(self, extend=extend, all=all)
2610
2611
2612
def _balanced_abs(self):
2613
"""
2614
This function returns `x` or `-x`, whichever has a
2615
positive representative in `-n/2 < x \leq n/2`.
2616
"""
2617
if self.ivalue > self.__modulus.int32 / 2:
2618
return -self
2619
else:
2620
return self
2621
2622
2623
2624
### End of class
2625
2626
2627
cdef int_fast32_t gcd_int(int_fast32_t a, int_fast32_t b):
2628
"""
2629
Returns the gcd of a and b
2630
2631
For use with IntegerMod_int
2632
2633
AUTHORS:
2634
2635
- Robert Bradshaw
2636
"""
2637
cdef int_fast32_t tmp
2638
if a < b:
2639
tmp = b
2640
b = a
2641
a = tmp
2642
while b:
2643
tmp = b
2644
b = a % b
2645
a = tmp
2646
return a
2647
2648
2649
cdef int_fast32_t mod_inverse_int(int_fast32_t x, int_fast32_t n) except 0:
2650
"""
2651
Returns y such that xy=1 mod n
2652
2653
For use in IntegerMod_int
2654
2655
AUTHORS:
2656
2657
- Robert Bradshaw
2658
"""
2659
cdef int_fast32_t tmp, a, b, last_t, t, next_t, q
2660
a = n
2661
b = x
2662
t = 0
2663
next_t = 1
2664
while b:
2665
# a = s * n + t * x
2666
if b == 1:
2667
next_t = next_t % n
2668
if next_t < 0:
2669
next_t = next_t + n
2670
return next_t
2671
q = a / b
2672
tmp = b
2673
b = a % b
2674
a = tmp
2675
last_t = t
2676
t = next_t
2677
next_t = last_t - q * t
2678
raise ZeroDivisionError, "Inverse does not exist."
2679
2680
2681
cdef int_fast32_t mod_pow_int(int_fast32_t base, int_fast32_t exp, int_fast32_t n):
2682
"""
2683
Returns base^exp mod n
2684
2685
For use in IntegerMod_int
2686
2687
EXAMPLES::
2688
2689
sage: z = Mod(2, 256)
2690
sage: z^8
2691
0
2692
2693
AUTHORS:
2694
2695
- Robert Bradshaw
2696
"""
2697
cdef int_fast32_t prod, pow2
2698
if exp <= 5:
2699
if exp == 0: return 1
2700
if exp == 1: return base
2701
prod = base * base % n
2702
if exp == 2: return prod
2703
if exp == 3: return (prod * base) % n
2704
if exp == 4: return (prod * prod) % n
2705
2706
pow2 = base
2707
if exp % 2: prod = base
2708
else: prod = 1
2709
exp = exp >> 1
2710
while(exp != 0):
2711
pow2 = pow2 * pow2
2712
if pow2 >= INTEGER_MOD_INT32_LIMIT: pow2 = pow2 % n
2713
if exp % 2:
2714
prod = prod * pow2
2715
if prod >= INTEGER_MOD_INT32_LIMIT: prod = prod % n
2716
exp = exp >> 1
2717
2718
if prod >= n:
2719
prod = prod % n
2720
return prod
2721
2722
2723
cdef int jacobi_int(int_fast32_t a, int_fast32_t m) except -2:
2724
"""
2725
Calculates the jacobi symbol (a/n)
2726
2727
For use in IntegerMod_int
2728
2729
AUTHORS:
2730
2731
- Robert Bradshaw
2732
"""
2733
cdef int s, jacobi = 1
2734
cdef int_fast32_t b
2735
2736
a = a % m
2737
2738
while 1:
2739
if a == 0:
2740
return 0 # gcd was nontrivial
2741
elif a == 1:
2742
return jacobi
2743
s = 0
2744
while (1 << s) & a == 0:
2745
s += 1
2746
b = a >> s
2747
# Now a = 2^s * b
2748
2749
# factor out (2/m)^s term
2750
if s % 2 == 1 and (m % 8 == 3 or m % 8 == 5):
2751
jacobi = -jacobi
2752
2753
if b == 1:
2754
return jacobi
2755
2756
# quadratic reciprocity
2757
if b % 4 == 3 and m % 4 == 3:
2758
jacobi = -jacobi
2759
a = m % b
2760
m = b
2761
#
2762
# These two functions are never used:
2763
#
2764
#def test_gcd(a, b):
2765
# return gcd_int(int(a), int(b))
2766
#
2767
#def test_mod_inverse(a, b):
2768
# return mod_inverse_int(int(a), int(b))
2769
#
2770
2771
2772
######################################################################
2773
# class IntegerMod_int64
2774
######################################################################
2775
2776
cdef class IntegerMod_int64(IntegerMod_abstract):
2777
"""
2778
Elements of `\ZZ/n\ZZ` for n small enough to
2779
be operated on in 64 bits
2780
2781
AUTHORS:
2782
2783
- Robert Bradshaw (2006-09-14)
2784
"""
2785
2786
def __init__(self, parent, value, empty=False):
2787
"""
2788
EXAMPLES::
2789
2790
sage: a = Mod(10,3^10); a
2791
10
2792
sage: type(a)
2793
<type 'sage.rings.finite_rings.integer_mod.IntegerMod_int64'>
2794
sage: loads(a.dumps()) == a
2795
True
2796
sage: Mod(5, 2^31)
2797
5
2798
"""
2799
IntegerMod_abstract.__init__(self, parent)
2800
if empty:
2801
return
2802
cdef int_fast64_t x
2803
if PY_TYPE_CHECK(value, int):
2804
x = value
2805
self.ivalue = x % self.__modulus.int64
2806
if self.ivalue < 0:
2807
self.ivalue = self.ivalue + self.__modulus.int64
2808
return
2809
cdef sage.rings.integer.Integer z
2810
if PY_TYPE_CHECK(value, sage.rings.integer.Integer):
2811
z = value
2812
elif PY_TYPE_CHECK(value, rational.Rational):
2813
z = value % self.__modulus.sageInteger
2814
else:
2815
z = sage.rings.integer_ring.Z(value)
2816
self.set_from_mpz(z.value)
2817
2818
cdef IntegerMod_int64 _new_c(self, int_fast64_t value):
2819
cdef IntegerMod_int64 x
2820
x = PY_NEW(IntegerMod_int64)
2821
x.__modulus = self.__modulus
2822
x._parent = self._parent
2823
x.ivalue = value
2824
return x
2825
2826
cdef void set_from_mpz(self, mpz_t value):
2827
if mpz_sgn(value) == -1 or mpz_cmp_si(value, self.__modulus.int64) >= 0:
2828
self.ivalue = mpz_fdiv_ui(value, self.__modulus.int64)
2829
else:
2830
self.ivalue = mpz_get_si(value)
2831
2832
cdef void set_from_long(self, long value):
2833
self.ivalue = value % self.__modulus.int64
2834
2835
cdef void set_from_int(IntegerMod_int64 self, int_fast64_t ivalue):
2836
if ivalue < 0:
2837
self.ivalue = self.__modulus.int64 + (ivalue % self.__modulus.int64) # Is ivalue % self.__modulus.int64 actually negative?
2838
elif ivalue >= self.__modulus.int64:
2839
self.ivalue = ivalue % self.__modulus.int64
2840
else:
2841
self.ivalue = ivalue
2842
2843
cdef int_fast64_t get_int_value(IntegerMod_int64 self):
2844
return self.ivalue
2845
2846
2847
cdef int _cmp_c_impl(self, Element right) except -2:
2848
"""
2849
EXAMPLES::
2850
2851
sage: mod(5,13^5) == mod(13^5+5,13^5)
2852
True
2853
sage: mod(5,13^5) == mod(8,13^5)
2854
False
2855
sage: mod(5,13^5) == mod(5,13)
2856
True
2857
sage: mod(0, 13^5) == 0
2858
True
2859
sage: mod(0, 13^5) == int(0)
2860
True
2861
"""
2862
if self.ivalue == (<IntegerMod_int64>right).ivalue: return 0
2863
elif self.ivalue < (<IntegerMod_int64>right).ivalue: return -1
2864
else: return 1
2865
2866
def __richcmp__(left, right, int op):
2867
return (<Element>left)._richcmp(right, op)
2868
2869
2870
cpdef bint is_one(IntegerMod_int64 self):
2871
"""
2872
Returns ``True`` if this is `1`, otherwise
2873
``False``.
2874
2875
EXAMPLES::
2876
2877
sage: (mod(-1,5^10)^2).is_one()
2878
True
2879
sage: mod(0,5^10).is_one()
2880
False
2881
"""
2882
return self.ivalue == 1
2883
2884
def __nonzero__(IntegerMod_int64 self):
2885
"""
2886
Returns ``True`` if this is not `0`, otherwise
2887
``False``.
2888
2889
EXAMPLES::
2890
2891
sage: mod(13,5^10).is_zero()
2892
False
2893
sage: mod(5^12,5^10).is_zero()
2894
True
2895
"""
2896
return self.ivalue != 0
2897
2898
cpdef bint is_unit(IntegerMod_int64 self):
2899
"""
2900
Return True iff this element is a unit.
2901
2902
EXAMPLES::
2903
2904
sage: mod(13, 5^10).is_unit()
2905
True
2906
sage: mod(25, 5^10).is_unit()
2907
False
2908
"""
2909
return gcd_int64(self.ivalue, self.__modulus.int64) == 1
2910
2911
def __crt(IntegerMod_int64 self, IntegerMod_int64 other):
2912
"""
2913
Use the Chinese Remainder Theorem to find an element of the
2914
integers modulo the product of the moduli that reduces to self and
2915
to other. The modulus of other must be coprime to the modulus of
2916
self.
2917
2918
EXAMPLES::
2919
2920
sage: a = mod(3,5^10)
2921
sage: b = mod(2,7)
2922
sage: a.crt(b)
2923
29296878
2924
sage: type(a.crt(b)) == type(b.crt(a)) and type(a.crt(b)) == type(mod(1, 7 * 5^10))
2925
True
2926
2927
::
2928
2929
sage: a = mod(3,10^10)
2930
sage: b = mod(2,9)
2931
sage: a.crt(b)
2932
80000000003
2933
sage: type(a.crt(b)) == type(b.crt(a)) and type(a.crt(b)) == type(mod(1, 9 * 10^10))
2934
True
2935
2936
AUTHORS:
2937
2938
- Robert Bradshaw
2939
"""
2940
cdef IntegerMod_int64 lift
2941
cdef int_fast64_t x
2942
2943
import integer_mod_ring
2944
lift = IntegerMod_int64(integer_mod_ring.IntegerModRing(self.__modulus.int64 * other.__modulus.int64), None, empty=True)
2945
2946
try:
2947
x = (other.ivalue - self.ivalue % other.__modulus.int64) * mod_inverse_int64(self.__modulus.int64, other.__modulus.int64)
2948
lift.set_from_int( x * self.__modulus.int64 + self.ivalue )
2949
return lift
2950
except ZeroDivisionError:
2951
raise ZeroDivisionError, "moduli must be coprime"
2952
2953
def __copy__(IntegerMod_int64 self):
2954
return self._new_c(self.ivalue)
2955
2956
cpdef ModuleElement _add_(self, ModuleElement right):
2957
"""
2958
EXAMPLES::
2959
2960
sage: R = Integers(10^5)
2961
sage: R(7) + R(8)
2962
15
2963
"""
2964
cdef int_fast64_t x
2965
x = self.ivalue + (<IntegerMod_int64>right).ivalue
2966
if x >= self.__modulus.int64:
2967
x = x - self.__modulus.int64
2968
return self._new_c(x)
2969
2970
cpdef ModuleElement _iadd_(self, ModuleElement right):
2971
"""
2972
EXAMPLES::
2973
2974
sage: R = Integers(10^5)
2975
sage: R(7) + R(8)
2976
15
2977
"""
2978
cdef int_fast64_t x
2979
x = self.ivalue + (<IntegerMod_int64>right).ivalue
2980
if x >= self.__modulus.int64:
2981
x = x - self.__modulus.int64
2982
self.ivalue = x
2983
return self
2984
2985
cpdef ModuleElement _sub_(self, ModuleElement right):
2986
"""
2987
EXAMPLES::
2988
2989
sage: R = Integers(10^5)
2990
sage: R(7) - R(8)
2991
99999
2992
"""
2993
cdef int_fast64_t x
2994
x = self.ivalue - (<IntegerMod_int64>right).ivalue
2995
if x < 0:
2996
x = x + self.__modulus.int64
2997
return self._new_c(x)
2998
2999
cpdef ModuleElement _isub_(self, ModuleElement right):
3000
"""
3001
EXAMPLES::
3002
3003
sage: R = Integers(10^5)
3004
sage: R(7) - R(8)
3005
99999
3006
"""
3007
cdef int_fast64_t x
3008
x = self.ivalue - (<IntegerMod_int64>right).ivalue
3009
if x < 0:
3010
x = x + self.__modulus.int64
3011
self.ivalue = x
3012
return self
3013
3014
cpdef ModuleElement _neg_(self):
3015
"""
3016
EXAMPLES::
3017
3018
sage: -mod(7,10^5)
3019
99993
3020
sage: -mod(0,10^6)
3021
0
3022
"""
3023
if self.ivalue == 0:
3024
return self
3025
return self._new_c(self.__modulus.int64 - self.ivalue)
3026
3027
cpdef RingElement _mul_(self, RingElement right):
3028
"""
3029
EXAMPLES::
3030
3031
sage: R = Integers(10^5)
3032
sage: R(700) * R(800)
3033
60000
3034
"""
3035
return self._new_c((self.ivalue * (<IntegerMod_int64>right).ivalue) % self.__modulus.int64)
3036
3037
3038
cpdef RingElement _imul_(self, RingElement right):
3039
"""
3040
EXAMPLES::
3041
3042
sage: R = Integers(10^5)
3043
sage: R(700) * R(800)
3044
60000
3045
"""
3046
self.ivalue = (self.ivalue * (<IntegerMod_int64>right).ivalue) % self.__modulus.int64
3047
return self
3048
3049
cpdef RingElement _div_(self, RingElement right):
3050
"""
3051
EXAMPLES::
3052
3053
sage: R = Integers(10^5)
3054
sage: R(2)/3
3055
33334
3056
"""
3057
return self._new_c((self.ivalue * mod_inverse_int64((<IntegerMod_int64>right).ivalue,
3058
self.__modulus.int64) ) % self.__modulus.int64)
3059
3060
def __int__(IntegerMod_int64 self):
3061
return self.ivalue
3062
3063
def __index__(self):
3064
"""
3065
Needed so integers modulo `n` can be used as list indices.
3066
3067
EXAMPLES::
3068
3069
sage: v = [1,2,3,4,5]
3070
sage: v[Mod(3, 2^20)]
3071
4
3072
"""
3073
return self.ivalue
3074
3075
def __long__(IntegerMod_int64 self):
3076
return self.ivalue
3077
3078
def __mod__(IntegerMod_int64 self, right):
3079
right = int(right)
3080
if self.__modulus.int64 % right != 0:
3081
raise ZeroDivisionError, "reduction modulo right not defined."
3082
import integer_mod_ring
3083
return integer_mod_ring.IntegerModRing(right)(self)
3084
3085
def __lshift__(IntegerMod_int64 self, k):
3086
r"""
3087
Performs a left shift by ``k`` bits.
3088
3089
For details, see :meth:`shift`.
3090
3091
EXAMPLES::
3092
3093
sage: e = Mod(5, 2^31 - 1)
3094
sage: e << 32
3095
10
3096
sage: e * 2^32
3097
10
3098
"""
3099
return self.shift(int(k))
3100
3101
def __rshift__(IntegerMod_int64 self, k):
3102
r"""
3103
Performs a right shift by ``k`` bits.
3104
3105
For details, see :meth:`shift`.
3106
3107
EXAMPLES::
3108
3109
sage: e = Mod(5, 2^31 - 1)
3110
sage: e >> 1
3111
2
3112
"""
3113
return self.shift(-int(k))
3114
3115
cdef shift(IntegerMod_int64 self, int k):
3116
"""
3117
Performs a bit-shift specified by ``k`` on ``self``.
3118
3119
Suppose that ``self`` represents an integer `x` modulo `n`. If `k` is
3120
`k = 0`, returns `x`. If `k > 0`, shifts `x` to the left, that is,
3121
multiplies `x` by `2^k` and then returns the representative in the
3122
range `[0,n)`. If `k < 0`, shifts `x` to the right, that is, returns
3123
the integral part of `x` divided by `2^k`.
3124
3125
Note that, in any case, ``self`` remains unchanged.
3126
3127
INPUT:
3128
3129
- ``k`` - Integer of type ``int``
3130
3131
OUTPUT:
3132
3133
- Result of type ``IntegerMod_int64``
3134
3135
WARNING:
3136
3137
For positive ``k``, if ``x << k`` overflows as a 64-bit integer, the
3138
result is meaningless.
3139
3140
EXAMPLES::
3141
3142
sage: e = Mod(5, 2^31 - 1)
3143
sage: e << 32
3144
10
3145
sage: e * 2^32
3146
10
3147
sage: e = Mod(5, 2^31 - 1)
3148
sage: e >> 1
3149
2
3150
"""
3151
if k == 0:
3152
return self
3153
elif k > 0:
3154
return self._new_c((self.ivalue << k) % self.__modulus.int64)
3155
else:
3156
return self._new_c(self.ivalue >> (-k))
3157
3158
def __pow__(IntegerMod_int64 self, exp, m): # NOTE: m ignored, always use modulus of parent ring
3159
"""
3160
EXAMPLES:
3161
sage: R = Integers(10)
3162
sage: R(2)^10
3163
4
3164
sage: p = next_prime(10^5)
3165
sage: R = Integers(p)
3166
sage: R(1234)^(p-1)
3167
1
3168
sage: R(0)^0
3169
Traceback (most recent call last):
3170
...
3171
ArithmeticError: 0^0 is undefined.
3172
sage: R = Integers(17^5)
3173
sage: R(17)^5
3174
0
3175
3176
sage: R(2)^-1 * 2
3177
1
3178
sage: R(2)^-1000000 * 2^1000000
3179
1
3180
sage: R(17)^-1
3181
Traceback (most recent call last):
3182
...
3183
ZeroDivisionError: Inverse does not exist.
3184
sage: R(17)^-100000000
3185
Traceback (most recent call last):
3186
...
3187
ZeroDivisionError: Inverse does not exist.
3188
3189
TESTS::
3190
3191
sage: type(R(0))
3192
<type 'sage.rings.finite_rings.integer_mod.IntegerMod_int64'>
3193
"""
3194
cdef long long_exp
3195
cdef int_fast64_t res
3196
cdef mpz_t res_mpz
3197
if PyInt_CheckExact(exp) and -100000 < PyInt_AS_LONG(exp) < 100000:
3198
long_exp = PyInt_AS_LONG(exp)
3199
elif PY_TYPE_CHECK_EXACT(exp, Integer) and mpz_cmpabs_ui((<Integer>exp).value, 100000) == -1:
3200
long_exp = mpz_get_si((<Integer>exp).value)
3201
else:
3202
try:
3203
sig_on()
3204
mpz_init(res_mpz)
3205
base = self.lift()
3206
mpz_pow_helper(res_mpz, (<Integer>base).value, exp, self.__modulus.sageInteger.value)
3207
if mpz_fits_ulong_p(res_mpz):
3208
res = mpz_get_ui(res_mpz)
3209
else:
3210
res = mpz_get_pyintlong(res_mpz)
3211
return self._new_c(res)
3212
finally:
3213
mpz_clear(res_mpz)
3214
sig_off()
3215
3216
if long_exp == 0 and self.ivalue == 0:
3217
raise ArithmeticError, "0^0 is undefined."
3218
cdef bint invert = False
3219
if long_exp < 0:
3220
invert = True
3221
long_exp = -long_exp
3222
res = mod_pow_int64(self.ivalue, long_exp, self.__modulus.int64)
3223
if invert:
3224
return self._new_c(mod_inverse_int64(res, self.__modulus.int64))
3225
else:
3226
return self._new_c(res)
3227
3228
def __invert__(IntegerMod_int64 self):
3229
"""
3230
Return the multiplicative inverse of self.
3231
3232
EXAMPLES::
3233
3234
sage: a = mod(7,2^40); type(a)
3235
<type 'sage.rings.finite_rings.integer_mod.IntegerMod_gmp'>
3236
sage: ~a
3237
471219269047
3238
sage: a
3239
7
3240
"""
3241
return self._new_c(mod_inverse_int64(self.ivalue, self.__modulus.int64))
3242
3243
def lift(IntegerMod_int64 self):
3244
"""
3245
Lift an integer modulo `n` to the integers.
3246
3247
EXAMPLES::
3248
3249
sage: a = Mod(8943, 2^25); type(a)
3250
<type 'sage.rings.finite_rings.integer_mod.IntegerMod_int64'>
3251
sage: lift(a)
3252
8943
3253
sage: a.lift()
3254
8943
3255
"""
3256
cdef sage.rings.integer.Integer z
3257
z = sage.rings.integer.Integer()
3258
mpz_set_si(z.value, self.ivalue)
3259
return z
3260
3261
def __float__(IntegerMod_int64 self):
3262
"""
3263
Coerce self to a float.
3264
3265
EXAMPLES::
3266
3267
sage: a = Mod(8943, 2^35)
3268
sage: float(a)
3269
8943.0
3270
"""
3271
return <double>self.ivalue
3272
3273
def __hash__(self):
3274
"""
3275
Compute hash of self.
3276
3277
EXAMPLES::
3278
3279
sage: a = Mod(8943, 2^35)
3280
sage: hash(a)
3281
8943
3282
"""
3283
3284
return hash(self.ivalue)
3285
3286
def _balanced_abs(self):
3287
"""
3288
This function returns `x` or `-x`, whichever has a
3289
positive representative in `-n/2 < x \leq n/2`.
3290
"""
3291
if self.ivalue > self.__modulus.int64 / 2:
3292
return -self
3293
else:
3294
return self
3295
3296
3297
### Helper functions
3298
3299
cdef mpz_pow_helper(mpz_t res, mpz_t base, object exp, mpz_t modulus):
3300
cdef bint invert = False
3301
cdef long long_exp
3302
if mpz_sgn(base) == 0 and not exp:
3303
raise ArithmeticError, "0^0 is undefined."
3304
if PyInt_CheckExact(exp):
3305
long_exp = PyInt_AS_LONG(exp)
3306
if long_exp < 0:
3307
long_exp = -long_exp
3308
invert = True
3309
mpz_powm_ui(res, base, long_exp, modulus)
3310
else:
3311
if not PY_TYPE_CHECK_EXACT(exp, Integer):
3312
exp = Integer(exp)
3313
if mpz_sgn((<Integer>exp).value) < 0:
3314
exp = -exp
3315
invert = True
3316
mpz_powm(res, base, (<Integer>exp).value, modulus)
3317
if invert:
3318
if not mpz_invert(res, res, modulus):
3319
raise ZeroDivisionError, "Inverse does not exist."
3320
3321
cdef int_fast64_t gcd_int64(int_fast64_t a, int_fast64_t b):
3322
"""
3323
Returns the gcd of a and b
3324
3325
For use with IntegerMod_int64
3326
3327
AUTHORS:
3328
3329
- Robert Bradshaw
3330
"""
3331
cdef int_fast64_t tmp
3332
if a < b:
3333
tmp = b
3334
b = a
3335
a = tmp
3336
while b:
3337
tmp = b
3338
b = a % b
3339
a = tmp
3340
return a
3341
3342
3343
cdef int_fast64_t mod_inverse_int64(int_fast64_t x, int_fast64_t n) except 0:
3344
"""
3345
Returns y such that xy=1 mod n
3346
3347
For use in IntegerMod_int64
3348
3349
AUTHORS:
3350
3351
- Robert Bradshaw
3352
"""
3353
cdef int_fast64_t tmp, a, b, last_t, t, next_t, q
3354
a = n
3355
b = x
3356
t = 0
3357
next_t = 1
3358
while b:
3359
# a = s * n + t * x
3360
if b == 1:
3361
next_t = next_t % n
3362
if next_t < 0:
3363
next_t = next_t + n
3364
return next_t
3365
q = a / b
3366
tmp = b
3367
b = a % b
3368
a = tmp
3369
last_t = t
3370
t = next_t
3371
next_t = last_t - q * t
3372
raise ZeroDivisionError, "Inverse does not exist."
3373
3374
3375
cdef int_fast64_t mod_pow_int64(int_fast64_t base, int_fast64_t exp, int_fast64_t n):
3376
"""
3377
Returns base^exp mod n
3378
3379
For use in IntegerMod_int64
3380
3381
AUTHORS:
3382
3383
- Robert Bradshaw
3384
"""
3385
cdef int_fast64_t prod, pow2
3386
if exp <= 5:
3387
if exp == 0: return 1
3388
if exp == 1: return base
3389
prod = base * base % n
3390
if exp == 2: return prod
3391
if exp == 3: return (prod * base) % n
3392
if exp == 4: return (prod * prod) % n
3393
3394
pow2 = base
3395
if exp % 2: prod = base
3396
else: prod = 1
3397
exp = exp >> 1
3398
while(exp != 0):
3399
pow2 = pow2 * pow2
3400
if pow2 >= INTEGER_MOD_INT64_LIMIT: pow2 = pow2 % n
3401
if exp % 2:
3402
prod = prod * pow2
3403
if prod >= INTEGER_MOD_INT64_LIMIT: prod = prod % n
3404
exp = exp >> 1
3405
3406
if prod >= n:
3407
prod = prod % n
3408
return prod
3409
3410
3411
cdef int jacobi_int64(int_fast64_t a, int_fast64_t m) except -2:
3412
"""
3413
Calculates the jacobi symbol (a/n)
3414
3415
For use in IntegerMod_int64
3416
3417
AUTHORS:
3418
3419
- Robert Bradshaw
3420
"""
3421
cdef int s, jacobi = 1
3422
cdef int_fast64_t b
3423
3424
a = a % m
3425
3426
while 1:
3427
if a == 0:
3428
return 0 # gcd was nontrivial
3429
elif a == 1:
3430
return jacobi
3431
s = 0
3432
while (1 << s) & a == 0:
3433
s += 1
3434
b = a >> s
3435
# Now a = 2^s * b
3436
3437
# factor out (2/m)^s term
3438
if s % 2 == 1 and (m % 8 == 3 or m % 8 == 5):
3439
jacobi = -jacobi
3440
3441
if b == 1:
3442
return jacobi
3443
3444
# quadratic reciprocity
3445
if b % 4 == 3 and m % 4 == 3:
3446
jacobi = -jacobi
3447
a = m % b
3448
m = b
3449
3450
3451
########################
3452
# Square root functions
3453
########################
3454
3455
def square_root_mod_prime_power(IntegerMod_abstract a, p, e):
3456
r"""
3457
Calculates the square root of `a`, where `a` is an
3458
integer mod `p^e`.
3459
3460
ALGORITHM: Perform `p`-adically by stripping off even
3461
powers of `p` to get a unit and lifting
3462
`\sqrt{unit} \bmod p` via Newton's method.
3463
3464
AUTHORS:
3465
3466
- Robert Bradshaw
3467
3468
EXAMPLES::
3469
3470
sage: from sage.rings.finite_rings.integer_mod import square_root_mod_prime_power
3471
sage: a=Mod(17,2^20)
3472
sage: b=square_root_mod_prime_power(a,2,20)
3473
sage: b^2 == a
3474
True
3475
3476
::
3477
3478
sage: a=Mod(72,97^10)
3479
sage: b=square_root_mod_prime_power(a,97,10)
3480
sage: b^2 == a
3481
True
3482
"""
3483
if a.is_zero() or a.is_one():
3484
return a
3485
3486
if p == 2:
3487
if e == 1:
3488
return a
3489
# TODO: implement something that isn't totally idiotic.
3490
for x in a.parent():
3491
if x**2 == a:
3492
return x
3493
3494
# strip off even powers of p
3495
cdef int i, val = a.lift().valuation(p)
3496
if val % 2 == 1:
3497
raise ValueError, "self must be a square."
3498
if val > 0:
3499
unit = a._parent(a.lift() // p**val)
3500
else:
3501
unit = a
3502
3503
# find square root of unit mod p
3504
x = unit.parent()(square_root_mod_prime(mod(unit, p), p))
3505
3506
# lift p-adically using Newton iteration
3507
# this is done to higher precision than necessary except at the last step
3508
one_half = ~(a._new_c_from_long(2))
3509
for i from 0 <= i < ceil(log(e)/log(2)) - val/2:
3510
x = (x+unit/x) * one_half
3511
3512
# multiply in powers of p (if any)
3513
if val > 0:
3514
x *= p**(val // 2)
3515
return x
3516
3517
cpdef square_root_mod_prime(IntegerMod_abstract a, p=None):
3518
r"""
3519
Calculates the square root of `a`, where `a` is an
3520
integer mod `p`; if `a` is not a perfect square,
3521
this returns an (incorrect) answer without checking.
3522
3523
ALGORITHM: Several cases based on residue class of
3524
`p \bmod 16`.
3525
3526
3527
- `p \bmod 2 = 0`: `p = 2` so
3528
`\sqrt{a} = a`.
3529
3530
- `p \bmod 4 = 3`: `\sqrt{a} = a^{(p+1)/4}`.
3531
3532
- `p \bmod 8 = 5`: `\sqrt{a} = \zeta i a` where
3533
`\zeta = (2a)^{(p-5)/8}`, `i=\sqrt{-1}`.
3534
3535
- `p \bmod 16 = 9`: Similar, work in a bi-quadratic
3536
extension of `\GF{p}` for small `p`, Tonelli
3537
and Shanks for large `p`.
3538
3539
- `p \bmod 16 = 1`: Tonelli and Shanks.
3540
3541
3542
REFERENCES:
3543
3544
- Siguna Muller. 'On the Computation of Square Roots in Finite
3545
Fields' Designs, Codes and Cryptography, Volume 31, Issue 3
3546
(March 2004)
3547
3548
- A. Oliver L. Atkin. 'Probabilistic primality testing' (Chapter
3549
30, Section 4) In Ph. Flajolet and P. Zimmermann, editors,
3550
Algorithms Seminar, 1991-1992. INRIA Research Report 1779, 1992,
3551
http://www.inria.fr/rrrt/rr-1779.html. Summary by F. Morain.
3552
http://citeseer.ist.psu.edu/atkin92probabilistic.html
3553
3554
- H. Postl. 'Fast evaluation of Dickson Polynomials' Contrib. to
3555
General Algebra, Vol. 6 (1988) pp. 223-225
3556
3557
AUTHORS:
3558
3559
- Robert Bradshaw
3560
3561
TESTS: Every case appears in the first hundred primes.
3562
3563
::
3564
3565
sage: from sage.rings.finite_rings.integer_mod import square_root_mod_prime # sqrt() uses brute force for small p
3566
sage: all([square_root_mod_prime(a*a)^2 == a*a
3567
... for p in prime_range(100)
3568
... for a in Integers(p)])
3569
True
3570
"""
3571
if not a or a.is_one():
3572
return a
3573
3574
if p is None:
3575
p = a._parent.order()
3576
if p < PyInt_GetMax():
3577
p = int(p)
3578
3579
cdef int p_mod_16 = p % 16
3580
cdef double bits = log(float(p))/log(2)
3581
cdef long r, m
3582
3583
cdef Integer resZ
3584
3585
3586
if p_mod_16 % 2 == 0: # p == 2
3587
return a
3588
3589
elif p_mod_16 % 4 == 3:
3590
return a ** ((p+1)//4)
3591
3592
elif p_mod_16 % 8 == 5:
3593
two_a = a+a
3594
zeta = two_a ** ((p-5)//8)
3595
i = zeta**2 * two_a # = two_a ** ((p-1)//4)
3596
return zeta*a*(i-1)
3597
3598
elif p_mod_16 == 9 and bits < 500:
3599
two_a = a+a
3600
s = two_a ** ((p-1)//4)
3601
if s.is_one():
3602
d = a._parent.quadratic_nonresidue()
3603
d2 = d*d
3604
z = (two_a * d2) ** ((p-9)//16)
3605
i = two_a * d2 * z*z
3606
return z*d*a*(i-1)
3607
else:
3608
z = two_a ** ((p-9)//16)
3609
i = two_a * z*z
3610
return z*a*(i-1)
3611
3612
else:
3613
one = a._new_c_from_long(1)
3614
r, q = (p-one_Z).val_unit(2)
3615
v = a._parent.quadratic_nonresidue()**q
3616
3617
x = a ** ((q-1)//2)
3618
b = a*x*x # a ^ q
3619
res = a*x # a ^ ((q-1)/2)
3620
3621
while b != one:
3622
m = 1
3623
bpow = b*b
3624
while bpow != one:
3625
bpow *= bpow
3626
m += 1
3627
g = v**(one_Z << (r-m-1)) # v^(2^(r-m-1))
3628
res *= g
3629
b *= g*g
3630
return res
3631
3632
3633
def fast_lucas(mm, IntegerMod_abstract P):
3634
"""
3635
Return `V_k(P, 1)` where `V_k` is the Lucas
3636
function defined by the recursive relation
3637
3638
`V_k(P, Q) = PV_{k-1}(P, Q) - QV_{k-2}(P, Q)`
3639
3640
with `V_0 = 2, V_1(P_Q) = P`.
3641
3642
REFERENCES:
3643
3644
- H. Postl. 'Fast evaluation of Dickson Polynomials' Contrib. to
3645
General Algebra, Vol. 6 (1988) pp. 223-225
3646
3647
AUTHORS:
3648
3649
- Robert Bradshaw
3650
3651
TESTS::
3652
3653
sage: from sage.rings.finite_rings.integer_mod import fast_lucas, slow_lucas
3654
sage: all([fast_lucas(k, a) == slow_lucas(k, a)
3655
... for a in Integers(23)
3656
... for k in range(13)])
3657
True
3658
"""
3659
if mm == 0:
3660
return 2
3661
elif mm == 1:
3662
return P
3663
3664
cdef sage.rings.integer.Integer m
3665
m = <sage.rings.integer.Integer>mm if PY_TYPE_CHECK(mm, sage.rings.integer.Integer) else sage.rings.integer.Integer(mm)
3666
two = P._new_c_from_long(2)
3667
d1 = P
3668
d2 = P*P - two
3669
3670
sig_on()
3671
cdef int j
3672
for j from mpz_sizeinbase(m.value, 2)-1 > j > 0:
3673
if mpz_tstbit(m.value, j):
3674
d1 = d1*d2 - P
3675
d2 = d2*d2 - two
3676
else:
3677
d2 = d1*d2 - P
3678
d1 = d1*d1 - two
3679
sig_off()
3680
if mpz_odd_p(m.value):
3681
return d1*d2 - P
3682
else:
3683
return d1*d1 - two
3684
3685
def slow_lucas(k, P, Q=1):
3686
"""
3687
Lucas function defined using the standard definition, for
3688
consistency testing.
3689
"""
3690
if k == 0:
3691
return 2
3692
elif k == 1:
3693
return P
3694
else:
3695
return P*slow_lucas(k-1, P, Q) - Q*slow_lucas(k-2, P, Q)
3696
3697
3698
############# Homomorphisms ###############
3699
3700
cdef class IntegerMod_hom(Morphism):
3701
cdef IntegerMod_abstract zero
3702
cdef NativeIntStruct modulus
3703
def __init__(self, parent):
3704
Morphism.__init__(self, parent)
3705
# we need to use element constructor so that we can register both coercions and conversions using these morphisms.
3706
self.zero = self._codomain._element_constructor_(0)
3707
self.modulus = self._codomain._pyx_order
3708
cpdef Element _call_(self, x):
3709
return IntegerMod(self.codomain(), x)
3710
3711
cdef class IntegerMod_to_IntegerMod(IntegerMod_hom):
3712
"""
3713
Very fast IntegerMod to IntegerMod homomorphism.
3714
3715
EXAMPLES::
3716
3717
sage: from sage.rings.finite_rings.integer_mod import IntegerMod_to_IntegerMod
3718
sage: Rs = [Integers(3**k) for k in range(1,30,5)]
3719
sage: [type(R(0)) for R in Rs]
3720
[<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'>]
3721
sage: fs = [IntegerMod_to_IntegerMod(S, R) for R in Rs for S in Rs if S is not R and S.order() > R.order()]
3722
sage: all([f(-1) == f.codomain()(-1) for f in fs])
3723
True
3724
sage: [f(-1) for f in fs]
3725
[2, 2, 2, 2, 2, 728, 728, 728, 728, 177146, 177146, 177146, 43046720, 43046720, 10460353202]
3726
"""
3727
def __init__(self, R, S):
3728
if not S.order().divides(R.order()):
3729
raise TypeError, "No natural coercion from %s to %s" % (R, S)
3730
import sage.categories.homset
3731
IntegerMod_hom.__init__(self, sage.categories.homset.Hom(R, S))
3732
3733
cpdef Element _call_(self, x):
3734
cdef IntegerMod_abstract a
3735
if PY_TYPE_CHECK(x, IntegerMod_int):
3736
return (<IntegerMod_int>self.zero)._new_c((<IntegerMod_int>x).ivalue % self.modulus.int32)
3737
elif PY_TYPE_CHECK(x, IntegerMod_int64):
3738
return self.zero._new_c_from_long((<IntegerMod_int64>x).ivalue % self.modulus.int64)
3739
else: # PY_TYPE_CHECK(x, IntegerMod_gmp)
3740
a = self.zero._new_c_from_long(0)
3741
a.set_from_mpz((<IntegerMod_gmp>x).value)
3742
return a
3743
3744
def _repr_type(self):
3745
return "Natural"
3746
3747
cdef class Integer_to_IntegerMod(IntegerMod_hom):
3748
r"""
3749
Fast `\ZZ \rightarrow \ZZ/n\ZZ`
3750
morphism.
3751
3752
EXAMPLES:
3753
3754
We make sure it works for every type.
3755
3756
::
3757
3758
sage: from sage.rings.finite_rings.integer_mod import Integer_to_IntegerMod
3759
sage: Rs = [Integers(10), Integers(10^5), Integers(10^10)]
3760
sage: [type(R(0)) for R in Rs]
3761
[<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'>]
3762
sage: fs = [Integer_to_IntegerMod(R) for R in Rs]
3763
sage: [f(-1) for f in fs]
3764
[9, 99999, 9999999999]
3765
"""
3766
def __init__(self, R):
3767
import sage.categories.homset
3768
IntegerMod_hom.__init__(self, sage.categories.homset.Hom(integer_ring.ZZ, R))
3769
3770
cpdef Element _call_(self, x):
3771
cdef IntegerMod_abstract a
3772
cdef Py_ssize_t res
3773
if self.modulus.table is not None:
3774
res = x % self.modulus.int64
3775
if res < 0:
3776
res += self.modulus.int64
3777
a = self.modulus.lookup(res)
3778
if a._parent is not self._codomain:
3779
a._parent = self._codomain
3780
# print (<Element>a)._parent, " is not ", parent
3781
return a
3782
else:
3783
a = self.zero._new_c_from_long(0)
3784
a.set_from_mpz((<Integer>x).value)
3785
return a
3786
3787
def _repr_type(self):
3788
return "Natural"
3789
3790
def section(self):
3791
return IntegerMod_to_Integer(self._codomain)
3792
3793
cdef class IntegerMod_to_Integer(Map):
3794
def __init__(self, R):
3795
import sage.categories.homset
3796
from sage.categories.all import Sets
3797
Morphism.__init__(self, sage.categories.homset.Hom(R, integer_ring.ZZ, Sets()))
3798
3799
cpdef Element _call_(self, x):
3800
cdef Integer ans = PY_NEW(Integer)
3801
if PY_TYPE_CHECK(x, IntegerMod_gmp):
3802
mpz_set(ans.value, (<IntegerMod_gmp>x).value)
3803
elif PY_TYPE_CHECK(x, IntegerMod_int):
3804
mpz_set_si(ans.value, (<IntegerMod_int>x).ivalue)
3805
elif PY_TYPE_CHECK(x, IntegerMod_int64):
3806
mpz_set_si(ans.value, (<IntegerMod_int64>x).ivalue)
3807
return ans
3808
3809
def _repr_type(self):
3810
return "Lifting"
3811
3812
cdef class Int_to_IntegerMod(IntegerMod_hom):
3813
"""
3814
EXAMPLES:
3815
3816
We make sure it works for every type.
3817
3818
::
3819
3820
sage: from sage.rings.finite_rings.integer_mod import Int_to_IntegerMod
3821
sage: Rs = [Integers(2**k) for k in range(1,50,10)]
3822
sage: [type(R(0)) for R in Rs]
3823
[<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'>]
3824
sage: fs = [Int_to_IntegerMod(R) for R in Rs]
3825
sage: [f(-1) for f in fs]
3826
[1, 2047, 2097151, 2147483647, 2199023255551]
3827
"""
3828
def __init__(self, R):
3829
import sage.categories.homset
3830
from sage.structure.parent import Set_PythonType
3831
IntegerMod_hom.__init__(self, sage.categories.homset.Hom(Set_PythonType(int), R))
3832
3833
cpdef Element _call_(self, x):
3834
cdef IntegerMod_abstract a
3835
cdef long res = PyInt_AS_LONG(x)
3836
if PY_TYPE_CHECK(self.zero, IntegerMod_gmp):
3837
if 0 <= res < INTEGER_MOD_INT64_LIMIT:
3838
return self.zero._new_c_from_long(res)
3839
else:
3840
return IntegerMod_gmp(self.zero._parent, x)
3841
else:
3842
res %= self.modulus.int64
3843
if res < 0:
3844
res += self.modulus.int64
3845
if self.modulus.table is not None:
3846
a = self.modulus.lookup(res)
3847
if a._parent is not self._codomain:
3848
a._parent = self._codomain
3849
# print (<Element>a)._parent, " is not ", parent
3850
return a
3851
else:
3852
return self.zero._new_c_from_long(res)
3853
3854
def _repr_type(self):
3855
return "Native"
3856
3857