This repository has been archived by the owner on Jan 30, 2023. It is now read-only.
/
integer_mod.pyx
4285 lines (3478 loc) · 126 KB
/
integer_mod.pyx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
r"""
Elements of `\ZZ/n\ZZ`
An element of the integers modulo `n`.
There are three types of integer_mod classes, depending on the
size of the modulus.
- ``IntegerMod_int`` stores its value in a
``int_fast32_t`` (typically an ``int``);
this is used if the modulus is less than
`\sqrt{2^{31}-1}`.
- ``IntegerMod_int64`` stores its value in a
``int_fast64_t`` (typically a ``long
long``); this is used if the modulus is less than
`2^{31}-1`.
- ``IntegerMod_gmp`` stores its value in a
``mpz_t``; this can be used for an arbitrarily large
modulus.
All extend ``IntegerMod_abstract``.
For efficiency reasons, it stores the modulus (in all three forms,
if possible) in a common (cdef) class
``NativeIntStruct`` rather than in the parent.
AUTHORS:
- Robert Bradshaw: most of the work
- Didier Deshommes: bit shifting
- William Stein: editing and polishing; new arith architecture
- Robert Bradshaw: implement native is_square and square_root
- William Stein: sqrt
- Maarten Derickx: moved the valuation code from the global
valuation function to here
TESTS::
sage: R = Integers(101^3)
sage: a = R(824362); b = R(205942)
sage: a * b
851127
sage: type(IntegerModRing(2^31-1).an_element())
<type 'sage.rings.finite_rings.integer_mod.IntegerMod_int64'>
sage: type(IntegerModRing(2^31).an_element())
<type 'sage.rings.finite_rings.integer_mod.IntegerMod_gmp'>
"""
#################################################################################
# Copyright (C) 2006 Robert Bradshaw <robertwb@math.washington.edu>
# 2006 William Stein <wstein@gmail.com>
#
# Distributed under the terms of the GNU General Public License (GPL)
#
# http://www.gnu.org/licenses/
#*****************************************************************************
include "sage/ext/interrupt.pxi" # ctrl-c interrupt block support
include "sage/ext/stdsage.pxi"
from cpython.int cimport *
from cpython.list cimport *
from cpython.ref cimport *
cdef extern from "math.h":
double log(double)
int ceil(double)
cdef extern from "mpz_pylong.h":
cdef mpz_get_pyintlong(mpz_t src)
import operator
cdef bint use_32bit_type(int_fast64_t modulus):
return modulus <= INTEGER_MOD_INT32_LIMIT
## import arith
import sage.rings.rational as rational
from sage.libs.pari.all import pari, PariError
import sage.rings.integer_ring as integer_ring
import sage.rings.commutative_ring_element as commutative_ring_element
import sage.interfaces.all
import sage.rings.integer
import sage.rings.integer_ring
cimport sage.rings.integer
from sage.rings.integer cimport Integer
import sage.structure.element
cimport sage.structure.element
coerce_binop = sage.structure.element.coerce_binop
from sage.structure.element cimport RingElement, ModuleElement, Element
from sage.categories.morphism cimport Morphism
from sage.categories.map cimport Map
from sage.structure.sage_object import register_unpickle_override
#from sage.structure.parent cimport Parent
cdef Integer one_Z = Integer(1)
def Mod(n, m, parent=None):
"""
Return the equivalence class of `n` modulo `m` as
an element of `\ZZ/m\ZZ`.
EXAMPLES::
sage: x = Mod(12345678, 32098203845329048)
sage: x
12345678
sage: x^100
1017322209155072
You can also use the lowercase version::
sage: mod(12,5)
2
Illustrates that trac #5971 is fixed. Consider `n` modulo `m` when
`m = 0`. Then `\ZZ/0\ZZ` is isomorphic to `\ZZ` so `n` modulo `0` is
is equivalent to `n` for any integer value of `n`::
sage: Mod(10, 0)
10
sage: a = randint(-100, 100)
sage: Mod(a, 0) == a
True
"""
# when m is zero, then ZZ/0ZZ is isomorphic to ZZ
if m == 0:
return n
# m is non-zero, so return n mod m
cdef IntegerMod_abstract x
import integer_mod_ring
x = IntegerMod(integer_mod_ring.IntegerModRing(m), n)
if parent is None:
return x
x._parent = parent
return x
mod = Mod
register_unpickle_override('sage.rings.integer_mod', 'Mod', Mod)
register_unpickle_override('sage.rings.integer_mod', 'mod', mod)
def IntegerMod(parent, value):
"""
Create an integer modulo `n` with the given parent.
This is mainly for internal use.
"""
cdef NativeIntStruct modulus
cdef Py_ssize_t res
modulus = parent._pyx_order
if modulus.table is not None:
if PY_TYPE_CHECK(value, sage.rings.integer.Integer) or PY_TYPE_CHECK(value, int) or PY_TYPE_CHECK(value, long):
res = value % modulus.int64
if res < 0:
res = res + modulus.int64
a = modulus.lookup(res)
if (<Element>a)._parent is not parent:
(<Element>a)._parent = parent
# print (<Element>a)._parent, " is not ", parent
return a
if modulus.int32 != -1:
return IntegerMod_int(parent, value)
elif modulus.int64 != -1:
return IntegerMod_int64(parent, value)
else:
return IntegerMod_gmp(parent, value)
def is_IntegerMod(x):
"""
Return ``True`` if and only if x is an integer modulo
`n`.
EXAMPLES::
sage: from sage.rings.finite_rings.integer_mod import is_IntegerMod
sage: is_IntegerMod(5)
False
sage: is_IntegerMod(Mod(5,10))
True
"""
return PY_TYPE_CHECK(x, IntegerMod_abstract)
def makeNativeIntStruct(sage.rings.integer.Integer z):
"""
Function to convert a Sage Integer into class NativeIntStruct.
.. note::
This function is only used for the unpickle override below.
"""
return NativeIntStruct(z)
register_unpickle_override('sage.rings.integer_mod', 'makeNativeIntStruct', makeNativeIntStruct)
cdef class NativeIntStruct:
"""
We store the various forms of the modulus here rather than in the
parent for efficiency reasons.
We may also store a cached table of all elements of a given ring in
this class.
"""
def __init__(NativeIntStruct self, sage.rings.integer.Integer z):
self.int64 = -1
self.int32 = -1
self.table = None # NULL
self.sageInteger = z
if mpz_cmp_si(z.value, INTEGER_MOD_INT64_LIMIT) <= 0:
self.int64 = mpz_get_si(z.value)
if use_32bit_type(self.int64):
self.int32 = self.int64
def __reduce__(NativeIntStruct self):
return sage.rings.finite_rings.integer_mod.makeNativeIntStruct, (self.sageInteger, )
def precompute_table(NativeIntStruct self, parent, inverses=True):
"""
Function to compute and cache all elements of this class.
If ``inverses == True``, also computes and caches the inverses
of the invertible elements.
EXAMPLES:
This is used by the :class:`sage.rings.finite_rings.integer_mod_ring.IntegerModRing_generic` constructor::
sage: from sage.rings.finite_rings.integer_mod_ring import IntegerModRing_generic
sage: R = IntegerModRing_generic(39, cache=False)
sage: R(5)^-1
8
sage: R(5)^-1 is R(8)
False
sage: R = IntegerModRing_generic(39, cache=True) # indirect doctest
sage: R(5)^-1 is R(8)
True
Check that the inverse of 0 modulo 1 works, see :trac:`13639`::
sage: R = IntegerModRing_generic(1, cache=True) # indirect doctest
sage: R(0)^-1 is R(0)
True
"""
self.table = PyList_New(self.int64)
cdef Py_ssize_t i
if self.int32 != -1:
for i from 0 <= i < self.int32:
z = IntegerMod_int(parent, i)
Py_INCREF(z); PyList_SET_ITEM(self.table, i, z)
else:
for i from 0 <= i < self.int64:
z = IntegerMod_int64(parent, i)
Py_INCREF(z); PyList_SET_ITEM(self.table, i, z)
if inverses:
if self.int64 == 1:
# Special case for integers modulo 1
self.inverses = self.table
else:
tmp = [None] * self.int64
for i from 1 <= i < self.int64:
try:
tmp[i] = ~self.table[i]
except ZeroDivisionError:
pass
self.inverses = tmp
def _get_table(self):
return self.table
cdef lookup(NativeIntStruct self, Py_ssize_t value):
return <object>PyList_GET_ITEM(self.table, value)
cdef class IntegerMod_abstract(FiniteRingElement):
def __init__(self, parent):
"""
EXAMPLES::
sage: a = Mod(10,30^10); a
10
sage: loads(a.dumps()) == a
True
"""
self._parent = parent
self.__modulus = parent._pyx_order
cdef _new_c_from_long(self, long value):
cdef IntegerMod_abstract x
x = <IntegerMod_abstract>PY_NEW(<object>PY_TYPE(self))
if PY_TYPE_CHECK(x, IntegerMod_gmp):
mpz_init((<IntegerMod_gmp>x).value) # should be done by the new method
x._parent = self._parent
x.__modulus = self.__modulus
x.set_from_long(value)
return x
cdef void set_from_mpz(self, mpz_t value):
raise NotImplementedError, "Must be defined in child class."
cdef void set_from_long(self, long value):
raise NotImplementedError, "Must be defined in child class."
def __abs__(self):
"""
Raise an error message, since ``abs(x)`` makes no sense
when ``x`` is an integer modulo `n`.
EXAMPLES::
sage: abs(Mod(2,3))
Traceback (most recent call last):
...
ArithmeticError: absolute valued not defined on integers modulo n.
"""
raise ArithmeticError, "absolute valued not defined on integers modulo n."
def __reduce__(IntegerMod_abstract self):
"""
EXAMPLES::
sage: a = Mod(4,5); a
4
sage: loads(a.dumps()) == a
True
sage: a = Mod(-1,5^30)^25;
sage: loads(a.dumps()) == a
True
"""
return sage.rings.finite_rings.integer_mod.mod, (self.lift(), self.modulus(), self.parent())
def is_nilpotent(self):
r"""
Return ``True`` if ``self`` is nilpotent,
i.e., some power of ``self`` is zero.
EXAMPLES::
sage: a = Integers(90384098234^3)
sage: factor(a.order())
2^3 * 191^3 * 236607587^3
sage: b = a(2*191)
sage: b.is_nilpotent()
False
sage: b = a(2*191*236607587)
sage: b.is_nilpotent()
True
ALGORITHM: Let `m \geq \log_2(n)`, where `n` is
the modulus. Then `x \in \ZZ/n\ZZ` is
nilpotent if and only if `x^m = 0`.
PROOF: This is clear if you reduce to the prime power case, which
you can do via the Chinese Remainder Theorem.
We could alternatively factor `n` and check to see if the
prime divisors of `n` all divide `x`. This is
asymptotically slower :-).
"""
if self.is_zero():
return True
m = self.__modulus.sageInteger.exact_log(2) + 1
return (self**m).is_zero()
#################################################################
# Interfaces
#################################################################
def _pari_init_(self):
return 'Mod(%s,%s)'%(str(self), self.__modulus.sageInteger)
def _pari_(self):
return self.lift()._pari_().Mod(self.__modulus.sageInteger)
def _gap_init_(self):
r"""
Return string representation of corresponding GAP object.
EXAMPLES::
sage: a = Mod(2,19)
sage: gap(a)
Z(19)
sage: gap(Mod(3, next_prime(10000)))
Z(10007)^6190
sage: gap(Mod(3, next_prime(100000)))
ZmodpZObj( 3, 100003 )
sage: gap(Mod(4, 48))
ZmodnZObj( 4, 48 )
"""
return '%s*One(ZmodnZ(%s))' % (self, self.__modulus.sageInteger)
def _magma_init_(self, magma):
"""
Coercion to Magma.
EXAMPLES::
sage: a = Integers(15)(4)
sage: b = magma(a) # optional - magma
sage: b.Type() # optional - magma
RngIntResElt
sage: b^2 # optional - magma
1
"""
return '%s!%s'%(self.parent()._magma_init_(magma), self)
def _axiom_init_(self):
"""
Return a string representation of the corresponding to
(Pan)Axiom object.
EXAMPLES::
sage: a = Integers(15)(4)
sage: a._axiom_init_()
'4 :: IntegerMod(15)'
sage: aa = axiom(a); aa #optional - axiom
4
sage: aa.type() #optional - axiom
IntegerMod 15
sage: aa = fricas(a); aa #optional - fricas
4
sage: aa.type() #optional - fricas
IntegerMod(15)
"""
return '%s :: %s'%(self, self.parent()._axiom_init_())
_fricas_init_ = _axiom_init_
def _sage_input_(self, sib, coerced):
r"""
Produce an expression which will reproduce this value when
evaluated.
EXAMPLES::
sage: K = GF(7)
sage: sage_input(K(5), verify=True)
# Verified
GF(7)(5)
sage: sage_input(K(5) * polygen(K), verify=True)
# Verified
R.<x> = GF(7)[]
5*x
sage: from sage.misc.sage_input import SageInputBuilder
sage: K(5)._sage_input_(SageInputBuilder(), False)
{call: {call: {atomic:GF}({atomic:7})}({atomic:5})}
sage: K(5)._sage_input_(SageInputBuilder(), True)
{atomic:5}
"""
v = sib.int(self.lift())
if coerced:
return v
else:
return sib(self.parent())(v)
def log(self, b=None):
r"""
Return an integer `x` such that `b^x = a`, where
`a` is ``self``.
INPUT:
- ``self`` - unit modulo `n`
- ``b`` - a unit modulo `n`. If ``b`` is not given,
``R.multiplicative_generator()`` is used, where
``R`` is the parent of ``self``.
OUTPUT: Integer `x` such that `b^x = a`, if this exists; a ValueError otherwise.
.. note::
If the modulus is prime and b is a generator, this calls Pari's ``znlog``
function, which is rather fast. If not, it falls back on the generic
discrete log implementation in :meth:`sage.groups.generic.discrete_log`.
EXAMPLES::
sage: r = Integers(125)
sage: b = r.multiplicative_generator()^3
sage: a = b^17
sage: a.log(b)
17
sage: a.log()
51
A bigger example::
sage: FF = FiniteField(2^32+61)
sage: c = FF(4294967356)
sage: x = FF(2)
sage: a = c.log(x)
sage: a
2147483678
sage: x^a
4294967356
Things that can go wrong. E.g., if the base is not a generator for
the multiplicative group, or not even a unit.
::
sage: Mod(3, 7).log(Mod(2, 7))
Traceback (most recent call last):
...
ValueError: No discrete log of 3 found to base 2
sage: a = Mod(16, 100); b = Mod(4,100)
sage: a.log(b)
Traceback (most recent call last):
...
ZeroDivisionError: Inverse does not exist.
We check that #9205 is fixed::
sage: Mod(5,9).log(Mod(2, 9))
5
We test against a bug (side effect on PARI) fixed in #9438::
sage: R.<a, b> = QQ[]
sage: pari(b)
b
sage: GF(7)(5).log()
5
sage: pari(b)
b
AUTHORS:
- David Joyner and William Stein (2005-11)
- William Stein (2007-01-27): update to use PARI as requested
by David Kohel.
- Simon King (2010-07-07): fix a side effect on PARI
"""
if b is None:
b = self._parent.multiplicative_generator()
else:
b = self._parent(b)
if self.modulus().is_prime() and b.multiplicative_order() == b.parent().unit_group_order():
# use PARI
cmd = 'if(znorder(Mod(%s,%s))!=eulerphi(%s),-1,znlog(%s,Mod(%s,%s)))'%(b, self.__modulus.sageInteger,
self.__modulus.sageInteger,
self, b, self.__modulus.sageInteger)
try:
n = Integer(pari(cmd))
return n
except PariError, msg:
raise ValueError, "%s\nPARI failed to compute discrete log (perhaps base is not a generator or is too large)"%msg
else: # fall back on slower native implementation
from sage.groups.generic import discrete_log
return discrete_log(self, b)
def generalised_log(self):
r"""
Return integers `n_i` such that
..math::
\prod_i x_i^{n_i} = \text{self},
where `x_1, \dots, x_d` are the generators of the unit group
returned by ``self.parent().unit_gens()``. See also :meth:`log`.
EXAMPLES::
sage: m = Mod(3, 1568)
sage: v = m.generalised_log(); v
[1, 3, 1]
sage: prod([Zmod(1568).unit_gens()[i] ** v[i] for i in [0..2]])
3
"""
if not self.is_unit():
raise ZeroDivisionError
N = self.modulus()
h = []
for (p, c) in N.factor():
if p != 2 or (p == 2 and c == 2):
h.append((self % p**c).log())
elif c > 2:
m = self % p**c
if m % 4 == 1:
h.append(0)
else:
h.append(1)
m *= -1
h.append(m.log(5))
return h
def modulus(IntegerMod_abstract self):
"""
EXAMPLES::
sage: Mod(3,17).modulus()
17
"""
return self.__modulus.sageInteger
def charpoly(self, var='x'):
"""
Returns the characteristic polynomial of this element.
EXAMPLES::
sage: k = GF(3)
sage: a = k.gen()
sage: a.charpoly('x')
x + 2
sage: a + 2
0
AUTHORS:
- Craig Citro
"""
R = self.parent()[var]
return R([-self,1])
def minpoly(self, var='x'):
"""
Returns the minimal polynomial of this element.
EXAMPLES:
sage: GF(241, 'a')(1).minpoly()
x + 240
"""
return self.charpoly(var)
def minimal_polynomial(self, var='x'):
"""
Returns the minimal polynomial of this element.
EXAMPLES:
sage: GF(241, 'a')(1).minimal_polynomial(var = 'z')
z + 240
"""
return self.minpoly(var)
def polynomial(self, var='x'):
"""
Returns a constant polynomial representing this value.
EXAMPLES::
sage: k = GF(7)
sage: a = k.gen(); a
1
sage: a.polynomial()
1
sage: type(a.polynomial())
<type 'sage.rings.polynomial.polynomial_zmod_flint.Polynomial_zmod_flint'>
"""
R = self.parent()[var]
return R(self)
def norm(self):
"""
Returns the norm of this element, which is itself. (This is here
for compatibility with higher order finite fields.)
EXAMPLES::
sage: k = GF(691)
sage: a = k(389)
sage: a.norm()
389
AUTHORS:
- Craig Citro
"""
return self
def trace(self):
"""
Returns the trace of this element, which is itself. (This is here
for compatibility with higher order finite fields.)
EXAMPLES::
sage: k = GF(691)
sage: a = k(389)
sage: a.trace()
389
AUTHORS:
- Craig Citro
"""
return self
def lift_centered(self):
r"""
Lift ``self`` to an integer `i` such that `n/2 < i <= n/2`
(where `n` denotes the modulus).
EXAMPLES::
sage: Mod(0,5).lift_centered()
0
sage: Mod(1,5).lift_centered()
1
sage: Mod(2,5).lift_centered()
2
sage: Mod(3,5).lift_centered()
-2
sage: Mod(4,5).lift_centered()
-1
sage: Mod(50,100).lift_centered()
50
sage: Mod(51,100).lift_centered()
-49
sage: Mod(-1,3^100).lift_centered()
-1
"""
n = self.modulus()
x = self.lift()
if 2*x <= n:
return x
else:
return x - n
cpdef bint is_one(self):
raise NotImplementedError
cpdef bint is_unit(self):
raise NotImplementedError
def is_square(self):
r"""
EXAMPLES::
sage: Mod(3,17).is_square()
False
sage: Mod(9,17).is_square()
True
sage: Mod(9,17*19^2).is_square()
True
sage: Mod(-1,17^30).is_square()
True
sage: Mod(1/9, next_prime(2^40)).is_square()
True
sage: Mod(1/25, next_prime(2^90)).is_square()
True
TESTS::
sage: Mod(1/25, 2^8).is_square()
True
sage: Mod(1/25, 2^40).is_square()
True
sage: for p,q,r in cartesian_product_iterator([[3,5],[11,13],[17,19]]): # long time
....: for ep,eq,er in cartesian_product_iterator([[0,1,2,3],[0,1,2,3],[0,1,2,3]]):
....: for e2 in [0, 1, 2, 3, 4]:
....: n = p^ep * q^eq * r^er * 2^e2
....: for _ in range(2):
....: a = Zmod(n).random_element()
....: if a.is_square().__xor__(a._pari_().issquare()):
....: print a, n
ALGORITHM: Calculate the Jacobi symbol
`(\mathtt{self}/p)` at each prime `p`
dividing `n`. It must be 1 or 0 for each prime, and if it
is 0 mod `p`, where `p^k || n`, then
`ord_p(\mathtt{self})` must be even or greater than
`k`.
The case `p = 2` is handled separately.
AUTHORS:
- Robert Bradshaw
"""
return self.is_square_c()
cdef bint is_square_c(self) except -2:
cdef int l2, m2
if self.is_zero() or self.is_one():
return 1
# We first try to rule out self being a square without
# factoring the modulus.
lift = self.lift()
m2, modd = self.modulus().val_unit(2)
if m2 == 2:
if lift & 2 == 2: # lift = 2 or 3 (mod 4)
return 0
elif m2 > 2:
l2, lodd = lift.val_unit(2)
if l2 < m2 and (l2 % 2 == 1 or lodd % (1 << min(3, m2 - l2)) != 1):
return 0
# self is a square modulo 2^m2. We compute the Jacobi symbol
# modulo modd. If this is -1, then self is not a square.
if lift.jacobi(modd) == -1:
return 0
# We need to factor the modulus. We do it here instead of
# letting PARI do it, so that we can cache the factorisation.
return lift._pari_().Zn_issquare(self._parent.factored_order()._pari_())
def sqrt(self, extend=True, all=False):
r"""
Returns square root or square roots of ``self`` modulo
`n`.
INPUT:
- ``extend`` - bool (default: ``True``);
if ``True``, return a square root in an extension ring,
if necessary. Otherwise, raise a ``ValueError`` if the
square root is not in the base ring.
- ``all`` - bool (default: ``False``); if
``True``, return {all} square roots of self, instead of
just one.
ALGORITHM: Calculates the square roots mod `p` for each of
the primes `p` dividing the order of the ring, then lifts
them `p`-adically and uses the CRT to find a square root
mod `n`.
See also ``square_root_mod_prime_power`` and
``square_root_mod_prime`` (in this module) for more
algorithmic details.
EXAMPLES::
sage: mod(-1, 17).sqrt()
4
sage: mod(5, 389).sqrt()
86
sage: mod(7, 18).sqrt()
5
sage: a = mod(14, 5^60).sqrt()
sage: a*a
14
sage: mod(15, 389).sqrt(extend=False)
Traceback (most recent call last):
...
ValueError: self must be a square
sage: Mod(1/9, next_prime(2^40)).sqrt()^(-2)
9
sage: Mod(1/25, next_prime(2^90)).sqrt()^(-2)
25
::
sage: a = Mod(3,5); a
3
sage: x = Mod(-1, 360)
sage: x.sqrt(extend=False)
Traceback (most recent call last):
...
ValueError: self must be a square
sage: y = x.sqrt(); y
sqrt359
sage: y.parent()
Univariate Quotient Polynomial Ring in sqrt359 over Ring of integers modulo 360 with modulus x^2 + 1
sage: y^2
359
We compute all square roots in several cases::
sage: R = Integers(5*2^3*3^2); R
Ring of integers modulo 360
sage: R(40).sqrt(all=True)
[20, 160, 200, 340]
sage: [x for x in R if x^2 == 40] # Brute force verification
[20, 160, 200, 340]
sage: R(1).sqrt(all=True)
[1, 19, 71, 89, 91, 109, 161, 179, 181, 199, 251, 269, 271, 289, 341, 359]
sage: R(0).sqrt(all=True)
[0, 60, 120, 180, 240, 300]
::
sage: R = Integers(5*13^3*37); R
Ring of integers modulo 406445
sage: v = R(-1).sqrt(all=True); v
[78853, 111808, 160142, 193097, 213348, 246303, 294637, 327592]
sage: [x^2 for x in v]
[406444, 406444, 406444, 406444, 406444, 406444, 406444, 406444]
sage: v = R(169).sqrt(all=True); min(v), -max(v), len(v)
(13, 13, 104)
sage: all([x^2==169 for x in v])
True
::
sage: t = FiniteField(next_prime(2^100))(4)
sage: t.sqrt(extend = False, all = True)
[2, 1267650600228229401496703205651]
sage: t = FiniteField(next_prime(2^100))(2)
sage: t.sqrt(extend = False, all = True)
[]
Modulo a power of 2::
sage: R = Integers(2^7); R
Ring of integers modulo 128
sage: a = R(17)
sage: a.sqrt()
23
sage: a.sqrt(all=True)
[23, 41, 87, 105]
sage: [x for x in R if x^2==17]
[23, 41, 87, 105]
"""
if self.is_one():
if all:
return list(self.parent().square_roots_of_one())
else:
return self
if not self.is_square_c():
if extend:
y = 'sqrt%s'%self
R = self.parent()['x']
modulus = R.gen()**2 - R(self)
if self._parent.is_field():
import constructor
Q = constructor.FiniteField(self.__modulus.sageInteger**2, y, modulus)
else:
R = self.parent()['x']
Q = R.quotient(modulus, names=(y,))
z = Q.gen()
if all:
# TODO
raise NotImplementedError
return z
if all:
return []
raise ValueError, "self must be a square"
F = self._parent.factored_order()
cdef long e, exp, val
if len(F) == 1:
p, e = F[0]
if all and e > 1 and not self.is_unit():
if self.is_zero():
# All multiples of p^ciel(e/2) vanish
return [self._parent(x) for x in xrange(0, self.__modulus.sageInteger, p**((e+1)/2))]
else:
z = self.lift()
val = z.valuation(p)/2 # square => valuation is even
from sage.rings.finite_rings.integer_mod_ring import IntegerModRing
# Find the unit part (mod the ring with appropriate precision)
u = IntegerModRing(p**(e-val))(z // p**(2*val))
# will add multiples of p^exp
exp = e - val
if p == 2:
exp -= 1 # note the factor of 2 below
if 2*exp < e:
exp = (e+1)/2
# For all a^2 = u and all integers b
# (a*p^val + b*p^exp) ^ 2
# = u*p^(2*val) + 2*a*b*p^(val+exp) + b^2*p^(2*exp)
# = u*p^(2*val) mod p^e
# whenever min(val+exp, 2*exp) > e
p_val = p**val
p_exp = p**exp
w = [self._parent(a.lift() * p_val + b)
for a in u.sqrt(all=True)
for b in xrange(0, self.__modulus.sageInteger, p_exp)]