Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemath
GitHub Repository: sagemath/sagelib
Path: blob/master/sage/rings/integer_ring.pyx
4045 views
1
r"""
2
Ring `\ZZ` of Integers
3
4
The class ``IntegerRing`` represents the ring
5
`\ZZ` of (arbitrary precision) integers. Each
6
integer is an instance of the class ``Integer``, which
7
is defined in a Pyrex extension module that wraps GMP integers (the
8
``mpz_t`` type in GMP).
9
10
::
11
12
sage: Z = IntegerRing(); Z
13
Integer Ring
14
sage: Z.characteristic()
15
0
16
sage: Z.is_field()
17
False
18
19
There is a unique instances of class ``IntegerRing``.
20
To create an ``Integer``, coerce either a Python int,
21
long, or a string. Various other types will also coerce to the
22
integers, when it makes sense.
23
24
::
25
26
sage: a = Z(1234); b = Z(5678); print a, b
27
1234 5678
28
sage: type(a)
29
<type 'sage.rings.integer.Integer'>
30
sage: a + b
31
6912
32
sage: Z('94803849083985934859834583945394')
33
94803849083985934859834583945394
34
"""
35
36
#*****************************************************************************
37
#
38
# Sage
39
#
40
# Copyright (C) 2005 William Stein <[email protected]>
41
#
42
# Distributed under the terms of the GNU General Public License (GPL)
43
#
44
# This code is distributed in the hope that it will be useful,
45
# but WITHOUT ANY WARRANTY; without even the implied warranty of
46
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
47
# General Public License for more details.
48
#
49
# The full text of the GPL is available at:
50
#
51
# http://www.gnu.org/licenses/
52
#*****************************************************************************
53
54
###########################################################################
55
56
include "../ext/cdefs.pxi"
57
include "../ext/gmp.pxi"
58
include "../ext/stdsage.pxi"
59
include "../ext/interrupt.pxi" # ctrl-c interrupt block support
60
include "../ext/random.pxi"
61
62
include "../ext/python_int.pxi"
63
include "../ext/python_list.pxi"
64
65
import sage.rings.infinity
66
import sage.rings.rational
67
import sage.rings.rational_field
68
import sage.rings.ideal
69
import sage.structure.factorization as factorization
70
import sage.libs.pari.all
71
import sage.rings.ideal
72
from sage.categories.basic import EuclideanDomains
73
from sage.structure.parent_gens import ParentWithGens
74
from sage.structure.parent cimport Parent
75
76
from sage.structure.sequence import Sequence
77
78
cimport integer
79
cimport rational
80
81
import ring
82
83
arith = None
84
cdef void late_import():
85
global arith
86
if arith is None:
87
import sage.rings.arith
88
arith = sage.rings.arith
89
90
cdef int number_of_integer_rings = 0
91
92
def is_IntegerRing(x):
93
"""
94
Internal function: returns true iff x is the ring ZZ of integers
95
96
EXAMPLES::
97
98
sage: from sage.rings.integer_ring import is_IntegerRing
99
sage: is_IntegerRing(ZZ)
100
True
101
sage: is_IntegerRing(QQ)
102
False
103
sage: is_IntegerRing(parent(3))
104
True
105
sage: is_IntegerRing(parent(1/3))
106
False
107
"""
108
return PY_TYPE_CHECK(x, IntegerRing_class)
109
110
import integer_ring_python
111
112
cdef class IntegerRing_class(PrincipalIdealDomain):
113
r"""
114
The ring of integers.
115
116
In order to introduce the ring `\ZZ` of integers, we
117
illustrate creation, calling a few functions, and working with its
118
elements.
119
120
::
121
122
sage: Z = IntegerRing(); Z
123
Integer Ring
124
sage: Z.characteristic()
125
0
126
sage: Z.is_field()
127
False
128
sage: Z.category()
129
Category of euclidean domains
130
sage: Z(2^(2^5) + 1)
131
4294967297
132
133
One can give strings to create integers. Strings starting with
134
``0x`` are interpreted as hexadecimal, and strings starting with
135
``0`` are interpreted as octal::
136
137
sage: parent('37')
138
<type 'str'>
139
sage: parent(Z('37'))
140
Integer Ring
141
sage: Z('0x10')
142
16
143
sage: Z('0x1a')
144
26
145
sage: Z('020')
146
16
147
148
As an inverse to :meth:`~sage.rings.integer.Integer.digits`,
149
lists of digits are accepted, provided that you give a base. The
150
lists are interpreted in little-endian order, so that entry ``i`` of
151
the list is the coefficient of ``base^i``::
152
153
sage: Z([3, 7], 10)
154
73
155
sage: Z([3, 7], 9)
156
66
157
sage: Z([], 10)
158
0
159
160
We next illustrate basic arithmetic in `\ZZ`::
161
162
sage: a = Z(1234); b = Z(5678); print a, b
163
1234 5678
164
sage: type(a)
165
<type 'sage.rings.integer.Integer'>
166
sage: a + b
167
6912
168
sage: b + a
169
6912
170
sage: a * b
171
7006652
172
sage: b * a
173
7006652
174
sage: a - b
175
-4444
176
sage: b - a
177
4444
178
179
When we divide to integers using /, the result is automatically
180
coerced to the field of rational numbers, even if the result is an
181
integer.
182
183
::
184
185
sage: a / b
186
617/2839
187
sage: type(a/b)
188
<type 'sage.rings.rational.Rational'>
189
sage: a/a
190
1
191
sage: type(a/a)
192
<type 'sage.rings.rational.Rational'>
193
194
For floor division, instead using the // operator::
195
196
sage: a // b
197
0
198
sage: type(a//b)
199
<type 'sage.rings.integer.Integer'>
200
201
Next we illustrate arithmetic with automatic coercion. The types
202
that coerce are: str, int, long, Integer.
203
204
::
205
206
sage: a + 17
207
1251
208
sage: a * 374
209
461516
210
sage: 374 * a
211
461516
212
sage: a/19
213
1234/19
214
sage: 0 + Z(-64)
215
-64
216
217
Integers can be coerced::
218
219
sage: a = Z(-64)
220
sage: int(a)
221
-64
222
223
We can create integers from several types of objects.
224
225
::
226
227
sage: ZZ(17/1)
228
17
229
sage: ZZ(Mod(19,23))
230
19
231
sage: ZZ(2 + 3*5 + O(5^3))
232
17
233
234
TESTS::
235
236
sage: TestSuite(ZZ).run()
237
"""
238
239
def __init__(self):
240
ParentWithGens.__init__(self, self, ('x',), normalize=False, category = EuclideanDomains())
241
self._populate_coercion_lists_(element_constructor=integer.Integer,
242
init_no_parent=True,
243
convert_method_name='_integer_')
244
245
def __cinit__(self):
246
# This is here because very old pickled integers don't have unique parents.
247
global number_of_integer_rings
248
if type(self) is IntegerRing_class:
249
if number_of_integer_rings > 0:
250
self._populate_coercion_lists_(element_constructor=integer.Integer,
251
init_no_parent=True,
252
convert_method_name='_integer_')
253
number_of_integer_rings += 1
254
255
def __reduce__(self):
256
"""
257
TESTS::
258
259
sage: loads(dumps(ZZ)) is ZZ
260
True
261
"""
262
return IntegerRing, ()
263
264
def __hash__(self):
265
return 554590422
266
267
def __richcmp__(left, right, int op):
268
return (<Parent>left)._richcmp_helper(right, op)
269
270
def _cmp_(left, right):
271
if isinstance(right,IntegerRing_class):
272
return 0
273
if isinstance(right, sage.rings.rational_field.RationalField):
274
return -1
275
return cmp(type(left), type(right))
276
277
def _repr_(self):
278
return "Integer Ring"
279
280
def _latex_(self):
281
return "\\Bold{Z}"
282
283
def __len__(self):
284
raise TypeError, 'len() of unsized object'
285
286
def _div(self, integer.Integer left, integer.Integer right):
287
cdef rational.Rational x = PY_NEW(rational.Rational)
288
if mpz_sgn(right.value) == 0:
289
raise ZeroDivisionError, 'Rational division by zero'
290
mpz_set(mpq_numref(x.value), left.value)
291
mpz_set(mpq_denref(x.value), right.value)
292
mpq_canonicalize(x.value)
293
return x
294
295
def __getitem__(self, x):
296
"""
297
Return the ring ZZ[...] obtained by adjoining to the integers a list
298
x of several elements.
299
300
EXAMPLES::
301
302
sage: ZZ[ sqrt(2), sqrt(3) ]
303
Relative Order in Number Field in sqrt2 with defining polynomial x^2 - 2 over its base field
304
sage: ZZ[x]
305
Univariate Polynomial Ring in x over Integer Ring
306
sage: ZZ['x,y']
307
Multivariate Polynomial Ring in x, y over Integer Ring
308
sage: R = ZZ[ sqrt(5) + 1]; R
309
Order in Number Field in a with defining polynomial x^2 - 2*x - 4
310
sage: R.is_maximal()
311
False
312
sage: R = ZZ[ (1+sqrt(5))/2 ]; R
313
Order in Number Field in a with defining polynomial x^2 - x - 1
314
sage: R.is_maximal()
315
True
316
"""
317
if x in self:
318
return self
319
if isinstance(x, str):
320
return PrincipalIdealDomain.__getitem__(self, x)
321
from sage.symbolic.ring import is_SymbolicVariable
322
323
if is_SymbolicVariable(x):
324
return PrincipalIdealDomain.__getitem__(self, repr(x))
325
326
from sage.rings.number_field.all import is_NumberFieldElement
327
328
if is_NumberFieldElement(x):
329
K, from_K = x.parent().subfield(x)
330
return K.order(K.gen())
331
332
return PrincipalIdealDomain.__getitem__(self, x)
333
334
def range(self, start, end=None, step=None):
335
"""
336
Optimized range function for Sage integer.
337
338
AUTHORS:
339
340
- Robert Bradshaw (2007-09-20)
341
342
EXAMPLES::
343
344
sage: ZZ.range(10)
345
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
346
sage: ZZ.range(-5,5)
347
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4]
348
sage: ZZ.range(0,50,5)
349
[0, 5, 10, 15, 20, 25, 30, 35, 40, 45]
350
sage: ZZ.range(0,50,-5)
351
[]
352
sage: ZZ.range(50,0,-5)
353
[50, 45, 40, 35, 30, 25, 20, 15, 10, 5]
354
sage: ZZ.range(50,0,5)
355
[]
356
sage: ZZ.range(50,-1,-5)
357
[50, 45, 40, 35, 30, 25, 20, 15, 10, 5, 0]
358
359
It uses different code if the step doesn't fit in a long::
360
361
sage: ZZ.range(0,2^83,2^80)
362
[0, 1208925819614629174706176, 2417851639229258349412352, 3626777458843887524118528, 4835703278458516698824704, 6044629098073145873530880, 7253554917687775048237056, 8462480737302404222943232]
363
364
Make sure #8818 is fixed::
365
366
sage: ZZ.range(1r, 10r)
367
[1, 2, 3, 4, 5, 6, 7, 8, 9]
368
"""
369
if end is None:
370
end = start
371
start = PY_NEW(Integer) # 0
372
if step is None:
373
step = 1
374
if not PyInt_CheckExact(step):
375
if not PY_TYPE_CHECK(step, integer.Integer):
376
step = integer.Integer(step)
377
if mpz_fits_slong_p((<Integer>step).value):
378
step = int(step)
379
if not PY_TYPE_CHECK(start, integer.Integer):
380
start = integer.Integer(start)
381
if not PY_TYPE_CHECK(end, integer.Integer):
382
end = integer.Integer(end)
383
cdef integer.Integer a = <Integer>start
384
cdef integer.Integer b = <Integer>end
385
386
cdef int step_sign
387
cdef long istep
388
cdef integer.Integer zstep, last
389
390
L = []
391
if PyInt_CheckExact(step):
392
istep = PyInt_AS_LONG(step)
393
step_sign = istep
394
else:
395
zstep = <Integer>step
396
step_sign = mpz_sgn(zstep.value)
397
398
sig_on()
399
while mpz_cmp(a.value, b.value)*step_sign < 0:
400
last = a
401
a = PY_NEW(Integer)
402
if PyInt_CheckExact(step): # count on branch prediction...
403
if istep > 0:
404
mpz_add_ui(a.value, last.value, istep)
405
else:
406
mpz_sub_ui(a.value, last.value, -istep)
407
else:
408
mpz_add(a.value, last.value, zstep.value)
409
PyList_Append(L, last)
410
sig_off()
411
return L
412
413
def __iter__(self):
414
"""
415
Iterate over all integers. 0 1 -1 2 -2 3 -3 ...
416
417
EXAMPLES::
418
419
sage: for n in ZZ:
420
... if n < 3: print n
421
... else: break
422
0
423
1
424
-1
425
2
426
-2
427
"""
428
return integer_ring_python.iterator(self)
429
430
cdef Integer _coerce_ZZ(self, ZZ_c *z):
431
cdef integer.Integer i
432
i = PY_NEW(integer.Integer)
433
sig_on()
434
ZZ_to_mpz(&i.value, z)
435
sig_off()
436
return i
437
438
cpdef _coerce_map_from_(self, S):
439
"""
440
x canonically coerces to the integers ZZ only if x is an int,
441
long or already an element of ZZ.
442
443
EXAMPLES::
444
445
sage: ZZ.coerce(int(5))
446
5
447
sage: ZZ.coerce(GF(7)(2))
448
Traceback (most recent call last):
449
...
450
TypeError: no canonical coercion from Finite Field of size 7 to Integer Ring
451
452
The rational number 3/1 = 3 does not canonically coerce into the
453
integers, since there is no canonical coercion map from the full
454
field of rational numbers to the integers.
455
456
::
457
458
sage: a = 3/1; parent(a)
459
Rational Field
460
sage: ZZ(a)
461
3
462
sage: ZZ.coerce(a)
463
Traceback (most recent call last):
464
...
465
TypeError: no canonical coercion from Rational Field to Integer Ring
466
467
TESTS::
468
469
sage: 5r + True
470
6
471
sage: 5 + True
472
6
473
474
sage: f = ZZ.coerce_map_from(int); f
475
Native morphism:
476
From: Set of Python objects of type 'int'
477
To: Integer Ring
478
sage: f(4r)
479
4
480
sage: f(-7r)
481
-7
482
483
Note that the input MUST be an int.
484
485
::
486
487
sage: a = 10000000000000000000000r
488
sage: type(a)
489
<type 'long'>
490
sage: f(a) # random
491
5
492
"""
493
if S is int:
494
return sage.rings.integer.int_to_Z()
495
elif S is long:
496
return sage.rings.integer.long_to_Z()
497
elif S is bool:
498
return True
499
else:
500
None
501
502
503
def is_subring(self, other):
504
"""
505
Return True if ZZ is a subring of other in a natural way.
506
507
Every ring of characteristic 0 contains ZZ as a subring.
508
509
EXAMPLES::
510
511
sage: ZZ.is_subring(QQ)
512
True
513
"""
514
if not ring.is_Ring(other):
515
raise TypeError, "other must be a ring"
516
if other.characteristic() == 0:
517
return True
518
else:
519
return False
520
521
def random_element(self, x=None, y=None, distribution=None):
522
r"""
523
Return a random integer.
524
525
ZZ.random_element()
526
return an integer using the default
527
distribution described below
528
ZZ.random_element(n)
529
return an
530
integer uniformly distributed between 0 and n-1, inclusive.
531
ZZ.random_element(min, max)
532
return an integer uniformly
533
distributed between min and max-1, inclusive.
534
535
The default distribution for ZZ.random_element() is based on
536
`X = \mbox{trunc}(4/(5R))`, where `R` is a random
537
variable uniformly distributed between -1 and 1. This gives
538
`\mbox{Pr}(X = 0) = 1/5`, and
539
`\mbox{Pr}(X = n) = 2/(5|n|(|n|+1))` for
540
`n \neq 0`. Most of the samples will be small; -1, 0, and 1
541
occur with probability 1/5 each. But we also have a small but
542
non-negligible proportion of "outliers";
543
`\mbox{Pr}(|X| \geq n) = 4/(5n)`, so for instance, we
544
expect that `|X| \geq 1000` on one in 1250 samples.
545
546
We actually use an easy-to-compute truncation of the above
547
distribution; the probabilities given above hold fairly well up to
548
about `|n| = 10000`, but around `|n| = 30000` some
549
values will never be returned at all, and we will never return
550
anything greater than `2^{30}`.
551
552
EXAMPLES:
553
554
The default distribution is on average 50% `\pm 1`
555
556
::
557
558
sage: [ZZ.random_element() for _ in range(10)]
559
[-8, 2, 0, 0, 1, -1, 2, 1, -95, -1]
560
561
The default uniform distribution is integers between -2 and 2
562
inclusive::
563
564
sage: [ZZ.random_element(distribution="uniform") for _ in range(10)]
565
[2, -2, 2, -2, -1, 1, -1, 2, 1, 0]
566
567
Here we use the distribution `1/n`::
568
569
sage: [ZZ.random_element(distribution="1/n") for _ in range(10)]
570
[-6, 1, -1, 1, 1, -1, 1, -1, -3, 1]
571
572
573
If a range is given, the distribution is uniform in that range::
574
575
sage: ZZ.random_element(-10,10)
576
-2
577
sage: ZZ.random_element(10)
578
2
579
sage: ZZ.random_element(10^50)
580
9531604786291536727294723328622110901973365898988
581
sage: [ZZ.random_element(5) for _ in range(10)]
582
[3, 1, 2, 3, 0, 0, 3, 4, 0, 3]
583
584
Notice that the right endpoint is not included::
585
586
sage: [ZZ.random_element(-2,2) for _ in range(10)]
587
[1, -2, -2, -1, -2, -1, -1, -2, 0, -2]
588
589
We compute a histogram over 1000 samples of the default
590
distribution::
591
592
sage: from collections import defaultdict
593
sage: d = defaultdict(lambda: 0)
594
sage: for _ in range(1000):
595
... samp = ZZ.random_element()
596
... d[samp] = d[samp] + 1
597
598
sage: sorted(d.items())
599
[(-1955, 1), (-1026, 1), (-357, 1), (-248, 1), (-145, 1), (-81, 1), (-80, 1), (-79, 1), (-75, 1), (-69, 1), (-68, 1), (-63, 2), (-61, 1), (-57, 1), (-50, 1), (-37, 1), (-35, 1), (-33, 1), (-29, 2), (-27, 1), (-25, 1), (-23, 2), (-22, 3), (-20, 1), (-19, 1), (-18, 1), (-16, 4), (-15, 3), (-14, 1), (-13, 2), (-12, 2), (-11, 2), (-10, 7), (-9, 3), (-8, 3), (-7, 7), (-6, 8), (-5, 13), (-4, 24), (-3, 34), (-2, 75), (-1, 206), (0, 208), (1, 189), (2, 63), (3, 35), (4, 13), (5, 11), (6, 10), (7, 4), (8, 3), (10, 1), (11, 1), (12, 1), (13, 1), (14, 1), (16, 3), (18, 2), (19, 1), (26, 2), (27, 1), (28, 2), (29, 1), (30, 1), (32, 1), (33, 2), (35, 1), (37, 1), (39, 1), (41, 1), (42, 1), (52, 1), (91, 1), (94, 1), (106, 1), (111, 1), (113, 2), (132, 1), (134, 1), (232, 1), (240, 1), (2133, 1), (3636, 1)]
600
"""
601
cdef integer.Integer z
602
z = <integer.Integer>PY_NEW(integer.Integer)
603
if x is not None and y is None and x <= 0:
604
raise TypeError, "x must be > 0"
605
if x is not None and y is not None and x >= y:
606
raise TypeError, "x must be < y"
607
self._randomize_mpz(z.value, x, y, distribution)
608
return z
609
610
cdef int _randomize_mpz(self, mpz_t value, x, y, distribution) except -1:
611
cdef integer.Integer n_max, n_min, n_width
612
cdef randstate rstate = current_randstate()
613
cdef int den = rstate.c_random()-SAGE_RAND_MAX/2
614
if den == 0: den = 1
615
if (distribution is None and x is None) or distribution == "1/n":
616
mpz_set_si(value, (SAGE_RAND_MAX/5*2) / den)
617
elif distribution is None or distribution == "uniform":
618
if y is None:
619
if x is None:
620
mpz_set_si(value, rstate.c_random()%5 - 2)
621
else:
622
n_max = x if PY_TYPE_CHECK(x, integer.Integer) else self(x)
623
mpz_urandomm(value, rstate.gmp_state, n_max.value)
624
else:
625
n_min = x if PY_TYPE_CHECK(x, integer.Integer) else self(x)
626
n_max = y if PY_TYPE_CHECK(y, integer.Integer) else self(y)
627
n_width = n_max - n_min
628
if mpz_sgn(n_width.value) <= 0:
629
n_min = self(-2)
630
n_width = self(5)
631
mpz_urandomm(value, rstate.gmp_state, n_width.value)
632
mpz_add(value, value, n_min.value)
633
elif distribution == "mpz_rrandomb":
634
if x is None:
635
raise ValueError("must specify x to use 'distribution=mpz_rrandomb'")
636
mpz_rrandomb(value, rstate.gmp_state, int(x))
637
else:
638
raise ValueError, "Unknown distribution for the integers: %s"%distribution
639
640
def _is_valid_homomorphism_(self, codomain, im_gens):
641
try:
642
return im_gens[0] == codomain.coerce(self.gen(0))
643
except TypeError:
644
return False
645
646
def is_noetherian(self):
647
"""
648
Return True - the integers are a Noetherian ring.
649
650
EXAMPLES::
651
652
sage: ZZ.is_noetherian()
653
True
654
"""
655
return True
656
657
def is_atomic_repr(self):
658
"""
659
Return True, since elements of the integers do not have to be
660
printed with parentheses around them, when they are coefficients,
661
e.g., in a polynomial.
662
663
EXAMPLE::
664
665
sage: ZZ.is_atomic_repr()
666
True
667
"""
668
return True
669
670
def is_field(self, proof = True):
671
"""
672
Return False - the integers are not a field.
673
674
EXAMPLES::
675
676
sage: ZZ.is_field()
677
False
678
"""
679
return False
680
681
def is_finite(self):
682
"""
683
Return False - the integers are an infinite ring.
684
685
EXAMPLES::
686
687
sage: ZZ.is_finite()
688
False
689
"""
690
return False
691
692
def fraction_field(self):
693
"""
694
Returns the field of rational numbers - the fraction field of the
695
integers.
696
697
EXAMPLES::
698
699
sage: ZZ.fraction_field()
700
Rational Field
701
sage: ZZ.fraction_field() == QQ
702
True
703
"""
704
return sage.rings.rational_field.Q
705
706
def extension(self, poly, names=None, embedding=None):
707
"""
708
Returns the order in the number field defined by poly generated (as
709
a ring) by a root of poly.
710
711
EXAMPLES::
712
713
sage: ZZ.extension(x^2-5, 'a')
714
Order in Number Field in a with defining polynomial x^2 - 5
715
sage: ZZ.extension([x^2 + 1, x^2 + 2], 'a,b')
716
Relative Order in Number Field in a with defining polynomial x^2 + 1 over its base field
717
"""
718
if embedding is not None:
719
if embedding!=[None]*len(embedding):
720
raise NotImplementedError
721
from sage.rings.number_field.order import EquationOrder
722
return EquationOrder(poly, names)
723
724
def quotient(self, I, names=None):
725
r"""
726
Return the quotient of `\ZZ` by the ideal
727
`I` or integer `I`.
728
729
EXAMPLES::
730
731
sage: ZZ.quo(6*ZZ)
732
Ring of integers modulo 6
733
sage: ZZ.quo(0*ZZ)
734
Integer Ring
735
sage: ZZ.quo(3)
736
Ring of integers modulo 3
737
sage: ZZ.quo(3*QQ)
738
Traceback (most recent call last):
739
...
740
TypeError: I must be an ideal of ZZ
741
"""
742
if isinstance(I, sage.rings.integer.Integer):
743
n = I
744
elif sage.rings.ideal.is_Ideal(I):
745
if not (I.ring() is self):
746
raise TypeError, "I must be an ideal of ZZ"
747
n = I.gens()[0]
748
else:
749
raise TypeError, "I must be an ideal of ZZ or an integer"
750
if n == 0:
751
return self
752
return sage.rings.finite_rings.integer_mod_ring.IntegerModRing(n)
753
754
def residue_field(self, prime, check = True):
755
"""
756
Return the residue field of the integers modulo the given prime, ie
757
`\ZZ/p\ZZ`.
758
759
INPUT:
760
761
762
- ``prime`` - a prime number
763
764
- ``check`` - (boolean, default True) whether or not
765
to check the primality of prime.
766
767
768
OUTPUT: The residue field at this prime.
769
770
EXAMPLES::
771
772
sage: F = ZZ.residue_field(61); F
773
Residue field of Integers modulo 61
774
sage: pi = F.reduction_map(); pi
775
Partially defined reduction map:
776
From: Rational Field
777
To: Residue field of Integers modulo 61
778
sage: pi(123/234)
779
6
780
sage: pi(1/61)
781
Traceback (most recent call last):
782
...
783
ZeroDivisionError: Cannot reduce rational 1/61 modulo 61: it has negative valuation
784
sage: lift = F.lift_map(); lift
785
Lifting map:
786
From: Residue field of Integers modulo 61
787
To: Integer Ring
788
sage: lift(F(12345/67890))
789
33
790
sage: (12345/67890) % 61
791
33
792
793
Construction can be from a prime ideal instead of a prime::
794
795
sage: ZZ.residue_field(ZZ.ideal(97))
796
Residue field of Integers modulo 97
797
798
TESTS::
799
800
sage: ZZ.residue_field(ZZ.ideal(96))
801
Traceback (most recent call last):
802
...
803
TypeError: Principal ideal (96) of Integer Ring is not prime
804
sage: ZZ.residue_field(96)
805
Traceback (most recent call last):
806
...
807
TypeError: 96 is not prime
808
"""
809
if isinstance(prime, sage.rings.integer.Integer):
810
p = self.ideal(prime)
811
elif sage.rings.ideal.is_Ideal(prime):
812
if not (prime.ring() is self):
813
raise TypeError, "%s is not an ideal of ZZ"%prime
814
p = prime
815
else:
816
raise TypeError, "%s is neither an ideal of ZZ nor an integer"%prime
817
if check and not p.is_prime():
818
raise TypeError, "%s is not prime"%prime
819
from sage.rings.residue_field import ResidueField
820
return ResidueField(p, names = None, check = check)
821
822
def gens(self):
823
"""
824
Returns the tuple (1,) containing a single element, the additive
825
generator of the integers, which is 1.
826
827
EXAMPLES::
828
829
sage: ZZ.gens(); ZZ.gens()[0]
830
(1,)
831
1
832
sage: type(ZZ.gens()[0])
833
<type 'sage.rings.integer.Integer'>
834
"""
835
return (self(1), )
836
837
def gen(self, n=0):
838
"""
839
Returns the additive generator of the integers, which is 1.
840
841
EXAMPLES::
842
843
sage: ZZ.gen()
844
1
845
sage: type(ZZ.gen())
846
<type 'sage.rings.integer.Integer'>
847
"""
848
if n == 0:
849
return self(1)
850
else:
851
raise IndexError, "n must be 0"
852
853
def ngens(self):
854
"""
855
Returns the number of additive generators of the ring, which is 1.
856
857
EXAMPLES::
858
859
sage: ZZ.ngens()
860
1
861
sage: len(ZZ.gens())
862
1
863
"""
864
return 1
865
866
def degree(self):
867
"""
868
Return the degree of the integers, which is 1
869
870
EXAMPLE::
871
872
sage: ZZ.degree()
873
1
874
"""
875
return 1
876
877
def absolute_degree(self):
878
"""
879
Return the absolute degree of the integers, which is 1
880
881
EXAMPLE::
882
883
sage: ZZ.absolute_degree()
884
1
885
"""
886
return 1
887
888
def characteristic(self):
889
"""
890
Return the characteristic of the integers, which is 0.
891
892
EXAMPLE::
893
894
sage: ZZ.characteristic()
895
0
896
"""
897
return ZZ.zero()
898
899
def krull_dimension(self):
900
"""
901
Return the Krull dimension of the integers, which is 1.
902
903
EXAMPLE::
904
905
sage: ZZ.krull_dimension()
906
1
907
"""
908
return 1
909
910
def is_integrally_closed(self):
911
"""
912
Returns that the integer ring is, in fact, an
913
integrally closed ring.
914
915
EXAMPLE::
916
917
sage: ZZ.is_integrally_closed()
918
True
919
"""
920
return True
921
922
def completion(self, p, prec, extras = {}):
923
"""
924
Returns the completion of Z at p.
925
926
EXAMPLES::
927
928
sage: ZZ.completion(infinity, 53)
929
Real Field with 53 bits of precision
930
sage: ZZ.completion(5, 15, {'print_mode': 'bars'})
931
5-adic Ring with capped relative precision 15
932
"""
933
if p == sage.rings.infinity.Infinity:
934
from sage.rings.real_mpfr import create_RealField
935
return create_RealField(prec, **extras)
936
else:
937
from sage.rings.padics.factory import Zp
938
return Zp(p, prec, **extras)
939
940
941
942
def order(self):
943
"""
944
Return the order (cardinality) of the integers, which is
945
+Infinity.
946
947
EXAMPLE::
948
949
sage: ZZ.order()
950
+Infinity
951
"""
952
return sage.rings.infinity.infinity
953
954
def zeta(self, n=2):
955
"""
956
Return a primitive n'th root of unity in the integers, or raise an
957
error if none exists
958
959
INPUT:
960
961
962
- ``n`` - a positive integer (default 2)
963
964
965
OUTPUT: an n'th root of unity in ZZ
966
967
EXAMPLE::
968
969
sage: ZZ.zeta()
970
-1
971
sage: ZZ.zeta(1)
972
1
973
sage: ZZ.zeta(3)
974
Traceback (most recent call last):
975
...
976
ValueError: no nth root of unity in integer ring
977
sage: ZZ.zeta(0)
978
Traceback (most recent call last):
979
...
980
ValueError: n must be positive in zeta()
981
"""
982
if n == 1:
983
return sage.rings.integer.Integer(1)
984
elif n == 2:
985
return sage.rings.integer.Integer(-1)
986
elif n < 1:
987
raise ValueError, "n must be positive in zeta()"
988
else:
989
raise ValueError, "no nth root of unity in integer ring"
990
991
def parameter(self):
992
"""
993
Returns an integer of degree 1 for the Euclidean property of ZZ,
994
namely 1.
995
996
EXAMPLES::
997
998
sage: ZZ.parameter()
999
1
1000
"""
1001
return self(1)
1002
1003
1004
1005
1006
#################################
1007
## Coercions to interfaces
1008
#################################
1009
def _gap_init_(self):
1010
"""
1011
EXAMPLES::
1012
1013
sage: gap(ZZ)
1014
Integers
1015
"""
1016
return 'Integers'
1017
1018
def _magma_init_(self, magma):
1019
"""
1020
EXAMPLES::
1021
1022
sage: magma(ZZ) # optional - magma
1023
Integer Ring
1024
"""
1025
return 'IntegerRing()'
1026
1027
def _macaulay2_init_(self):
1028
"""
1029
EXAMPLES::
1030
1031
sage: macaulay2(ZZ) #optional - macaulay2
1032
ZZ
1033
"""
1034
return "ZZ"
1035
1036
def _sage_input_(self, sib, coerced):
1037
r"""
1038
Produce an expression which will reproduce this value when
1039
evaluated.
1040
1041
EXAMPLES::
1042
1043
sage: sage_input(ZZ, verify=True)
1044
# Verified
1045
ZZ
1046
sage: from sage.misc.sage_input import SageInputBuilder
1047
sage: ZZ._sage_input_(SageInputBuilder(), False)
1048
{atomic:ZZ}
1049
"""
1050
return sib.name('ZZ')
1051
1052
ZZ = IntegerRing_class()
1053
Z = ZZ
1054
1055
def IntegerRing():
1056
"""
1057
Return the integer ring
1058
1059
EXAMPLE::
1060
1061
sage: IntegerRing()
1062
Integer Ring
1063
sage: ZZ==IntegerRing()
1064
True
1065
"""
1066
return ZZ
1067
1068
def factor(*args, **kwds):
1069
"""
1070
This function is deprecated. To factor an Integer `n`, call `n.factor()`.
1071
For other objects, use the factor method from sage.rings.arith.
1072
1073
EXAMPLE::
1074
1075
sage: sage.rings.integer_ring.factor(1)
1076
doctest:...: DeprecationWarning: This function is deprecated...
1077
1
1078
"""
1079
from sage.misc.misc import deprecation
1080
deprecation("This function is deprecated. Call the factor method of an Integer,"
1081
+"or sage.arith.factor instead.")
1082
#deprecated 4.6.2
1083
1084
late_import()
1085
return arith.factor(*args, **kwds)
1086
1087
import sage.misc.misc
1088
def crt_basis(X, xgcd=None):
1089
"""
1090
Compute and return a Chinese Remainder Theorem basis for the list X
1091
of coprime integers.
1092
1093
INPUT:
1094
1095
1096
- ``X`` - a list of Integers that are coprime in
1097
pairs
1098
1099
1100
OUTPUT:
1101
1102
1103
- ``E`` - a list of Integers such that E[i] = 1 (mod
1104
X[i]) and E[i] = 0 (mod X[j]) for all j!=i.
1105
1106
1107
The E[i] have the property that if A is a list of objects, e.g.,
1108
integers, vectors, matrices, etc., where A[i] is moduli X[i], then
1109
a CRT lift of A is simply
1110
1111
sum E[i] \* A[i].
1112
1113
ALGORITHM: To compute E[i], compute integers s and t such that
1114
1115
s \* X[i] + t \* (prod over i!=j of X[j]) = 1. (\*)
1116
1117
Then E[i] = t \* (prod over i!=j of X[j]). Notice that equation
1118
(\*) implies that E[i] is congruent to 1 modulo X[i] and to 0
1119
modulo the other X[j] for j!=i.
1120
1121
COMPLEXITY: We compute len(X) extended GCD's.
1122
1123
EXAMPLES::
1124
1125
sage: X = [11,20,31,51]
1126
sage: E = crt_basis([11,20,31,51])
1127
sage: E[0]%X[0]; E[1]%X[0]; E[2]%X[0]; E[3]%X[0]
1128
1
1129
0
1130
0
1131
0
1132
sage: E[0]%X[1]; E[1]%X[1]; E[2]%X[1]; E[3]%X[1]
1133
0
1134
1
1135
0
1136
0
1137
sage: E[0]%X[2]; E[1]%X[2]; E[2]%X[2]; E[3]%X[2]
1138
0
1139
0
1140
1
1141
0
1142
sage: E[0]%X[3]; E[1]%X[3]; E[2]%X[3]; E[3]%X[3]
1143
0
1144
0
1145
0
1146
1
1147
"""
1148
if not isinstance(X, list):
1149
raise TypeError, "X must be a list"
1150
if len(X) == 0:
1151
return []
1152
1153
P = sage.misc.misc.prod(X)
1154
1155
Y = []
1156
# 2. Compute extended GCD's
1157
ONE=X[0].parent()(1)
1158
for i in range(len(X)):
1159
p = X[i]
1160
prod = P//p
1161
g,s,t = p.xgcd(prod)
1162
if g != ONE:
1163
raise ArithmeticError, "The elements of the list X must be coprime in pairs."
1164
Y.append(t*prod)
1165
return Y
1166
1167