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