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