Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemath
GitHub Repository: sagemath/sagesmc
Path: blob/master/src/sage/rings/integer.pyx
8817 views
1
r"""
2
Elements of the ring `\ZZ` of integers
3
4
AUTHORS:
5
6
- William Stein (2005): initial version
7
8
- Gonzalo Tornaria (2006-03-02): vastly improved python/GMP
9
conversion; hashing
10
11
- Didier Deshommes (2006-03-06): numerous examples
12
and docstrings
13
14
- William Stein (2006-03-31): changes to reflect GMP bug fixes
15
16
- William Stein (2006-04-14): added GMP factorial method (since it's
17
now very fast).
18
19
- David Harvey (2006-09-15): added nth_root, exact_log
20
21
- David Harvey (2006-09-16): attempt to optimise Integer constructor
22
23
- Rishikesh (2007-02-25): changed quo_rem so that the rem is positive
24
25
- David Harvey, Martin Albrecht, Robert Bradshaw (2007-03-01):
26
optimized Integer constructor and pool
27
28
- Pablo De Napoli (2007-04-01): multiplicative_order should return
29
+infinity for non zero numbers
30
31
- Robert Bradshaw (2007-04-12): is_perfect_power, Jacobi symbol (with
32
Kronecker extension). Convert some methods to use GMP directly
33
rather than PARI, Integer(), PY_NEW(Integer)
34
35
- David Roe (2007-03-21): sped up valuation and is_square, added
36
val_unit, is_power, is_power_of and divide_knowing_divisible_by
37
38
- Robert Bradshaw (2008-03-26): gamma function, multifactorials
39
40
- Robert Bradshaw (2008-10-02): bounded squarefree part
41
42
- David Loeffler (2011-01-15): fixed bug #10625 (inverse_mod should accept an ideal as argument)
43
44
- Vincent Delecroix (2010-12-28): added unicode in Integer.__init__
45
46
- David Roe (2012-03): deprecate :meth:`~sage.rings.integer.Integer.is_power`
47
in favour of :meth:`~sage.rings.integer.Integer.is_perfect_power` (see
48
:trac:`12116`)
49
50
EXAMPLES:
51
52
Add 2 integers::
53
54
sage: a = Integer(3) ; b = Integer(4)
55
sage: a + b == 7
56
True
57
58
Add an integer and a real number::
59
60
sage: a + 4.0
61
7.00000000000000
62
63
Add an integer and a rational number::
64
65
sage: a + Rational(2)/5
66
17/5
67
68
Add an integer and a complex number::
69
70
sage: b = ComplexField().0 + 1.5
71
sage: loads((a+b).dumps()) == a+b
72
True
73
74
sage: z = 32
75
sage: -z
76
-32
77
sage: z = 0; -z
78
0
79
sage: z = -0; -z
80
0
81
sage: z = -1; -z
82
1
83
84
Multiplication::
85
86
sage: a = Integer(3) ; b = Integer(4)
87
sage: a * b == 12
88
True
89
sage: loads((a * 4.0).dumps()) == a*b
90
True
91
sage: a * Rational(2)/5
92
6/5
93
94
::
95
96
sage: list([2,3]) * 4
97
[2, 3, 2, 3, 2, 3, 2, 3]
98
99
::
100
101
sage: 'sage'*Integer(3)
102
'sagesagesage'
103
104
COERCIONS:
105
106
Returns version of this integer in the multi-precision floating
107
real field R::
108
109
sage: n = 9390823
110
sage: RR = RealField(200)
111
sage: RR(n)
112
9.3908230000000000000000000000000000000000000000000000000000e6
113
114
"""
115
#*****************************************************************************
116
# Copyright (C) 2004,2006 William Stein <[email protected]>
117
# Copyright (C) 2006 Gonzalo Tornaria <[email protected]>
118
# Copyright (C) 2006 Didier Deshommes <[email protected]>
119
# Copyright (C) 2007 David Harvey <[email protected]>
120
# Copyright (C) 2007 Martin Albrecht <[email protected]>
121
# Copyright (C) 2007,2008 Robert Bradshaw <[email protected]>
122
# Copyright (C) 2007 David Roe <[email protected]>
123
#
124
# Distributed under the terms of the GNU General Public License (GPL)
125
# as published by the Free Software Foundation; either version 2 of
126
# the License, or (at your option) any later version.
127
# http://www.gnu.org/licenses/
128
#*****************************************************************************
129
130
# Do not create any Integer, especially non cdef'ed ones, before the hooked
131
# creation and deletion are setup by the call to hook_fast_tp_functions
132
133
doc="""
134
Integers
135
"""
136
137
import cython
138
139
import operator
140
141
import sys
142
143
include "sage/ext/gmp.pxi"
144
include "sage/ext/interrupt.pxi" # ctrl-c interrupt block support
145
include "sage/ext/stdsage.pxi"
146
from cpython.list cimport *
147
from cpython.number cimport *
148
from cpython.int cimport *
149
include "sage/ext/python_debug.pxi"
150
include "../structure/coerce.pxi" # for parent_c
151
include "sage/libs/pari/decl.pxi"
152
153
cdef extern from "limits.h":
154
long LONG_MAX
155
156
cdef extern from "math.h":
157
double sqrt_double "sqrt"(double)
158
cdef double log_c "log" (double)
159
cdef double ceil_c "ceil" (double)
160
int isnan(double)
161
162
cdef extern from "mpz_pylong.h":
163
cdef mpz_get_pylong(mpz_t src)
164
cdef mpz_get_pyintlong(mpz_t src)
165
cdef int mpz_set_pylong(mpz_t dst, src) except -1
166
cdef long mpz_pythonhash(mpz_t src)
167
168
cdef extern from "mpz_longlong.h":
169
cdef void mpz_set_longlong(mpz_t dst, long long src)
170
cdef void mpz_set_ulonglong(mpz_t dst, unsigned long long src)
171
172
cdef extern from "convert.h":
173
cdef void t_INT_to_ZZ( mpz_t value, long *g )
174
175
from sage.libs.pari.gen cimport gen as pari_gen
176
from sage.libs.pari.pari_instance cimport PariInstance
177
from sage.libs.flint.ulong_extras cimport *
178
179
import sage.rings.infinity
180
181
import sage.libs.pari.pari_instance
182
cdef PariInstance pari = sage.libs.pari.pari_instance.pari
183
184
from sage.structure.element import canonical_coercion, coerce_binop
185
from sage.misc.superseded import deprecated_function_alias
186
187
cdef object numpy_long_interface = {'typestr': '=i4' if sizeof(long) == 4 else '=i8' }
188
cdef object numpy_int64_interface = {'typestr': '=i8'}
189
cdef object numpy_object_interface = {'typestr': '|O'}
190
191
cdef mpz_t mpz_tmp
192
mpz_init(mpz_tmp)
193
194
def init_mpz_globals():
195
init_mpz_globals_c()
196
197
def clear_mpz_globals():
198
clear_mpz_globals_c()
199
200
cdef int set_mpz(Integer self, mpz_t value):
201
mpz_set(self.value, value)
202
203
cdef set_from_Integer(Integer self, Integer other):
204
mpz_set(self.value, other.value)
205
206
cdef set_from_int(Integer self, int other):
207
mpz_set_si(self.value, other)
208
209
cdef mpz_t* get_value(Integer self):
210
return &self.value
211
212
213
def _test_mpz_set_longlong(long long v):
214
"""
215
TESTS::
216
217
sage: from sage.rings.integer import _test_mpz_set_longlong
218
sage: _test_mpz_set_longlong(1)
219
1
220
sage: _test_mpz_set_longlong(-1)
221
-1
222
sage: _test_mpz_set_longlong(100)
223
100
224
sage: _test_mpz_set_longlong(100000000000)
225
100000000000
226
sage: _test_mpz_set_longlong(2^32) == 2^32
227
True
228
sage: _test_mpz_set_longlong(-2^32) == -2^32
229
True
230
sage: all([_test_mpz_set_longlong(2^n) == 2^n for n in range(63)])
231
True
232
"""
233
cdef Integer z = PY_NEW(Integer)
234
mpz_set_longlong(z.value, v)
235
return z
236
237
cdef _digits_naive(mpz_t v,l,int offset,Integer base,digits):
238
"""
239
This method fills in digit entries in the list, l, using the most
240
basic digit algorithm -- repeat division by base.
241
242
INPUT:
243
244
- ``v`` - the value whose digits we want to put into the list
245
246
- ``l`` - the list to file
247
248
- ``offset`` - offset from the beginning of the list that we want
249
to fill at
250
251
- ``base`` -- the base to which we finding digits
252
253
- ``digits`` - a python sequence type with objects to use for digits
254
note that python negative index semantics are relied upon
255
256
AUTHORS:
257
258
- Joel B. Mohler (2009-01-16)
259
"""
260
cdef mpz_t mpz_value
261
cdef mpz_t mpz_res # used on one side of the 'if'
262
cdef Integer z # used on the other side of the 'if'
263
264
mpz_init(mpz_value)
265
mpz_set(mpz_value, v)
266
267
# we aim to avoid sage Integer creation if possible
268
if digits is None:
269
while mpz_cmp_si(mpz_value,0):
270
z = PY_NEW(Integer)
271
mpz_tdiv_qr(mpz_value, z.value, mpz_value, base.value)
272
l[offset] = z
273
offset += 1
274
else:
275
mpz_init(mpz_res)
276
while mpz_cmp_si(mpz_value,0):
277
mpz_tdiv_qr(mpz_value, mpz_res, mpz_value, base.value)
278
l[offset] = digits[mpz_get_si(mpz_res)]
279
offset += 1
280
mpz_clear(mpz_res)
281
282
mpz_clear(mpz_value)
283
284
cdef _digits_internal(mpz_t v,l,int offset,int power_index,power_list,digits):
285
"""
286
INPUT:
287
288
- ``v`` - the value whose digits we want to put into the list
289
290
- ``l`` - the list to file
291
292
- ``offset`` - offset from the beginning of the list that we want
293
to fill at
294
295
- ``power_index`` - a measure of size to fill and index to
296
power_list we're filling 1 << (power_index+1) digits
297
298
- ``power_list`` - a list of powers of the base, precomputed in
299
method digits digits - a python sequence type with objects to
300
use for digits note that python negative index semantics are
301
relied upon
302
303
AUTHORS:
304
305
- Joel B. Mohler (2008-03-13)
306
"""
307
cdef mpz_t mpz_res
308
cdef mpz_t mpz_quot
309
cdef Integer temp
310
cdef int v_int
311
if power_index < 5:
312
# It turns out that simple repeated division is very fast for
313
# relatively few digits. I don't think this is a real algorithmic
314
# statement, it's an annoyance introduced by memory allocation.
315
# I think that manual memory management with mpn_* would make the
316
# divide & conquer approach even faster, but the code would be much
317
# more complicated.
318
_digits_naive(v,l,offset,power_list[0],digits)
319
else:
320
mpz_init(mpz_quot)
321
mpz_init(mpz_res)
322
temp = power_list[power_index]
323
mpz_tdiv_qr(mpz_quot, mpz_res, v, temp.value)
324
if mpz_sgn(mpz_res) != 0:
325
_digits_internal(mpz_res,l,offset,power_index-1,power_list,digits)
326
if mpz_sgn(mpz_quot) != 0:
327
_digits_internal(mpz_quot,l,offset+(1<<power_index),power_index-1,power_list,digits)
328
mpz_clear(mpz_quot)
329
mpz_clear(mpz_res)
330
331
arith = None
332
cdef void late_import():
333
global arith
334
if arith is None:
335
import sage.rings.arith
336
arith = sage.rings.arith
337
338
MAX_UNSIGNED_LONG = 2 * sys.maxint
339
340
from sage.structure.sage_object cimport SageObject
341
from sage.structure.element cimport EuclideanDomainElement, ModuleElement, Element
342
from sage.structure.element import bin_op
343
from sage.structure.coerce_exceptions import CoercionException
344
345
import integer_ring
346
the_integer_ring = integer_ring.ZZ
347
348
# The documentation for the ispseudoprime() function in the PARI
349
# manual states that its result is always prime up to this 10^13.
350
cdef mpz_t PARI_PSEUDOPRIME_LIMIT
351
mpz_init(PARI_PSEUDOPRIME_LIMIT)
352
mpz_set_str(PARI_PSEUDOPRIME_LIMIT, "10000000000000", 10)
353
354
def is_Integer(x):
355
"""
356
Return true if x is of the Sage integer type.
357
358
EXAMPLES::
359
360
sage: from sage.rings.integer import is_Integer
361
sage: is_Integer(2)
362
True
363
sage: is_Integer(2/1)
364
False
365
sage: is_Integer(int(2))
366
False
367
sage: is_Integer(long(2))
368
False
369
sage: is_Integer('5')
370
False
371
"""
372
return PY_TYPE_CHECK(x, Integer)
373
374
cdef inline Integer as_Integer(x):
375
if PY_TYPE_CHECK(x, Integer):
376
return <Integer>x
377
else:
378
return Integer(x)
379
380
cdef class IntegerWrapper(Integer):
381
r"""
382
Rationale for the ``IntegerWrapper`` class:
383
384
With ``Integers``, the allocation/deallocation function slots are
385
hijacked with custom functions that stick already allocated
386
``Integers`` (with initialized ``parent`` and ``mpz_t`` fields)
387
into a pool on "deallocation" and then pull them out whenever a
388
new one is needed. Because ``Integers`` are so common, this is
389
actually a significant savings. However , this does cause issues
390
with subclassing a Python class directly from ``Integer`` (but
391
that's ok for a Cython class).
392
393
As a workaround, one can instead derive a class from the
394
intermediate class ``IntegerWrapper``, which sets statically its
395
alloc/dealloc methods to the *original* ``Integer`` alloc/dealloc
396
methods, before they are swapped manually for the custom ones.
397
398
The constructor of ``IntegerWrapper`` further allows for
399
specifying an alternative parent to ``IntegerRing()``.
400
"""
401
402
def __init__(self, parent=None, x=None, unsigned int base=0):
403
"""
404
We illustrate how to create integers with parents different
405
from ``IntegerRing()``::
406
407
sage: from sage.rings.integer import IntegerWrapper
408
409
sage: n = IntegerWrapper(Primes(), 3) # indirect doctest
410
sage: n
411
3
412
sage: n.parent()
413
Set of all prime numbers: 2, 3, 5, 7, ...
414
415
Pickling seems to work now (as of #10314)
416
417
sage: nn = loads(dumps(n))
418
sage: nn
419
3
420
sage: nn.parent()
421
Integer Ring
422
423
sage: TestSuite(n).run()
424
"""
425
if parent is not None:
426
Element.__init__(self, parent=parent)
427
Integer.__init__(self, x, base=base)
428
429
cdef class Integer(sage.structure.element.EuclideanDomainElement):
430
r"""
431
The ``Integer`` class represents arbitrary precision
432
integers. It derives from the ``Element`` class, so
433
integers can be used as ring elements anywhere in Sage.
434
435
Integer() interprets numbers and strings that begin with 0 as octal
436
numbers, and numbers and strings that begin with 0x as hexadecimal
437
numbers.
438
439
The class ``Integer`` is implemented in Cython, as a
440
wrapper of the GMP ``mpz_t`` integer type.
441
442
EXAMPLES::
443
444
sage: Integer(010)
445
8
446
sage: Integer(0x10)
447
16
448
sage: Integer(10)
449
10
450
sage: Integer('0x12')
451
18
452
sage: Integer('012')
453
10
454
455
Conversion from PARI::
456
457
sage: Integer(pari('-10380104371593008048799446356441519384'))
458
-10380104371593008048799446356441519384
459
sage: Integer(pari('Pol([-3])'))
460
-3
461
"""
462
463
def __cinit__(self):
464
mpz_init(self.value)
465
self._parent = <SageObject>the_integer_ring
466
467
def __init__(self, x=None, base=0):
468
"""
469
EXAMPLES::
470
471
sage: a = long(-901824309821093821093812093810928309183091832091)
472
sage: b = ZZ(a); b
473
-901824309821093821093812093810928309183091832091
474
sage: ZZ(b)
475
-901824309821093821093812093810928309183091832091
476
sage: ZZ('-901824309821093821093812093810928309183091832091')
477
-901824309821093821093812093810928309183091832091
478
sage: ZZ(int(-93820984323))
479
-93820984323
480
sage: ZZ(ZZ(-901824309821093821093812093810928309183091832091))
481
-901824309821093821093812093810928309183091832091
482
sage: ZZ(QQ(-901824309821093821093812093810928309183091832091))
483
-901824309821093821093812093810928309183091832091
484
sage: ZZ(RR(2.0)^80)
485
1208925819614629174706176
486
sage: ZZ(QQbar(sqrt(28-10*sqrt(3)) + sqrt(3)))
487
5
488
sage: ZZ(AA(32).nth_root(5))
489
2
490
sage: ZZ(pari('Mod(-3,7)'))
491
4
492
sage: ZZ('sage')
493
Traceback (most recent call last):
494
...
495
TypeError: unable to convert x (=sage) to an integer
496
sage: Integer('zz',36).str(36)
497
'zz'
498
sage: ZZ('0x3b').str(16)
499
'3b'
500
sage: ZZ( ZZ(5).digits(3) , 3)
501
5
502
sage: import numpy
503
sage: ZZ(numpy.int64(7^7))
504
823543
505
sage: ZZ(numpy.ubyte(-7))
506
249
507
sage: ZZ(True)
508
1
509
sage: ZZ(False)
510
0
511
sage: ZZ(1==0)
512
0
513
sage: ZZ('+10')
514
10
515
516
::
517
518
sage: k = GF(2)
519
sage: ZZ( (k(0),k(1)), 2)
520
2
521
522
::
523
524
sage: ZZ(float(2.0))
525
2
526
sage: ZZ(float(1.0/0.0))
527
Traceback (most recent call last):
528
...
529
OverflowError: cannot convert float infinity to integer
530
sage: ZZ(float(0.0/0.0))
531
Traceback (most recent call last):
532
...
533
ValueError: cannot convert float NaN to integer
534
535
::
536
537
sage: class MyInt(int):
538
... pass
539
sage: class MyLong(long):
540
... pass
541
sage: class MyFloat(float):
542
... pass
543
sage: ZZ(MyInt(3))
544
3
545
sage: ZZ(MyLong(4))
546
4
547
sage: ZZ(MyFloat(5))
548
5
549
550
::
551
552
sage: Integer(u'0')
553
0
554
sage: Integer(u'0X2AEEF')
555
175855
556
557
Test conversion from PARI (#11685)::
558
559
sage: ZZ(pari(-3))
560
-3
561
sage: ZZ(pari("-3.0"))
562
-3
563
sage: ZZ(pari("-3.5"))
564
Traceback (most recent call last):
565
...
566
TypeError: Attempt to coerce non-integral real number to an Integer
567
sage: ZZ(pari("1e100"))
568
Traceback (most recent call last):
569
...
570
PariError: precision too low in truncr (precision loss in truncation)
571
sage: ZZ(pari("10^50"))
572
100000000000000000000000000000000000000000000000000
573
sage: ZZ(pari("Pol(3)"))
574
3
575
sage: ZZ(GF(3^20,'t')(1))
576
1
577
sage: ZZ(pari(GF(3^20,'t')(1)))
578
1
579
sage: x = polygen(QQ)
580
sage: K.<a> = NumberField(x^2+3)
581
sage: ZZ(a^2)
582
-3
583
sage: ZZ(pari(a)^2)
584
-3
585
sage: ZZ(pari("Mod(x, x^3+x+1)")) # Note error message refers to lifted element
586
Traceback (most recent call last):
587
...
588
TypeError: Unable to coerce PARI x to an Integer
589
590
Test coercion of p-adic with negative valuation::
591
592
sage: ZZ(pari(Qp(11)(11^-7)))
593
Traceback (most recent call last):
594
...
595
TypeError: Cannot convert p-adic with negative valuation to an integer
596
597
Test converting a list with a very large base::
598
599
sage: a=ZZ(randint(0,2^128-1))
600
sage: L = a.digits(2^64)
601
sage: a == sum([x * 2^(64*i) for i,x in enumerate(L)])
602
True
603
sage: a == ZZ(L,base=2^64)
604
True
605
"""
606
# TODO: All the code below should somehow be in an external
607
# cdef'd function. Then e.g., if a matrix or vector or
608
# polynomial is getting filled by mpz_t's, it can use the
609
# rules below to do the fill construction of mpz_t's, but
610
# without the overhead of creating any Python objects at all.
611
# The cdef's function should be of the form
612
# mpz_init_set_sage(mpz_t y, object x)
613
# Then this function becomes the one liner:
614
# mpz_init_set_sage(self.value, x)
615
616
cdef Integer tmp
617
cdef char* xs
618
cdef int paritype
619
cdef Py_ssize_t j
620
cdef object otmp
621
cdef unsigned int ibase
622
623
cdef Element lift
624
625
if x is None:
626
if mpz_sgn(self.value) != 0:
627
mpz_set_si(self.value, 0)
628
629
else:
630
# First do all the type-check versions; these are fast.
631
632
if PY_TYPE_CHECK(x, Integer):
633
set_from_Integer(self, <Integer>x)
634
635
elif PY_TYPE_CHECK(x, bool):
636
mpz_set_si(self.value, PyInt_AS_LONG(x))
637
638
elif PyInt_Check(x):
639
mpz_set_si(self.value, PyInt_AS_LONG(x))
640
641
elif PyLong_Check(x):
642
mpz_set_pylong(self.value, x)
643
644
elif PyFloat_Check(x):
645
n = long(x)
646
if n == x:
647
mpz_set_pylong(self.value, n)
648
else:
649
raise TypeError, "Cannot convert non-integral float to integer"
650
651
elif PY_TYPE_CHECK(x, pari_gen):
652
# Simplify and lift until we get an integer
653
while typ((<pari_gen>x).g) != t_INT:
654
x = x.simplify()
655
paritype = typ((<pari_gen>x).g)
656
if paritype == t_INT:
657
break
658
elif paritype == t_REAL:
659
# Check that the fractional part is zero
660
if not x.frac().gequal0():
661
raise TypeError, "Attempt to coerce non-integral real number to an Integer"
662
# floor yields an integer
663
x = x.floor()
664
break
665
elif paritype == t_PADIC:
666
if x._valp() < 0:
667
raise TypeError("Cannot convert p-adic with negative valuation to an integer")
668
# Lifting a PADIC yields an integer
669
x = x.lift()
670
break
671
elif paritype == t_INTMOD:
672
# Lifting an INTMOD yields an integer
673
x = x.lift()
674
break
675
elif paritype == t_POLMOD:
676
x = x.lift()
677
elif paritype == t_FFELT:
678
# x = (f modulo defining polynomial of finite field);
679
# we extract f.
680
sig_on()
681
x = pari.new_gen(FF_to_FpXQ_i((<pari_gen>x).g))
682
else:
683
raise TypeError, "Unable to coerce PARI %s to an Integer"%x
684
685
# Now we have a true PARI integer, convert it to Sage
686
t_INT_to_ZZ(self.value, (<pari_gen>x).g)
687
688
elif PyString_Check(x) or PY_TYPE_CHECK(x,unicode):
689
if base < 0 or base > 36:
690
raise ValueError, "`base` (=%s) must be between 2 and 36."%base
691
ibase = base
692
xs = x
693
if xs[0] == c'+':
694
xs += 1
695
if mpz_set_str(self.value, xs, ibase) != 0:
696
raise TypeError, "unable to convert x (=%s) to an integer"%x
697
698
elif PyObject_HasAttrString(x, "_integer_"):
699
# TODO: Note that PyObject_GetAttrString returns NULL if
700
# the attribute was not found. If we could test for this,
701
# we could skip the double lookup. Unfortunately Cython doesn't
702
# seem to let us do this; it flags an error if the function
703
# returns NULL, because it can't construct an "object" object
704
# out of the NULL pointer. This really sucks. Perhaps we could
705
# make the function prototype have return type void*, but
706
# then how do we make Cython handle the reference counting?
707
set_from_Integer(self, (<object> PyObject_GetAttrString(x, "_integer_"))(the_integer_ring))
708
709
elif (PY_TYPE_CHECK(x, list) or PY_TYPE_CHECK(x, tuple)) and base > 1:
710
b = the_integer_ring(base)
711
if b == 2: # we use a faster method
712
for j from 0 <= j < len(x):
713
otmp = x[j]
714
if not PY_TYPE_CHECK(otmp, Integer):
715
# should probably also have fast code for Python ints...
716
otmp = Integer(otmp)
717
if mpz_cmp_si((<Integer>otmp).value, 1) == 0:
718
mpz_setbit(self.value, j)
719
elif mpz_sgn((<Integer>otmp).value) != 0:
720
# one of the entries was something other than 0 or 1.
721
break
722
else:
723
return
724
tmp = the_integer_ring(0)
725
for i in range(len(x)):
726
tmp += the_integer_ring(x[i])*b**i
727
mpz_set(self.value, tmp.value)
728
729
else:
730
import numpy
731
if isinstance(x, numpy.integer):
732
mpz_set_pylong(self.value, x.__long__())
733
return
734
735
elif PY_TYPE_CHECK(x, Element):
736
try:
737
lift = x.lift()
738
if lift._parent != (<Element>x)._parent:
739
tmp = the_integer_ring(lift)
740
mpz_swap(tmp.value, self.value)
741
return
742
except AttributeError:
743
pass
744
745
raise TypeError, "unable to coerce %s to an integer" % type(x)
746
747
def __reduce__(self):
748
"""
749
This is used when pickling integers.
750
751
EXAMPLES::
752
753
sage: n = 5
754
sage: t = n.__reduce__(); t
755
(<built-in function make_integer>, ('5',))
756
sage: t[0](*t[1])
757
5
758
sage: loads(dumps(n)) == n
759
True
760
"""
761
# This single line below took me HOURS to figure out.
762
# It is the *trick* needed to pickle Cython extension types.
763
# The trick is that you must put a pure Python function
764
# as the first argument, and that function must return
765
# the result of unpickling with the argument in the second
766
# tuple as input. All kinds of problems happen
767
# if we don't do this.
768
return sage.rings.integer.make_integer, (self.str(32),)
769
770
cdef _reduce_set(self, s):
771
"""
772
Set this integer from a string in base 32.
773
774
.. note::
775
776
Integers are supposed to be immutable, so you should not
777
use this function.
778
"""
779
mpz_set_str(self.value, s, 32)
780
781
def __index__(self):
782
"""
783
Needed so integers can be used as list indices.
784
785
EXAMPLES::
786
787
sage: v = [1,2,3,4,5]
788
sage: v[Integer(3)]
789
4
790
sage: v[Integer(2):Integer(4)]
791
[3, 4]
792
"""
793
return mpz_get_pyintlong(self.value)
794
795
def _im_gens_(self, codomain, im_gens):
796
"""
797
Return the image of self under the map that sends the generators of
798
the parent to im_gens. Since ZZ maps canonically in the category
799
of rings, this is just the natural coercion.
800
801
EXAMPLES::
802
803
sage: n = -10
804
sage: R = GF(17)
805
sage: n._im_gens_(R, [R(1)])
806
7
807
"""
808
return codomain._coerce_(self)
809
810
cdef _xor(Integer self, Integer other):
811
cdef Integer x
812
x = PY_NEW(Integer)
813
mpz_xor(x.value, self.value, other.value)
814
return x
815
816
def __xor__(x, y):
817
"""
818
Compute the exclusive or of x and y.
819
820
EXAMPLES::
821
822
sage: n = ZZ(2); m = ZZ(3)
823
sage: n.__xor__(m)
824
1
825
"""
826
if PY_TYPE_CHECK(x, Integer) and PY_TYPE_CHECK(y, Integer):
827
return (<Integer>x)._xor(y)
828
return bin_op(x, y, operator.xor)
829
830
def __richcmp__(left, right, int op):
831
"""
832
cmp for integers
833
834
EXAMPLES::
835
836
sage: 2 < 3
837
True
838
sage: 2 > 3
839
False
840
sage: 2 == 3
841
False
842
sage: 3 > 2
843
True
844
sage: 3 < 2
845
False
846
847
sage: 1000000000000000000000000000000000000000000000000000.0r==1000000000000000000000000000000000000000000000000000
848
False
849
sage: 1000000000000000000000000000000000000000000000000000.1r==1000000000000000000000000000000000000000000000000000
850
False
851
852
Canonical coercions are used but non-canonical ones are not.
853
854
::
855
856
sage: 4 == 4/1
857
True
858
sage: 4 == '4'
859
False
860
861
TESTS::
862
863
sage: 3 < 4r
864
True
865
sage: 3r < 4
866
True
867
sage: 3 >= 4r
868
False
869
sage: 4r <= 3
870
False
871
sage: 12345678901234567890123456789r == 12345678901234567890123456789
872
True
873
sage: 12345678901234567890123456788 < 12345678901234567890123456789r
874
True
875
sage: 2 < 2.7r
876
True
877
sage: 4 < 3.1r
878
False
879
sage: -1r < 1
880
True
881
sage: -1.5r < 3
882
True
883
sage: Ilist = [-2,-1,0,1,2,12345678901234567890123456788]
884
sage: ilist = [-4r,-1r,0r,1r,2r,5r]
885
sage: llist = [-12345678901234567890123456788r, 12345678901234567890123456788r, 12345678901234567890123456900r]
886
sage: flist = [-21.8r, -1.2r, -.000005r, 0.0r, .999999r, 1000000000000.0r]
887
sage: all([(a < b) == (RR(a) < RR(b)) for (a, b) in zip(Ilist, ilist)])
888
True
889
sage: all([(a > b) == (RR(a) > RR(b)) for (a, b) in zip(Ilist, ilist)])
890
True
891
sage: all([(a == b) == (RR(a) == RR(b)) for (a, b) in zip(Ilist, ilist)])
892
True
893
sage: all([(a <= b) == (RR(a) <= RR(b)) for (a, b) in zip(Ilist, ilist)])
894
True
895
sage: all([(a >= b) == (RR(a) >= RR(b)) for (a, b) in zip(Ilist, ilist)])
896
True
897
sage: all([(a != b) == (RR(a) != RR(b)) for (a, b) in zip(Ilist, ilist)])
898
True
899
sage: all([(a < b) == (RR(a) < RR(b)) for (a, b) in zip(Ilist, llist)])
900
True
901
sage: all([(a > b) == (RR(a) > RR(b)) for (a, b) in zip(Ilist, llist)])
902
True
903
sage: all([(a < b) == (RR(a) < RR(b)) for (a, b) in zip(Ilist, flist)])
904
True
905
sage: all([(a > b) == (RR(a) > RR(b)) for (a, b) in zip(Ilist, flist)])
906
True
907
908
Verify that trac 12149 was fixed (and the fix is consistent
909
with Python ints)::
910
911
sage: a = int(1); b = 1; n = float('nan')
912
sage: a == n
913
False
914
sage: a == n, b == n
915
(False, False)
916
sage: a != n, b != n, n != b
917
(True, True, True)
918
sage: a < n, b < n, n > b
919
(False, False, False)
920
sage: a > n, b > n, n < b
921
(False, False, False)
922
sage: a <= n, b <= n, n >= b
923
(False, False, False)
924
sage: a >= n, b >= n, n <= b
925
(False, False, False)
926
"""
927
cdef int c
928
cdef double d
929
if PY_TYPE_CHECK(left, Integer):
930
if PY_TYPE_CHECK(right, Integer):
931
c = mpz_cmp((<Integer>left).value, (<Integer>right).value)
932
elif PyInt_CheckExact(right):
933
c = mpz_cmp_si((<Integer>left).value, PyInt_AS_LONG(right))
934
elif PyLong_CheckExact(right):
935
mpz_set_pylong(mpz_tmp, right)
936
c = mpz_cmp((<Integer>left).value, mpz_tmp)
937
elif PyFloat_CheckExact(right):
938
d = PyFloat_AsDouble(right)
939
if isnan(d): return op == 3
940
c = mpz_cmp_d((<Integer>left).value, d)
941
else:
942
return (<sage.structure.element.Element>left)._richcmp(right, op)
943
944
else: # right is an Integer
945
if PyInt_CheckExact(left):
946
c = -mpz_cmp_si((<Integer>right).value, PyInt_AS_LONG(left))
947
elif PyLong_CheckExact(left):
948
mpz_set_pylong(mpz_tmp, left)
949
c = mpz_cmp(mpz_tmp, (<Integer>right).value)
950
elif PyFloat_CheckExact(left):
951
d = PyFloat_AsDouble(left)
952
if isnan(d): return op == 3
953
c = -mpz_cmp_d((<Integer>right).value, d)
954
else:
955
return (<sage.structure.element.Element>left)._richcmp(right, op)
956
return (<sage.structure.element.Element>left)._rich_to_bool(op, c)
957
958
cdef int _cmp_c_impl(left, sage.structure.element.Element right) except -2:
959
cdef int i
960
i = mpz_cmp((<Integer>left).value, (<Integer>right).value)
961
if i < 0: return -1
962
elif i == 0: return 0
963
else: return 1
964
965
def __copy__(self):
966
"""
967
Return a copy of the integer.
968
969
EXAMPLES::
970
971
sage: n = 2
972
sage: copy(n)
973
2
974
sage: copy(n) is n
975
False
976
"""
977
cdef Integer z
978
z = PY_NEW(Integer)
979
set_mpz(z,self.value)
980
return z
981
982
def list(self):
983
"""
984
Return a list with this integer in it, to be compatible with the
985
method for number fields.
986
987
EXAMPLES::
988
989
sage: m = 5
990
sage: m.list()
991
[5]
992
"""
993
return [ self ]
994
995
def __dealloc__(self):
996
mpz_clear(self.value)
997
998
def __repr__(self):
999
"""
1000
Return string representation of this integer.
1001
1002
EXAMPLES::
1003
1004
sage: n = -5; n.__repr__()
1005
'-5'
1006
"""
1007
return self.str()
1008
1009
def _latex_(self):
1010
"""
1011
Return latex representation of this integer. This is just the
1012
underlying string representation and nothing more. This is called
1013
by the latex function.
1014
1015
EXAMPLES::
1016
1017
sage: n = -5; n._latex_()
1018
'-5'
1019
sage: latex(n)
1020
-5
1021
"""
1022
return self.str()
1023
1024
def _sympy_(self):
1025
"""
1026
Convert Sage Integer() to SymPy Integer.
1027
1028
EXAMPLES::
1029
1030
sage: n = 5; n._sympy_()
1031
5
1032
sage: n = -5; n._sympy_()
1033
-5
1034
"""
1035
import sympy
1036
return sympy.sympify(int(self))
1037
1038
def _mathml_(self):
1039
"""
1040
Return mathml representation of this integer.
1041
1042
EXAMPLES::
1043
1044
sage: mathml(-45)
1045
<mn>-45</mn>
1046
sage: (-45)._mathml_()
1047
'<mn>-45</mn>'
1048
"""
1049
return '<mn>%s</mn>'%self
1050
1051
def str(self, int base=10):
1052
r"""
1053
Return the string representation of ``self`` in the
1054
given base.
1055
1056
EXAMPLES::
1057
1058
sage: Integer(2^10).str(2)
1059
'10000000000'
1060
sage: Integer(2^10).str(17)
1061
'394'
1062
1063
::
1064
1065
sage: two=Integer(2)
1066
sage: two.str(1)
1067
Traceback (most recent call last):
1068
...
1069
ValueError: base (=1) must be between 2 and 36
1070
1071
::
1072
1073
sage: two.str(37)
1074
Traceback (most recent call last):
1075
...
1076
ValueError: base (=37) must be between 2 and 36
1077
1078
::
1079
1080
sage: big = 10^5000000
1081
sage: s = big.str() # long time (> 20 seconds)
1082
sage: len(s) # long time (depends on above defn of s)
1083
5000001
1084
sage: s[:10] # long time (depends on above defn of s)
1085
'1000000000'
1086
"""
1087
if base < 2 or base > 36:
1088
raise ValueError, "base (=%s) must be between 2 and 36"%base
1089
cdef size_t n
1090
cdef char *s
1091
n = mpz_sizeinbase(self.value, base) + 2
1092
s = <char *>PyMem_Malloc(n)
1093
if s == NULL:
1094
raise MemoryError, "Unable to allocate enough memory for the string representation of an integer."
1095
sig_on()
1096
mpz_get_str(s, base, self.value)
1097
sig_off()
1098
k = <object> PyString_FromString(s)
1099
PyMem_Free(s)
1100
return k
1101
1102
def __format__(self, *args, **kwargs):
1103
"""
1104
Returns a string representation using Python's Format protocol.
1105
Valid format descriptions are exactly those for Python integers.
1106
1107
EXAMPLES::
1108
1109
sage: "{0:#x}; {0:#b}; {0:+05d}".format(ZZ(17))
1110
'0x11; 0b10001; +0017'
1111
1112
"""
1113
return int(self).__format__(*args,**kwargs)
1114
1115
def ordinal_str(self):
1116
"""
1117
Returns a string representation of the ordinal associated to self.
1118
1119
EXAMPLES::
1120
1121
sage: [ZZ(n).ordinal_str() for n in range(25)]
1122
['0th',
1123
'1st',
1124
'2nd',
1125
'3rd',
1126
'4th',
1127
...
1128
'10th',
1129
'11th',
1130
'12th',
1131
'13th',
1132
'14th',
1133
...
1134
'20th',
1135
'21st',
1136
'22nd',
1137
'23rd',
1138
'24th']
1139
1140
sage: ZZ(1001).ordinal_str()
1141
'1001st'
1142
1143
sage: ZZ(113).ordinal_str()
1144
'113th'
1145
sage: ZZ(112).ordinal_str()
1146
'112th'
1147
sage: ZZ(111).ordinal_str()
1148
'111th'
1149
1150
"""
1151
if self<0:
1152
raise ValueError, "Negative integers are not ordinals."
1153
n = self.abs()
1154
if ((n%100)!=11 and n%10==1):
1155
th = 'st'
1156
elif ((n%100)!=12 and n%10==2):
1157
th = 'nd'
1158
elif ((n%100)!=13 and n%10==3):
1159
th = 'rd'
1160
else:
1161
th = 'th'
1162
return n.str()+th
1163
1164
def __hex__(self):
1165
r"""
1166
Return the hexadecimal digits of self in lower case.
1167
1168
.. note::
1169
1170
'0x' is *not* prepended to the result like is done by the
1171
corresponding Python function on int or long. This is for
1172
efficiency sake--adding and stripping the string wastes
1173
time; since this function is used for conversions from
1174
integers to other C-library structures, it is important
1175
that it be fast.
1176
1177
EXAMPLES::
1178
1179
sage: print hex(Integer(15))
1180
f
1181
sage: print hex(Integer(16))
1182
10
1183
sage: print hex(Integer(16938402384092843092843098243))
1184
36bb1e3929d1a8fe2802f083
1185
sage: print hex(long(16938402384092843092843098243))
1186
0x36bb1e3929d1a8fe2802f083L
1187
"""
1188
return self.str(16)
1189
1190
def __oct__(self):
1191
r"""
1192
Return the digits of self in base 8.
1193
1194
.. note::
1195
1196
'0' is *not* prepended to the result like is done by the
1197
corresponding Python function on int or long. This is for
1198
efficiency sake--adding and stripping the string wastes
1199
time; since this function is used for conversions from
1200
integers to other C-library structures, it is important
1201
that it be fast.
1202
1203
EXAMPLES::
1204
1205
sage: print oct(Integer(800))
1206
1440
1207
sage: print oct(Integer(8))
1208
10
1209
sage: print oct(Integer(-50))
1210
-62
1211
sage: print oct(Integer(-899))
1212
-1603
1213
sage: print oct(Integer(16938402384092843092843098243))
1214
15535436162247215217705000570203
1215
1216
Behavior of Sage integers vs. Python integers::
1217
1218
sage: oct(Integer(10))
1219
'12'
1220
sage: oct(int(10))
1221
'012'
1222
sage: oct(Integer(-23))
1223
'-27'
1224
sage: oct(int(-23))
1225
'-027'
1226
"""
1227
return self.str(8)
1228
1229
def binary(self):
1230
"""
1231
Return the binary digits of self as a string.
1232
1233
EXAMPLES::
1234
1235
sage: print Integer(15).binary()
1236
1111
1237
sage: print Integer(16).binary()
1238
10000
1239
sage: print Integer(16938402384092843092843098243).binary()
1240
1101101011101100011110001110010010100111010001101010001111111000101000000000101111000010000011
1241
"""
1242
return self.str(2)
1243
1244
def bits(self):
1245
"""
1246
Return the bits in self as a list, least significant first. The
1247
result satisfies the identity
1248
1249
::
1250
1251
x == sum(b*2^e for e, b in enumerate(x.bits()))
1252
1253
Negative numbers will have negative "bits". (So, strictly
1254
speaking, the entries of the returned list are not really
1255
members of `\ZZ/2\ZZ`.)
1256
1257
This method just calls :func:`digits` with ``base=2``.
1258
1259
SEE ALSO:
1260
1261
:func:`nbits` (number of bits; a faster way to compute
1262
``len(x.bits())``; and :func:`binary`, which returns a string in
1263
more-familiar notation.
1264
1265
EXAMPLES::
1266
1267
sage: 500.bits()
1268
[0, 0, 1, 0, 1, 1, 1, 1, 1]
1269
sage: 11.bits()
1270
[1, 1, 0, 1]
1271
sage: (-99).bits()
1272
[-1, -1, 0, 0, 0, -1, -1]
1273
"""
1274
return self.digits(base=2)
1275
1276
def nbits(self):
1277
"""
1278
Return the number of bits in self.
1279
1280
EXAMPLES::
1281
1282
sage: 500.nbits()
1283
9
1284
sage: 5.nbits()
1285
3
1286
sage: 0.nbits() == len(0.bits()) == 0.ndigits(base=2)
1287
True
1288
sage: 12345.nbits() == len(12345.binary())
1289
True
1290
"""
1291
# mpz_sizeinbase(0,2) always returns 1
1292
if mpz_cmp_si(self.value,0) == 0:
1293
return int(0)
1294
else:
1295
return int(mpz_sizeinbase(self.value, 2))
1296
1297
def trailing_zero_bits(self):
1298
"""
1299
Return the number of trailing zero bits in self, i.e.
1300
the exponent of the largest power of 2 dividing self.
1301
1302
EXAMPLES::
1303
1304
sage: 11.trailing_zero_bits()
1305
0
1306
sage: (-11).trailing_zero_bits()
1307
0
1308
sage: (11<<5).trailing_zero_bits()
1309
5
1310
sage: (-11<<5).trailing_zero_bits()
1311
5
1312
sage: 0.trailing_zero_bits()
1313
0
1314
1315
"""
1316
if mpz_sgn(self.value) == 0:
1317
return int(0)
1318
return int(mpz_scan1(self.value, 0))
1319
1320
def digits(self, base=10, digits=None, padto=0):
1321
r"""
1322
Return a list of digits for ``self`` in the given base in little
1323
endian order.
1324
1325
The returned value is unspecified if self is a negative number
1326
and the digits are given.
1327
1328
INPUT:
1329
1330
- ``base`` - integer (default: 10)
1331
1332
- ``digits`` - optional indexable object as source for
1333
the digits
1334
1335
- ``padto`` - the minimal length of the returned list,
1336
sufficient number of zeros are added to make the list minimum that
1337
length (default: 0)
1338
1339
As a shorthand for ``digits(2)``, you can use :meth:`.bits`.
1340
1341
Also see :meth:`ndigits`.
1342
1343
EXAMPLES::
1344
1345
sage: 17.digits()
1346
[7, 1]
1347
sage: 5.digits(base=2, digits=["zero","one"])
1348
['one', 'zero', 'one']
1349
sage: 5.digits(3)
1350
[2, 1]
1351
sage: 0.digits(base=10) # 0 has 0 digits
1352
[]
1353
sage: 0.digits(base=2) # 0 has 0 digits
1354
[]
1355
sage: 10.digits(16,'0123456789abcdef')
1356
['a']
1357
sage: 0.digits(16,'0123456789abcdef')
1358
[]
1359
sage: 0.digits(16,'0123456789abcdef',padto=1)
1360
['0']
1361
sage: 123.digits(base=10,padto=5)
1362
[3, 2, 1, 0, 0]
1363
sage: 123.digits(base=2,padto=3) # padto is the minimal length
1364
[1, 1, 0, 1, 1, 1, 1]
1365
sage: 123.digits(base=2,padto=10,digits=(1,-1))
1366
[-1, -1, 1, -1, -1, -1, -1, 1, 1, 1]
1367
sage: a=9939082340; a.digits(10)
1368
[0, 4, 3, 2, 8, 0, 9, 3, 9, 9]
1369
sage: a.digits(512)
1370
[100, 302, 26, 74]
1371
sage: (-12).digits(10)
1372
[-2, -1]
1373
sage: (-12).digits(2)
1374
[0, 0, -1, -1]
1375
1376
We support large bases.
1377
1378
::
1379
1380
sage: n=2^6000
1381
sage: n.digits(2^3000)
1382
[0, 0, 1]
1383
1384
::
1385
1386
sage: base=3; n=25
1387
sage: l=n.digits(base)
1388
sage: # the next relationship should hold for all n,base
1389
sage: sum(base^i*l[i] for i in range(len(l)))==n
1390
True
1391
sage: base=3; n=-30; l=n.digits(base); sum(base^i*l[i] for i in range(len(l)))==n
1392
True
1393
1394
The inverse of this method -- constructing an integer from a
1395
list of digits and a base -- can be done using the above method
1396
or by simply using :class:`ZZ()
1397
<sage.rings.integer_ring.IntegerRing_class>` with a base::
1398
1399
sage: x = 123; ZZ(x.digits(), 10)
1400
123
1401
sage: x == ZZ(x.digits(6), 6)
1402
True
1403
sage: x == ZZ(x.digits(25), 25)
1404
True
1405
1406
Using :func:`sum` and :func:`enumerate` to do the same thing is
1407
slightly faster in many cases (and
1408
:func:`~sage.misc.misc_c.balanced_sum` may be faster yet). Of
1409
course it gives the same result::
1410
1411
sage: base = 4
1412
sage: sum(digit * base^i for i, digit in enumerate(x.digits(base))) == ZZ(x.digits(base), base)
1413
True
1414
1415
Note: In some cases it is faster to give a digits collection. This
1416
would be particularly true for computing the digits of a series of
1417
small numbers. In these cases, the code is careful to allocate as
1418
few python objects as reasonably possible.
1419
1420
::
1421
1422
sage: digits = range(15)
1423
sage: l=[ZZ(i).digits(15,digits) for i in range(100)]
1424
sage: l[16]
1425
[1, 1]
1426
1427
This function is comparable to ``str`` for speed.
1428
1429
::
1430
1431
sage: n=3^100000
1432
sage: n.digits(base=10)[-1] # slightly slower than str
1433
1
1434
sage: n=10^10000
1435
sage: n.digits(base=10)[-1] # slightly faster than str
1436
1
1437
1438
AUTHORS:
1439
1440
- Joel B. Mohler (2008-03-02): significantly rewrote this entire function
1441
"""
1442
cdef Integer _base
1443
cdef Integer self_abs = self
1444
cdef int power_index = 0
1445
cdef list power_list
1446
cdef list l
1447
cdef int i
1448
cdef size_t s
1449
1450
if PY_TYPE_CHECK(base, Integer):
1451
_base = <Integer>base
1452
else:
1453
_base = Integer(base)
1454
1455
if mpz_cmp_si(_base.value,2) < 0:
1456
raise ValueError, "base must be >= 2"
1457
1458
if mpz_sgn(self.value) < 0:
1459
self_abs = -self
1460
1461
cdef bint do_sig_on
1462
if mpz_sgn(self.value) == 0:
1463
l = [the_integer_ring._zero_element if digits is None else digits[0]]*padto
1464
elif mpz_cmp_si(_base.value,2) == 0:
1465
s = mpz_sizeinbase(self.value, 2)
1466
if digits:
1467
o = digits[1]
1468
z = digits[0]
1469
else:
1470
if mpz_sgn(self.value) == 1:
1471
o = the_integer_ring._one_element
1472
else:
1473
o = -the_integer_ring._one_element
1474
z = the_integer_ring._zero_element
1475
l = [z]*(s if s >= padto else padto)
1476
for i from 0<= i < s:
1477
# mpz_tstbit seems to return 0 for the high-order bit of
1478
# negative numbers?!
1479
if mpz_tstbit(self_abs.value,i):
1480
l[i] = o
1481
else:
1482
s = mpz_sizeinbase(self.value, 2)
1483
do_sig_on = (s > 256)
1484
if do_sig_on: sig_on()
1485
1486
# We use a divide and conquer approach (suggested by the prior
1487
# author, malb?, of the digits method) here: for base b, compute
1488
# b^2, b^4, b^8, ... (repeated squaring) until you get larger
1489
# than your number; then compute (n // b^256, n % b^256)
1490
# (if b^512 > number) to split the number in half and recurse
1491
1492
# Pre-computing the exact number of digits up-front is actually
1493
# faster (especially for large values of self) than trimming off
1494
# trailing zeros after the fact. It also seems that it would
1495
# avoid duplicating the list in memory with a list-slice.
1496
z = the_integer_ring._zero_element if digits is None else digits[0]
1497
s = self_abs.exact_log(_base)
1498
l = [z]*(s+1 if s+1 >= padto else padto)
1499
1500
# set up digits for optimal access once we get inside the worker
1501
# functions
1502
if not digits is None:
1503
# list objects have fastest access in the innermost loop
1504
if not PyList_CheckExact(digits):
1505
digits = [digits[i] for i in range(_base)]
1506
elif mpz_cmp_ui(_base.value,s) < 0 and mpz_cmp_ui(_base.value,10000):
1507
# We can get a speed boost by pre-allocating digit values in
1508
# big cases.
1509
# We do this we have more digits than the base and the base
1510
# is not too extremely large (currently, "extremely" means
1511
# larger than 10000 -- that's very arbitrary.)
1512
if mpz_sgn(self.value) > 0:
1513
digits = [Integer(i) for i in range(_base)]
1514
else:
1515
# All the digits will be negated in the recursive function.
1516
# we'll just compensate for python index semantics
1517
digits = [Integer(i) for i in range(-_base,0)]
1518
digits[0] = the_integer_ring._zero_element
1519
1520
if s < 40:
1521
_digits_naive(self.value,l,0,_base,digits)
1522
else:
1523
# count the bits of s
1524
i = 0
1525
while s != 0:
1526
s >>= 1
1527
i += 1
1528
1529
power_list = [_base]*i
1530
for power_index from 1 <= power_index < i:
1531
power_list[power_index] = power_list[power_index-1]**2
1532
1533
# Note that it may appear that the recursive calls to
1534
# _digit_internal would be assigning list elements i in l for
1535
# anywhere from 0<=i<(1<<power_index). However, this is not
1536
# the case due to the optimization of skipping assigns
1537
# assigning zero.
1538
_digits_internal(self.value,l,0,i-1,power_list,digits)
1539
1540
if do_sig_on: sig_off()
1541
1542
# padding should be taken care of with-in the function
1543
# all we need to do is return
1544
return l
1545
1546
def ndigits(self, base=10):
1547
"""
1548
Return the number of digits of self expressed in the given base.
1549
1550
INPUT:
1551
1552
- ``base`` - integer (default: 10)
1553
1554
EXAMPLES::
1555
1556
sage: n = 52
1557
sage: n.ndigits()
1558
2
1559
sage: n = -10003
1560
sage: n.ndigits()
1561
5
1562
sage: n = 15
1563
sage: n.ndigits(2)
1564
4
1565
sage: n = 1000**1000000+1
1566
sage: n.ndigits()
1567
3000001
1568
sage: n = 1000**1000000-1
1569
sage: n.ndigits()
1570
3000000
1571
sage: n = 10**10000000-10**9999990
1572
sage: n.ndigits()
1573
10000000
1574
"""
1575
cdef Integer temp
1576
1577
if mpz_sgn(self.value) == 0:
1578
temp = PY_NEW(Integer)
1579
mpz_set_ui(temp.value, 0)
1580
return temp
1581
1582
if mpz_sgn(self.value) > 0:
1583
temp = self.exact_log(base)
1584
mpz_add_ui(temp.value, temp.value, 1)
1585
return temp
1586
else:
1587
return self.abs().exact_log(base) + 1
1588
1589
cdef void set_from_mpz(Integer self, mpz_t value):
1590
mpz_set(self.value, value)
1591
1592
cdef mpz_t* get_value(Integer self):
1593
return &self.value
1594
1595
cdef void _to_ZZ(self, ZZ_c *z):
1596
sig_on()
1597
mpz_to_ZZ(z, &self.value)
1598
sig_off()
1599
1600
cpdef ModuleElement _add_(self, ModuleElement right):
1601
"""
1602
Integer addition.
1603
1604
TESTS::
1605
1606
sage: Integer(32) + Integer(23)
1607
55
1608
sage: sum(Integer(i) for i in [1..100])
1609
5050
1610
sage: a = ZZ.random_element(10^50000)
1611
sage: b = ZZ.random_element(10^50000)
1612
sage: a+b == b+a
1613
True
1614
"""
1615
# self and right are guaranteed to be Integers
1616
cdef Integer x = <Integer>PY_NEW(Integer)
1617
mpz_add(x.value, self.value, (<Integer>right).value)
1618
return x
1619
1620
cpdef ModuleElement _iadd_(self, ModuleElement right):
1621
# self and right are guaranteed to be Integers, self safe to mutate
1622
mpz_add(self.value, self.value, (<Integer>right).value)
1623
return self
1624
1625
cdef RingElement _add_long(self, long n):
1626
"""
1627
Fast path for adding a C long.
1628
1629
TESTS::
1630
sage: int(10) + Integer(100)
1631
110
1632
sage: Integer(100) + int(10)
1633
110
1634
sage: Integer(10^100) + int(10)
1635
10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010
1636
1637
Also called for subtraction::
1638
1639
sage: Integer(100) - int(10)
1640
90
1641
sage: Integer(10^100) - int(10)
1642
9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999990
1643
1644
Make sure it works when -<long>n would overflow::
1645
1646
sage: most_neg_long = int(-sys.maxint - 1)
1647
sage: type(most_neg_long), type(-most_neg_long)
1648
(<type 'int'>, <type 'long'>)
1649
sage: 0 + most_neg_long == most_neg_long
1650
True
1651
sage: 0 - most_neg_long == -most_neg_long
1652
True
1653
"""
1654
cdef Integer x = <Integer>PY_NEW(Integer)
1655
if n > 0:
1656
mpz_add_ui(x.value, self.value, n)
1657
else:
1658
# Note that 0-<unsigned long>n is always -n as an unsigned
1659
# long (whereas -n may overflow).
1660
mpz_sub_ui(x.value, self.value, 0 - <unsigned long>n)
1661
return x
1662
1663
cpdef ModuleElement _sub_(self, ModuleElement right):
1664
"""
1665
Integer subtraction.
1666
1667
TESTS::
1668
1669
sage: Integer(32) - Integer(23)
1670
9
1671
sage: Integer(10^100) - Integer(1)
1672
9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999
1673
sage: Integer(1) - Integer(10^100)
1674
-9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999
1675
sage: a = ZZ.random_element(10^50000)
1676
sage: b = ZZ.random_element(10^50000)
1677
sage: a-b == -(b-a) == a + -b
1678
True
1679
"""
1680
# self and right are guaranteed to be Integers
1681
cdef Integer x = <Integer>PY_NEW(Integer)
1682
mpz_sub(x.value, self.value, (<Integer>right).value)
1683
return x
1684
1685
cpdef ModuleElement _isub_(self, ModuleElement right):
1686
mpz_sub(self.value, self.value, (<Integer>right).value)
1687
return self
1688
1689
def __neg__(self):
1690
"""
1691
TESTS::
1692
1693
sage: a = Integer(3)
1694
sage: -a
1695
-3
1696
sage: a = Integer(3^100); a
1697
515377520732011331036461129765621272702107522001
1698
sage: -a
1699
-515377520732011331036461129765621272702107522001
1700
"""
1701
cdef Integer x = <Integer>PY_NEW(Integer)
1702
mpz_neg(x.value, self.value)
1703
return x
1704
1705
cpdef ModuleElement _neg_(self):
1706
cdef Integer x = <Integer>PY_NEW(Integer)
1707
mpz_neg(x.value, self.value)
1708
return x
1709
1710
cpdef _act_on_(self, s, bint self_on_left):
1711
"""
1712
EXAMPLES::
1713
1714
sage: 8 * [0] #indirect doctest
1715
[0, 0, 0, 0, 0, 0, 0, 0]
1716
sage: 'hi' * 8
1717
'hihihihihihihihi'
1718
"""
1719
if isinstance(s, (list, tuple, basestring)):
1720
if mpz_fits_slong_p(self.value):
1721
return s * mpz_get_si(self.value)
1722
else:
1723
return s * int(self) # will raise the appropriate exception
1724
1725
cdef ModuleElement _mul_long(self, long n):
1726
"""
1727
Fast path for multiplying a C long.
1728
1729
TESTS::
1730
1731
sage: Integer(25) * int(4)
1732
100
1733
sage: int(4) * Integer(25)
1734
100
1735
sage: Integer(10^100) * int(4)
1736
40000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
1737
"""
1738
cdef Integer x = <Integer>PY_NEW(Integer)
1739
if mpz_size(self.value) > 100000:
1740
sig_on()
1741
mpz_mul_si(x.value, self.value, n)
1742
sig_off()
1743
else:
1744
mpz_mul_si(x.value, self.value, n)
1745
return x
1746
1747
cpdef RingElement _mul_(self, RingElement right):
1748
"""
1749
Integer multiplication.
1750
1751
sage: Integer(25) * Integer(4)
1752
100
1753
sage: Integer(5^100) * Integer(2^100)
1754
10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
1755
sage: a = ZZ.random_element(10^50000)
1756
sage: b = ZZ.random_element(10^50000)
1757
sage: a*b == b*a
1758
True
1759
"""
1760
# self and right are guaranteed to be Integers
1761
cdef Integer x = <Integer>PY_NEW(Integer)
1762
if mpz_size(self.value) + mpz_size((<Integer>right).value) > 100000:
1763
# We only use the signal handler (to enable ctrl-c out) when the
1764
# product might take a while to compute
1765
sig_on()
1766
mpz_mul(x.value, self.value, (<Integer>right).value)
1767
sig_off()
1768
else:
1769
mpz_mul(x.value, self.value, (<Integer>right).value)
1770
return x
1771
1772
cpdef RingElement _imul_(self, RingElement right):
1773
if mpz_size(self.value) + mpz_size((<Integer>right).value) > 100000:
1774
# We only use the signal handler (to enable ctrl-c out) when the
1775
# product might take a while to compute
1776
sig_on()
1777
mpz_mul(self.value, self.value, (<Integer>right).value)
1778
sig_off()
1779
else:
1780
mpz_mul(self.value, self.value, (<Integer>right).value)
1781
return self
1782
1783
cpdef RingElement _div_(self, RingElement right):
1784
r"""
1785
Computes `\frac{a}{b}`
1786
1787
EXAMPLES::
1788
1789
sage: a = Integer(3) ; b = Integer(4)
1790
sage: a / b == Rational(3) / 4
1791
True
1792
sage: Integer(32) / Integer(32)
1793
1
1794
"""
1795
# This is vastly faster than doing it here, since here
1796
# we can't cimport rationals.
1797
return the_integer_ring._div(self, right)
1798
1799
def __floordiv__(x, y):
1800
r"""
1801
Computes the whole part of `\frac{x}{y}`.
1802
1803
EXAMPLES::
1804
1805
sage: a = Integer(321) ; b = Integer(10)
1806
sage: a // b
1807
32
1808
sage: z = Integer(-231)
1809
sage: z // 2
1810
-116
1811
sage: z = Integer(231)
1812
sage: z // 2
1813
115
1814
sage: z // -2
1815
-116
1816
sage: z // 0
1817
Traceback (most recent call last):
1818
...
1819
ZeroDivisionError: Integer division by zero
1820
sage: 101 // int(5)
1821
20
1822
sage: 100 // int(-3)
1823
-34
1824
1825
TESTS::
1826
1827
sage: signs = [(11,5), (11,-5), (-11,5), (-11,-5)]
1828
sage: control = [int(a) // int(b) for a, b in signs]
1829
sage: [a // b for a,b in signs] == control
1830
True
1831
sage: [a // int(b) for a,b in signs] == control
1832
True
1833
sage: [int(a) // b for a,b in signs] == control
1834
True
1835
"""
1836
cdef Integer z = <Integer>PY_NEW(Integer)
1837
cdef long yy, res
1838
if PY_TYPE(x) is PY_TYPE(y):
1839
if not mpz_sgn((<Integer>y).value):
1840
raise ZeroDivisionError, "Integer division by zero"
1841
if mpz_size((<Integer>x).value) > 100000:
1842
sig_on()
1843
mpz_fdiv_q(z.value, (<Integer>x).value, (<Integer>y).value)
1844
sig_off()
1845
else:
1846
mpz_fdiv_q(z.value, (<Integer>x).value, (<Integer>y).value)
1847
return z
1848
1849
elif PyInt_CheckExact(y):
1850
yy = PyInt_AS_LONG(y)
1851
if yy > 0:
1852
mpz_fdiv_q_ui(z.value, (<Integer>x).value, yy)
1853
elif yy == 0:
1854
raise ZeroDivisionError, "Integer division by zero"
1855
else:
1856
res = mpz_fdiv_q_ui(z.value, (<Integer>x).value, -yy)
1857
mpz_neg(z.value, z.value)
1858
if res:
1859
mpz_sub_ui(z.value, z.value, 1)
1860
return z
1861
1862
else:
1863
return bin_op(x, y, operator.floordiv)
1864
1865
def __pow__(self, n, modulus):
1866
r"""
1867
Computes `\text{self}^n`
1868
1869
EXAMPLES::
1870
1871
sage: 2^-6
1872
1/64
1873
sage: 2^6
1874
64
1875
sage: 2^0
1876
1
1877
sage: 2^-0
1878
1
1879
sage: (-1)^(1/3)
1880
(-1)^(1/3)
1881
1882
For consistency with Python and MPFR, 0^0 is defined to be 1 in
1883
Sage::
1884
1885
sage: 0^0
1886
1
1887
1888
The base need not be an integer (it can be a builtin Python type).
1889
1890
::
1891
1892
sage: int(2)^10
1893
1024
1894
sage: float(2.5)^10
1895
9536.7431640625
1896
sage: 'sage'^3
1897
'sagesagesage'
1898
1899
The exponent must fit in a long unless the base is -1, 0, or 1.
1900
1901
::
1902
1903
sage: x = 2^100000000000000000000000
1904
Traceback (most recent call last):
1905
...
1906
RuntimeError: exponent must be at most 2147483647 # 32-bit
1907
RuntimeError: exponent must be at most 9223372036854775807 # 64-bit
1908
sage: (-1)^100000000000000000000000
1909
1
1910
1911
We raise 2 to various interesting exponents::
1912
1913
sage: 2^x # symbolic x
1914
2^x
1915
sage: 2^1.5 # real number
1916
2.82842712474619
1917
sage: 2^float(1.5) # python float
1918
2.8284271247461903
1919
sage: 2^I # complex number
1920
2^I
1921
sage: f = 2^(sin(x)-cos(x)); f
1922
2^(-cos(x) + sin(x))
1923
sage: f(x=3)
1924
2^(-cos(3) + sin(3))
1925
1926
A symbolic sum::
1927
1928
sage: x,y,z = var('x,y,z')
1929
sage: 2^(x+y+z)
1930
2^(x + y + z)
1931
sage: 2^(1/2)
1932
sqrt(2)
1933
sage: 2^(-1/2)
1934
1/2*sqrt(2)
1935
1936
TESTS::
1937
1938
sage: complex(0,1)^2
1939
(-1+0j)
1940
sage: R.<t> = QQ[]
1941
sage: 2^t
1942
Traceback (most recent call last):
1943
...
1944
TypeError: non-integral exponents not supported
1945
sage: int(3)^-3
1946
1/27
1947
sage: type(int(3)^2)
1948
<type 'sage.rings.integer.Integer'>
1949
sage: type(int(3)^int(2))
1950
<type 'int'>
1951
1952
Check that a ``MemoryError`` is thrown if the resulting number
1953
would be ridiculously large, see :trac:`15363`::
1954
1955
sage: 2^(2^63-2)
1956
Traceback (most recent call last):
1957
...
1958
RuntimeError: exponent must be at most 2147483647 # 32-bit
1959
MemoryError: failed to allocate 1152921504606847008 bytes # 64-bit
1960
"""
1961
if modulus is not None:
1962
from sage.rings.finite_rings.integer_mod import Mod
1963
return Mod(self, modulus) ** n
1964
1965
if not PY_TYPE_CHECK(self, Integer):
1966
if isinstance(self, str):
1967
return self * n
1968
if not PY_TYPE_CHECK(self, int):
1969
return self ** int(n)
1970
else:
1971
self = Integer(self) #convert from int to Integer
1972
cdef Integer _self = <Integer>self
1973
cdef long nn
1974
1975
try:
1976
nn = PyNumber_Index(n)
1977
except TypeError:
1978
s = parent_c(n)(self)
1979
return s**n
1980
except OverflowError:
1981
if mpz_cmp_si(_self.value, 1) == 0:
1982
return self
1983
elif mpz_cmp_si(_self.value, 0) == 0:
1984
return self
1985
elif mpz_cmp_si(_self.value, -1) == 0:
1986
return self if n % 2 else -self
1987
raise RuntimeError, "exponent must be at most %s" % sys.maxint
1988
1989
if nn == 0:
1990
return one
1991
1992
cdef Integer x = PY_NEW(Integer)
1993
1994
sig_on()
1995
mpz_pow_ui(x.value, (<Integer>self).value, nn if nn > 0 else -nn)
1996
sig_off()
1997
1998
if nn < 0:
1999
return ~x
2000
else:
2001
return x
2002
2003
def nth_root(self, int n, bint truncate_mode=0):
2004
r"""
2005
Returns the (possibly truncated) n'th root of self.
2006
2007
INPUT:
2008
2009
- ``n`` - integer >= 1 (must fit in C int type).
2010
2011
- ``truncate_mode`` - boolean, whether to allow truncation if
2012
self is not an n'th power.
2013
2014
OUTPUT:
2015
2016
If truncate_mode is 0 (default), then returns the exact n'th root
2017
if self is an n'th power, or raises a ValueError if it is not.
2018
2019
If truncate_mode is 1, then if either n is odd or self is
2020
positive, returns a pair (root, exact_flag) where root is the
2021
truncated nth root (rounded towards zero) and exact_flag is a
2022
boolean indicating whether the root extraction was exact;
2023
otherwise raises a ValueError.
2024
2025
AUTHORS:
2026
2027
- David Harvey (2006-09-15)
2028
- Interface changed by John Cremona (2009-04-04)
2029
2030
EXAMPLES::
2031
2032
sage: Integer(125).nth_root(3)
2033
5
2034
sage: Integer(124).nth_root(3)
2035
Traceback (most recent call last):
2036
...
2037
ValueError: 124 is not a 3rd power
2038
sage: Integer(124).nth_root(3, truncate_mode=1)
2039
(4, False)
2040
sage: Integer(125).nth_root(3, truncate_mode=1)
2041
(5, True)
2042
sage: Integer(126).nth_root(3, truncate_mode=1)
2043
(5, False)
2044
2045
::
2046
2047
sage: Integer(-125).nth_root(3)
2048
-5
2049
sage: Integer(-125).nth_root(3,truncate_mode=1)
2050
(-5, True)
2051
sage: Integer(-124).nth_root(3,truncate_mode=1)
2052
(-4, False)
2053
sage: Integer(-126).nth_root(3,truncate_mode=1)
2054
(-5, False)
2055
2056
::
2057
2058
sage: Integer(125).nth_root(2, True)
2059
(11, False)
2060
sage: Integer(125).nth_root(3, True)
2061
(5, True)
2062
2063
::
2064
2065
sage: Integer(125).nth_root(-5)
2066
Traceback (most recent call last):
2067
...
2068
ValueError: n (=-5) must be positive
2069
2070
::
2071
2072
sage: Integer(-25).nth_root(2)
2073
Traceback (most recent call last):
2074
...
2075
ValueError: cannot take even root of negative number
2076
2077
::
2078
2079
sage: a=9
2080
sage: a.nth_root(3)
2081
Traceback (most recent call last):
2082
...
2083
ValueError: 9 is not a 3rd power
2084
2085
sage: a.nth_root(22)
2086
Traceback (most recent call last):
2087
...
2088
ValueError: 9 is not a 22nd power
2089
2090
sage: ZZ(2^20).nth_root(21)
2091
Traceback (most recent call last):
2092
...
2093
ValueError: 1048576 is not a 21st power
2094
2095
sage: ZZ(2^20).nth_root(21, truncate_mode=1)
2096
(1, False)
2097
2098
"""
2099
if n < 1:
2100
raise ValueError, "n (=%s) must be positive" % n
2101
if (mpz_sgn(self.value) < 0) and not (n & 1):
2102
raise ValueError, "cannot take even root of negative number"
2103
cdef Integer x
2104
cdef bint is_exact
2105
x = PY_NEW(Integer)
2106
sig_on()
2107
is_exact = mpz_root(x.value, self.value, n)
2108
sig_off()
2109
2110
if truncate_mode:
2111
return x, is_exact
2112
else:
2113
if is_exact:
2114
return x
2115
else:
2116
raise ValueError, "%s is not a %s power"%(self,integer_ring.ZZ(n).ordinal_str())
2117
2118
cpdef size_t _exact_log_log2_iter(self,Integer m):
2119
"""
2120
This is only for internal use only. You should expect it to crash
2121
and burn for negative or other malformed input. In particular, if
2122
the base `2 \leq m < 4` the log2 approximation of m is 1 and certain
2123
input causes endless loops. Along these lines, it is clear that
2124
this function is most useful for m with a relatively large number
2125
of bits.
2126
2127
For ``small`` values (which I'll leave quite ambiguous), this function
2128
is a fast path for exact log computations. Any integer division with
2129
such input tends to dominate the runtime. Thus we avoid division
2130
entirely in this function.
2131
2132
AUTHOR::
2133
2134
- Joel B. Mohler (2009-04-10)
2135
2136
EXAMPLES::
2137
2138
sage: Integer(125)._exact_log_log2_iter(4)
2139
3
2140
sage: Integer(5^150)._exact_log_log2_iter(5)
2141
150
2142
"""
2143
cdef size_t n_log2
2144
cdef size_t m_log2
2145
cdef size_t l_min
2146
cdef size_t l_max
2147
cdef size_t l
2148
cdef Integer result
2149
cdef mpz_t accum
2150
cdef mpz_t temp_exp
2151
2152
if mpz_cmp_si(m.value,4) < 0:
2153
raise ValueError, "This is undefined or possibly non-convergent with this algorithm."
2154
2155
n_log2=mpz_sizeinbase(self.value,2)-1
2156
m_log2=mpz_sizeinbase(m.value,2)-1
2157
l_min=n_log2/(m_log2+1)
2158
l_max=n_log2/m_log2
2159
if l_min != l_max:
2160
sig_on()
2161
mpz_init(accum)
2162
mpz_init(temp_exp)
2163
mpz_set_ui(accum,1)
2164
l = 0
2165
while l_min != l_max:
2166
# print "self=...",m,l_min,l_max
2167
if l_min + 1 == l_max:
2168
mpz_pow_ui(temp_exp,m.value,l_min+1-l)
2169
# This might over-shoot and make accum > self, but
2170
# we'll know that it's only over by a factor of m^1.
2171
mpz_mul(accum,accum,temp_exp)
2172
if mpz_cmp(self.value,accum) >= 0:
2173
l_min += 1
2174
break
2175
mpz_pow_ui(temp_exp,m.value,l_min-l)
2176
mpz_mul(accum,accum,temp_exp)
2177
l = l_min
2178
2179
# Let x=n_log2-(mpz_sizeinbase(accum,2)-1) and y=m_log2.
2180
# Now, with x>0 and y>0, we have the following observation.
2181
# If floor((x-1)/(y+1))=0, then x-1<y+1 which implies that
2182
# x/y<1+2/y.
2183
# So long as y>=2, this means that floor(x/y)<=1. This shows
2184
# that this iteration is forced to converge for input m >= 4.
2185
# If m=3, we can find input so that floor((x-1)/(y+1))=0 and
2186
# floor(x/y)=2 which results in non-convergence.
2187
2188
# We need the additional '-1' in the l_min computation
2189
# because mpz_sizeinbase(accum,2)-1 is smaller than the
2190
# true log_2(accum)
2191
l_min=l+(n_log2-(mpz_sizeinbase(accum,2)-1)-1)/(m_log2+1)
2192
l_max=l+(n_log2-(mpz_sizeinbase(accum,2)-1))/m_log2
2193
mpz_clear(temp_exp)
2194
mpz_clear(accum)
2195
sig_off()
2196
return l_min
2197
2198
cpdef size_t _exact_log_mpfi_log(self,m):
2199
"""
2200
This is only for internal use only. You should expect it to crash
2201
and burn for negative or other malformed input.
2202
2203
I avoid using this function until the input is large. The overhead
2204
associated with computing the floating point log entirely dominates
2205
the runtime for small values. Note that this is most definitely not
2206
an artifact of format conversion. Tricks with log2 approximations
2207
and using exact integer arithmetic are much better for small input.
2208
2209
AUTHOR::
2210
2211
- Joel B. Mohler (2009-04-10)
2212
2213
EXAMPLES::
2214
2215
sage: Integer(125)._exact_log_mpfi_log(3)
2216
4
2217
sage: Integer(5^150)._exact_log_mpfi_log(5)
2218
150
2219
"""
2220
cdef int i
2221
cdef list pow_2_things
2222
cdef int pow_2
2223
cdef size_t upper,lower,middle
2224
2225
import real_mpfi
2226
R=real_mpfi.RIF
2227
2228
rif_self = R(self)
2229
2230
sig_on()
2231
rif_m = R(m)
2232
rif_log = rif_self.log()/rif_m.log()
2233
# upper is *greater* than the answer
2234
try:
2235
upper = rif_log.upper().ceiling()
2236
except Exception:
2237
# ceiling is probably Infinity
2238
# I'm not sure what to do now
2239
upper = 0
2240
lower = rif_log.lower().floor()
2241
# since the log function is monotonic increasing, lower
2242
# and upper bracket our desired answer
2243
2244
# if upper - lower == 1: "we are done"
2245
if upper - lower == 2:
2246
# You could test it by checking rif_m**(lower+1), but I think
2247
# that's a waste of time since it won't be conclusive.
2248
# We must test with exact integer arithmetic which takes all
2249
# the bits of self into account.
2250
sig_off()
2251
if self >= m**(lower+1):
2252
return lower + 1
2253
else:
2254
return lower
2255
elif upper - lower > 2:
2256
# this case would only happen in cases with extremely large 'self'
2257
rif_m = R(m)
2258
min_power = rif_m**lower
2259
middle = upper-lower
2260
pow_2 = 0
2261
while middle != 0:
2262
middle >>= 1
2263
pow_2 += 1
2264
# if middle was an exact power of 2, adjust down
2265
if (1 << (pow_2-1)) == upper-lower:
2266
pow_2 -= 1
2267
#print upper, lower, pow_2
2268
pow_2_things = [rif_m]*pow_2
2269
for i from 1<=i<pow_2:
2270
pow_2_things[i] = pow_2_things[i-1]**2
2271
for i from pow_2>i>=0:
2272
middle = lower + int(2)**i
2273
#print "Upper: %i; Lower: %i; Middle: %i" % (upper,lower, middle)
2274
exp = min_power*pow_2_things[i]
2275
if exp > rif_self:
2276
upper = middle
2277
elif exp < rif_self:
2278
lower = middle
2279
min_power = exp
2280
else:
2281
sig_off()
2282
if m**middle <= self:
2283
return middle
2284
else:
2285
return lower
2286
sig_off()
2287
2288
if upper == 0:
2289
raise ValueError, "The input for exact_log is too large and support is not implemented."
2290
2291
return lower
2292
2293
def exact_log(self, m):
2294
r"""
2295
Returns the largest integer `k` such that `m^k \leq \text{self}`,
2296
i.e., the floor of `\log_m(\text{self})`.
2297
2298
This is guaranteed to return the correct answer even when the usual
2299
log function doesn't have sufficient precision.
2300
2301
INPUT:
2302
2303
- ``m`` - integer >= 2
2304
2305
AUTHORS:
2306
2307
- David Harvey (2006-09-15)
2308
- Joel B. Mohler (2009-04-08) -- rewrote this to handle small cases
2309
and/or easy cases up to 100x faster..
2310
2311
EXAMPLES::
2312
2313
sage: Integer(125).exact_log(5)
2314
3
2315
sage: Integer(124).exact_log(5)
2316
2
2317
sage: Integer(126).exact_log(5)
2318
3
2319
sage: Integer(3).exact_log(5)
2320
0
2321
sage: Integer(1).exact_log(5)
2322
0
2323
sage: Integer(178^1700).exact_log(178)
2324
1700
2325
sage: Integer(178^1700-1).exact_log(178)
2326
1699
2327
sage: Integer(178^1700+1).exact_log(178)
2328
1700
2329
sage: # we need to exercise the large base code path too
2330
sage: Integer(1780^1700-1).exact_log(1780)
2331
1699
2332
2333
sage: # The following are very very fast.
2334
sage: # Note that for base m a perfect power of 2, we get the exact log by counting bits.
2335
sage: n=2983579823750185701375109835; m=32
2336
sage: n.exact_log(m)
2337
18
2338
sage: # The next is a favorite of mine. The log2 approximate is exact and immediately provable.
2339
sage: n=90153710570912709517902579010793251709257901270941709247901209742124;m=213509721309572
2340
sage: n.exact_log(m)
2341
4
2342
2343
::
2344
2345
sage: x = 3^100000
2346
sage: RR(log(RR(x), 3))
2347
100000.000000000
2348
sage: RR(log(RR(x + 100000), 3))
2349
100000.000000000
2350
2351
::
2352
2353
sage: x.exact_log(3)
2354
100000
2355
sage: (x+1).exact_log(3)
2356
100000
2357
sage: (x-1).exact_log(3)
2358
99999
2359
2360
::
2361
2362
sage: x.exact_log(2.5)
2363
Traceback (most recent call last):
2364
...
2365
TypeError: Attempt to coerce non-integral RealNumber to Integer
2366
"""
2367
cdef Integer _m
2368
cdef Integer result
2369
cdef size_t n_log2
2370
cdef size_t m_log2
2371
cdef size_t guess # this will contain the final answer
2372
cdef bint guess_filled = 0 # this variable is only used in one branch below
2373
cdef mpz_t z
2374
if PY_TYPE_CHECK(m,Integer):
2375
_m=<Integer>m
2376
else:
2377
_m=<Integer>Integer(m)
2378
2379
if mpz_sgn(self.value) <= 0 or mpz_sgn(_m.value) <= 0:
2380
raise ValueError, "both self and m must be positive"
2381
if mpz_cmp_si(_m.value,2) < 0:
2382
raise ValueError, "m must be at least 2"
2383
2384
n_log2=mpz_sizeinbase(self.value,2)-1
2385
m_log2=mpz_sizeinbase(_m.value,2)-1
2386
if mpz_divisible_2exp_p(_m.value,m_log2):
2387
# Here, m is a power of 2 and the correct answer is found
2388
# by a log 2 approximation.
2389
guess = n_log2/m_log2 # truncating division
2390
elif n_log2/(m_log2+1) == n_log2/m_log2:
2391
# In this case, we have an upper bound and lower bound which
2392
# give the same answer, thus, the correct answer.
2393
guess = n_log2/m_log2
2394
elif m_log2 < 8: # i.e. m<256
2395
# if the base m is at most 256, we can use mpz_sizeinbase
2396
# to get the following guess which is either the exact
2397
# log, or 1+ the exact log
2398
guess = mpz_sizeinbase(self.value, mpz_get_si(_m.value)) - 1
2399
2400
# we've already excluded the case when m is an exact power of 2
2401
2402
if n_log2/m_log2 > 8000:
2403
# If we have a very large number of digits, it can be a nice
2404
# shortcut to test the guess using interval arithmetic.
2405
# (suggested by David Harvey and Carl Witty)
2406
# "for randomly distributed integers, the chance of this
2407
# interval-based comparison failing is absurdly low"
2408
import real_mpfi
2409
approx_compare = real_mpfi.RIF(m)**guess
2410
if self > approx_compare:
2411
guess_filled = 1
2412
elif self < approx_compare:
2413
guess_filled = 1
2414
guess = guess - 1
2415
if not guess_filled:
2416
# At this point, either
2417
# 1) self is close enough to a perfect power of m that we
2418
# need an exact comparison, or
2419
# 2) the numbers are small enough that converting to the
2420
# interval field is more work than the exact comparison.
2421
compare = _m**guess
2422
if self < compare:
2423
guess = guess - 1
2424
elif n_log2 < 5000:
2425
# for input with small exact log, it's very fast to work in exact
2426
# integer arithmetic starting from log2 approximations
2427
guess = self._exact_log_log2_iter(_m)
2428
else:
2429
# finally, we are out of easy cases this subroutine uses interval
2430
# arithmetic to guess and check the exact log.
2431
guess = self._exact_log_mpfi_log(_m)
2432
2433
result = PY_NEW(Integer)
2434
mpz_set_ui(result.value,guess)
2435
return result
2436
2437
def log(self, m=None, prec=None):
2438
r"""
2439
Returns symbolic log by default, unless the logarithm is exact (for
2440
an integer base). When precision is given, the RealField
2441
approximation to that bit precision is used.
2442
2443
This function is provided primarily so that Sage integers may be
2444
treated in the same manner as real numbers when convenient. Direct
2445
use of exact_log is probably best for arithmetic log computation.
2446
2447
INPUT:
2448
2449
- ``m`` - default: natural log base e
2450
2451
- ``prec`` - integer (default: None): if None, returns
2452
symbolic, else to given bits of precision as in RealField
2453
2454
EXAMPLES::
2455
2456
sage: Integer(124).log(5)
2457
log(124)/log(5)
2458
sage: Integer(124).log(5,100)
2459
2.9950093311241087454822446806
2460
sage: Integer(125).log(5)
2461
3
2462
sage: Integer(125).log(5,prec=53)
2463
3.00000000000000
2464
sage: log(Integer(125))
2465
log(125)
2466
2467
For extremely large numbers, this works::
2468
2469
sage: x = 3^100000
2470
sage: log(x,3)
2471
100000
2472
2473
With the new Pynac symbolic backend, log(x) also
2474
works in a reasonable amount of time for this x::
2475
2476
sage: x = 3^100000
2477
sage: log(x)
2478
log(1334971414230...5522000001)
2479
2480
But approximations are probably more useful in this
2481
case, and work to as high a precision as we desire::
2482
2483
sage: x.log(3,53) # default precision for RealField
2484
100000.000000000
2485
sage: (x+1).log(3,53)
2486
100000.000000000
2487
sage: (x+1).log(3,1000)
2488
100000.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
2489
2490
We can use non-integer bases, with default e::
2491
2492
sage: x.log(2.5,prec=53)
2493
119897.784671579
2494
2495
We also get logarithms of negative integers, via the
2496
symbolic ring, using the branch from `-pi` to `pi`::
2497
2498
sage: log(-1)
2499
I*pi
2500
2501
The logarithm of zero is done likewise::
2502
2503
sage: log(0)
2504
-Infinity
2505
"""
2506
if mpz_sgn(self.value) <= 0:
2507
from sage.symbolic.all import SR
2508
return SR(self).log()
2509
if m <= 0 and m != None:
2510
raise ValueError, "m must be positive"
2511
if prec:
2512
from sage.rings.real_mpfr import RealField
2513
if m is None:
2514
return RealField(prec)(self).log()
2515
return RealField(prec)(self).log(m)
2516
if type(m)==Integer and type(self)==Integer and m**(self.exact_log(m))==self:
2517
return self.exact_log(m)
2518
2519
from sage.symbolic.all import SR
2520
from sage.functions.log import function_log
2521
if m is None:
2522
return function_log(self,dont_call_method_on_arg=True)
2523
return function_log(self,dont_call_method_on_arg=True)/\
2524
function_log(m,dont_call_method_on_arg=True)
2525
2526
def exp(self, prec=None):
2527
r"""
2528
Returns the exponential function of self as a real number.
2529
2530
This function is provided only so that Sage integers may be treated
2531
in the same manner as real numbers when convenient.
2532
2533
INPUT:
2534
2535
2536
- ``prec`` - integer (default: None): if None, returns
2537
symbolic, else to given bits of precision as in RealField
2538
2539
2540
EXAMPLES::
2541
2542
sage: Integer(8).exp()
2543
e^8
2544
sage: Integer(8).exp(prec=100)
2545
2980.9579870417282747435920995
2546
sage: exp(Integer(8))
2547
e^8
2548
2549
For even fairly large numbers, this may not be useful.
2550
2551
::
2552
2553
sage: y=Integer(145^145)
2554
sage: y.exp()
2555
e^25024207011349079210459585279553675697932183658421565260323592409432707306554163224876110094014450895759296242775250476115682350821522931225499163750010280453185147546962559031653355159703678703793369785727108337766011928747055351280379806937944746847277089168867282654496776717056860661614337004721164703369140625
2556
sage: y.exp(prec=53) # default RealField precision
2557
+infinity
2558
"""
2559
from sage.functions.all import exp
2560
res = exp(self, dont_call_method_on_arg=True)
2561
if prec:
2562
return res.n(prec=prec)
2563
return res
2564
2565
def prime_to_m_part(self, m):
2566
"""
2567
Returns the prime-to-m part of self, i.e., the largest divisor of
2568
self that is coprime to m.
2569
2570
INPUT:
2571
2572
- ``m`` - Integer
2573
2574
OUTPUT: Integer
2575
2576
EXAMPLES::
2577
2578
sage: z = 43434
2579
sage: z.prime_to_m_part(20)
2580
21717
2581
"""
2582
late_import()
2583
return sage.rings.arith.prime_to_m_part(self, m)
2584
2585
def prime_divisors(self):
2586
"""
2587
The prime divisors of self, sorted in increasing order. If n is
2588
negative, we do *not* include -1 among the prime divisors, since
2589
-1 is not a prime number.
2590
2591
EXAMPLES::
2592
2593
sage: a = 1; a.prime_divisors()
2594
[]
2595
sage: a = 100; a.prime_divisors()
2596
[2, 5]
2597
sage: a = -100; a.prime_divisors()
2598
[2, 5]
2599
sage: a = 2004; a.prime_divisors()
2600
[2, 3, 167]
2601
"""
2602
late_import()
2603
return sage.rings.arith.prime_divisors(self)
2604
2605
prime_factors = prime_divisors
2606
2607
def divisors(self):
2608
"""
2609
Returns a list of all positive integer divisors of the integer
2610
self.
2611
2612
EXAMPLES::
2613
2614
sage: a = -3; a.divisors()
2615
[1, 3]
2616
sage: a = 6; a.divisors()
2617
[1, 2, 3, 6]
2618
sage: a = 28; a.divisors()
2619
[1, 2, 4, 7, 14, 28]
2620
sage: a = 2^5; a.divisors()
2621
[1, 2, 4, 8, 16, 32]
2622
sage: a = 100; a.divisors()
2623
[1, 2, 4, 5, 10, 20, 25, 50, 100]
2624
sage: a = 1; a.divisors()
2625
[1]
2626
sage: a = 0; a.divisors()
2627
Traceback (most recent call last):
2628
...
2629
ValueError: n must be nonzero
2630
sage: a = 2^3 * 3^2 * 17; a.divisors()
2631
[1, 2, 3, 4, 6, 8, 9, 12, 17, 18, 24, 34, 36, 51, 68, 72, 102, 136, 153, 204, 306, 408, 612, 1224]
2632
sage: a = odd_part(factorial(31))
2633
sage: v = a.divisors(); len(v)
2634
172800
2635
sage: prod(e+1 for p,e in factor(a))
2636
172800
2637
sage: all([t.divides(a) for t in v])
2638
True
2639
2640
.. note::
2641
2642
If one first computes all the divisors and then sorts it,
2643
the sorting step can easily dominate the runtime. Note,
2644
however, that (non-negative) multiplication on the left
2645
preserves relative order. One can leverage this fact to
2646
keep the list in order as one computes it using a process
2647
similar to that of the merge sort when adding new elements.
2648
"""
2649
cdef list all, prev, sorted
2650
cdef long tip, top
2651
cdef long i, j, e, ee
2652
cdef Integer apn, p, pn, z, all_tip
2653
2654
if not self:
2655
raise ValueError, "n must be nonzero"
2656
f = self.factor()
2657
2658
# All of the declarations below are for optimizing the word-sized
2659
# case. Operations are performed in c as far as possible without
2660
# overflow before moving to python objects.
2661
cdef long long p_c, pn_c, apn_c
2662
cdef long all_len, sorted_len, prev_len
2663
cdef long long* ptr
2664
cdef long long* empty_c
2665
cdef long long* swap_tmp
2666
cdef long long* all_c
2667
cdef long long* sorted_c
2668
cdef long long* prev_c
2669
2670
cdef long divisor_count = 1
2671
for p,e in f: divisor_count *= (1+e)
2672
ptr = <long long*>sage_malloc(sizeof(long long) * 3 * divisor_count)
2673
if ptr == NULL:
2674
raise MemoryError
2675
all_c = ptr
2676
sorted_c = ptr + divisor_count
2677
prev_c = ptr + (2*divisor_count)
2678
2679
# These are used to keep track of whether or not we are able to
2680
# perform the operations in machine words. A factor of two safety
2681
# margin is added to cover any floating-point rounding issues.
2682
cdef bint fits_c = True
2683
cdef double cur_max = 1
2684
cdef double fits_max = 2.0**(sizeof(long long)*8-2)
2685
2686
sorted_c[0] = 1
2687
sorted_len = 1
2688
2689
for p, e in f:
2690
2691
cur_max *= (<double>p)**e
2692
if fits_c and cur_max > fits_max:
2693
sorted = []
2694
for i from 0 <= i < sorted_len:
2695
z = <Integer>PY_NEW(Integer)
2696
mpz_set_longlong(z.value, sorted_c[i])
2697
sorted.append(z)
2698
sage_free(ptr)
2699
fits_c = False
2700
2701
# The two cases below are essentially the same algorithm, one
2702
# operating on Integers in Python lists, the other on long longs.
2703
if fits_c:
2704
2705
pn_c = p_c = p
2706
2707
swap_tmp = sorted_c
2708
sorted_c = prev_c
2709
prev_c = swap_tmp
2710
prev_len = sorted_len
2711
sorted_len = 0
2712
2713
tip = 0
2714
prev_c[prev_len] = prev_c[prev_len-1] * pn_c
2715
for i from 0 <= i < prev_len:
2716
apn_c = prev_c[i] * pn_c
2717
while prev_c[tip] < apn_c:
2718
sorted_c[sorted_len] = prev_c[tip]
2719
sorted_len += 1
2720
tip += 1
2721
sorted_c[sorted_len] = apn_c
2722
sorted_len += 1
2723
2724
for ee in range(1, e):
2725
2726
swap_tmp = all_c
2727
all_c = sorted_c
2728
sorted_c = swap_tmp
2729
all_len = sorted_len
2730
sorted_len = 0
2731
2732
pn_c *= p_c
2733
tip = 0
2734
all_c[all_len] = prev_c[prev_len-1] * pn_c
2735
for i from 0 <= i < prev_len:
2736
apn_c = prev_c[i] * pn_c
2737
while all_c[tip] < apn_c:
2738
sorted_c[sorted_len] = all_c[tip]
2739
sorted_len += 1
2740
tip += 1
2741
sorted_c[sorted_len] = apn_c
2742
sorted_len += 1
2743
2744
else:
2745
prev = sorted
2746
pn = <Integer>PY_NEW(Integer)
2747
mpz_set_ui(pn.value, 1)
2748
for ee in range(e):
2749
all = sorted
2750
sorted = []
2751
tip = 0
2752
top = len(all)
2753
mpz_mul(pn.value, pn.value, p.value) # pn *= p
2754
for a in prev:
2755
# apn = a*pn
2756
apn = <Integer>PY_NEW(Integer)
2757
mpz_mul(apn.value, (<Integer>a).value, pn.value)
2758
while tip < top:
2759
all_tip = <Integer>all[tip]
2760
if mpz_cmp(all_tip.value, apn.value) > 0:
2761
break
2762
sorted.append(all_tip)
2763
tip += 1
2764
sorted.append(apn)
2765
2766
if fits_c:
2767
# all the data is in sorted_c
2768
sorted = []
2769
for i from 0 <= i < sorted_len:
2770
z = <Integer>PY_NEW(Integer)
2771
mpz_set_longlong(z.value, sorted_c[i])
2772
sorted.append(z)
2773
sage_free(ptr)
2774
2775
return sorted
2776
2777
2778
def __pos__(self):
2779
"""
2780
EXAMPLES::
2781
2782
sage: z=43434
2783
sage: z.__pos__()
2784
43434
2785
"""
2786
return self
2787
2788
def __abs__(self):
2789
"""
2790
Computes `|self|`
2791
2792
EXAMPLES::
2793
2794
sage: z = -1
2795
sage: abs(z)
2796
1
2797
sage: abs(z) == abs(1)
2798
True
2799
"""
2800
cdef Integer x = PY_NEW(Integer)
2801
mpz_abs(x.value, self.value)
2802
return x
2803
2804
def sign(self):
2805
"""
2806
Returns the sign of this integer, which is -1, 0, or 1
2807
depending on whether this number is negative, zero, or positive
2808
respectively.
2809
2810
OUTPUT: Integer
2811
2812
EXAMPLES::
2813
2814
sage: 500.sign()
2815
1
2816
sage: 0.sign()
2817
0
2818
sage: (-10^43).sign()
2819
-1
2820
"""
2821
return smallInteger(mpz_sgn(self.value))
2822
2823
def __mod__(x, y):
2824
r"""
2825
Returns x modulo y.
2826
2827
EXAMPLES::
2828
2829
sage: z = 43
2830
sage: z % 2
2831
1
2832
sage: z % 0
2833
Traceback (most recent call last):
2834
...
2835
ZeroDivisionError: Integer modulo by zero
2836
sage: -5 % 7
2837
2
2838
sage: -5 % -7
2839
-5
2840
sage: 5 % -7
2841
-2
2842
2843
TESTS::
2844
2845
sage: signs = [(11,5), (11,-5), (-11,5), (-11,-5)]
2846
sage: control = [int(a) % int(b) for a, b in signs]
2847
sage: [a % b for a,b in signs] == control
2848
True
2849
sage: [a % int(b) for a,b in signs] == control
2850
True
2851
sage: [int(a) % b for a,b in signs] == control
2852
True
2853
2854
This example caused trouble in trac #6083::
2855
2856
sage: a = next_prime(2**31)
2857
sage: b = Integers(a)(100)
2858
sage: a % b
2859
59
2860
"""
2861
cdef Integer z = PY_NEW(Integer)
2862
cdef long yy, res
2863
2864
# first case: Integer % Integer
2865
if PY_TYPE(x) is PY_TYPE(y):
2866
if not mpz_sgn((<Integer>y).value):
2867
raise ZeroDivisionError, "Integer modulo by zero"
2868
if mpz_size((<Integer>x).value) > 100000:
2869
sig_on()
2870
mpz_fdiv_r(z.value, (<Integer>x).value, (<Integer>y).value)
2871
sig_off()
2872
else:
2873
mpz_fdiv_r(z.value, (<Integer>x).value, (<Integer>y).value)
2874
return z
2875
2876
# next: Integer % python int
2877
elif PyInt_CheckExact(y):
2878
yy = PyInt_AS_LONG(y)
2879
if yy > 0:
2880
mpz_fdiv_r_ui(z.value, (<Integer>x).value, yy)
2881
elif yy == 0:
2882
raise ZeroDivisionError, "Integer modulo by zero"
2883
else:
2884
res = mpz_fdiv_r_ui(z.value, (<Integer>x).value, -yy)
2885
if res:
2886
mpz_sub_ui(z.value, z.value, -yy)
2887
return z
2888
2889
# all other cases
2890
else:
2891
try:
2892
# we explicitly try coercing both to ZZ here to
2893
# avoid infinite loops in some cases (such as
2894
# Integers and Integers(n)), see trac #6083
2895
x = integer(x)
2896
y = integer(y)
2897
return x % y
2898
except ValueError:
2899
return bin_op(x, y, operator.mod)
2900
2901
def quo_rem(Integer self, other):
2902
"""
2903
Returns the quotient and the remainder of self divided by other.
2904
Note that the remainder returned is always either zero or of the
2905
same sign as other.
2906
2907
INPUT:
2908
2909
- ``other`` - the divisor
2910
2911
OUTPUT:
2912
2913
- ``q`` - the quotient of self/other
2914
2915
- ``r`` - the remainder of self/other
2916
2917
EXAMPLES::
2918
2919
sage: z = Integer(231)
2920
sage: z.quo_rem(2)
2921
(115, 1)
2922
sage: z.quo_rem(-2)
2923
(-116, -1)
2924
sage: z.quo_rem(0)
2925
Traceback (most recent call last):
2926
...
2927
ZeroDivisionError: Integer division by zero
2928
2929
sage: a = ZZ.random_element(10**50)
2930
sage: b = ZZ.random_element(10**15)
2931
sage: q, r = a.quo_rem(b)
2932
sage: q*b + r == a
2933
True
2934
2935
sage: 3.quo_rem(ZZ['x'].0)
2936
(0, 3)
2937
2938
TESTS:
2939
2940
The divisor can be rational as well, although the remainder
2941
will always be zero (trac #7965)::
2942
2943
sage: 5.quo_rem(QQ(2))
2944
(5/2, 0)
2945
sage: 5.quo_rem(2/3)
2946
(15/2, 0)
2947
2948
"""
2949
cdef Integer q = PY_NEW(Integer)
2950
cdef Integer r = PY_NEW(Integer)
2951
cdef long d, res
2952
2953
if PyInt_CheckExact(other):
2954
d = PyInt_AS_LONG(other)
2955
if d > 0:
2956
mpz_fdiv_qr_ui(q.value, r.value, self.value, d)
2957
elif d == 0:
2958
raise ZeroDivisionError, "Integer division by zero"
2959
else:
2960
res = mpz_fdiv_qr_ui(q.value, r.value, self.value, -d)
2961
mpz_neg(q.value, q.value)
2962
if res:
2963
mpz_sub_ui(q.value, q.value, 1)
2964
mpz_sub_ui(r.value, r.value, -d)
2965
2966
elif PY_TYPE_CHECK_EXACT(other, Integer):
2967
if mpz_sgn((<Integer>other).value) == 0:
2968
raise ZeroDivisionError, "Integer division by zero"
2969
if mpz_size((<Integer>x).value) > 100000:
2970
sig_on()
2971
mpz_fdiv_qr(q.value, r.value, self.value, (<Integer>other).value)
2972
sig_off()
2973
else:
2974
mpz_fdiv_qr(q.value, r.value, self.value, (<Integer>other).value)
2975
2976
else:
2977
left, right = canonical_coercion(self, other)
2978
return left.quo_rem(right)
2979
2980
return q, r
2981
2982
def powermod(self, exp, mod):
2983
"""
2984
Compute self\*\*exp modulo mod.
2985
2986
EXAMPLES::
2987
2988
sage: z = 2
2989
sage: z.powermod(31,31)
2990
2
2991
sage: z.powermod(0,31)
2992
1
2993
sage: z.powermod(-31,31) == 2^-31 % 31
2994
True
2995
2996
As expected, the following is invalid::
2997
2998
sage: z.powermod(31,0)
2999
Traceback (most recent call last):
3000
...
3001
ZeroDivisionError: cannot raise to a power modulo 0
3002
"""
3003
cdef Integer x, _exp, _mod
3004
_exp = Integer(exp); _mod = Integer(mod)
3005
if mpz_cmp_si(_mod.value,0) == 0:
3006
raise ZeroDivisionError, "cannot raise to a power modulo 0"
3007
3008
x = PY_NEW(Integer)
3009
3010
sig_on()
3011
mpz_powm(x.value, self.value, _exp.value, _mod.value)
3012
sig_off()
3013
3014
return x
3015
3016
def rational_reconstruction(self, Integer m):
3017
"""
3018
Return the rational reconstruction of this integer modulo m, i.e.,
3019
the unique (if it exists) rational number that reduces to self
3020
modulo m and whose numerator and denominator is bounded by
3021
sqrt(m/2).
3022
3023
EXAMPLES::
3024
3025
sage: (3/7)%100
3026
29
3027
sage: (29).rational_reconstruction(100)
3028
3/7
3029
3030
TEST:
3031
3032
Check that ticket #9345 is fixed::
3033
3034
sage: ZZ(1).rational_reconstruction(0)
3035
Traceback (most recent call last):
3036
...
3037
ZeroDivisionError: The modulus cannot be zero
3038
sage: m = ZZ.random_element(-10^6,10^6)
3039
sage: m.rational_reconstruction(0)
3040
Traceback (most recent call last):
3041
...
3042
ZeroDivisionError: The modulus cannot be zero
3043
"""
3044
import rational
3045
return rational.pyrex_rational_reconstruction(self, m)
3046
3047
def powermodm_ui(self, exp, mod):
3048
r"""
3049
Computes self\*\*exp modulo mod, where exp is an unsigned long
3050
integer.
3051
3052
EXAMPLES::
3053
3054
sage: z = 32
3055
sage: z.powermodm_ui(2, 4)
3056
0
3057
sage: z.powermodm_ui(2, 14)
3058
2
3059
sage: z.powermodm_ui(2^32-2, 14)
3060
2
3061
sage: z.powermodm_ui(2^32-1, 14)
3062
Traceback (most recent call last): # 32-bit
3063
... # 32-bit
3064
OverflowError: exp (=4294967295) must be <= 4294967294 # 32-bit
3065
8 # 64-bit
3066
sage: z.powermodm_ui(2^65, 14)
3067
Traceback (most recent call last):
3068
...
3069
OverflowError: exp (=36893488147419103232) must be <= 4294967294 # 32-bit
3070
OverflowError: exp (=36893488147419103232) must be <= 18446744073709551614 # 64-bit
3071
"""
3072
if exp < 0:
3073
raise ValueError, "exp (=%s) must be nonnegative"%exp
3074
elif exp > MAX_UNSIGNED_LONG:
3075
raise OverflowError, "exp (=%s) must be <= %s"%(exp, MAX_UNSIGNED_LONG)
3076
cdef Integer x, _mod
3077
_mod = Integer(mod)
3078
x = PY_NEW(Integer)
3079
3080
sig_on()
3081
mpz_powm_ui(x.value, self.value, exp, _mod.value)
3082
sig_off()
3083
3084
return x
3085
3086
def __int__(self):
3087
"""
3088
Return the Python int (or long) corresponding to this Sage
3089
integer.
3090
3091
EXAMPLES::
3092
3093
sage: n = 920938; n
3094
920938
3095
sage: int(n)
3096
920938
3097
sage: type(n.__int__())
3098
<type 'int'>
3099
sage: n = 99028390823409823904823098490238409823490820938; n
3100
99028390823409823904823098490238409823490820938
3101
sage: type(n.__int__())
3102
<type 'long'>
3103
"""
3104
# TODO -- this crashes on sage.math, since it is evidently written incorrectly.
3105
return mpz_get_pyintlong(self.value)
3106
#return int(mpz_get_pylong(self.value))
3107
3108
def __long__(self):
3109
"""
3110
Return long integer corresponding to this Sage integer.
3111
3112
EXAMPLES::
3113
3114
sage: n = 9023408290348092849023849820934820938490234290; n
3115
9023408290348092849023849820934820938490234290
3116
sage: long(n)
3117
9023408290348092849023849820934820938490234290L
3118
sage: n = 920938; n
3119
920938
3120
sage: long(n)
3121
920938L
3122
sage: n.__long__()
3123
920938L
3124
"""
3125
return mpz_get_pylong(self.value)
3126
3127
def __float__(self):
3128
"""
3129
Return double precision floating point representation of this
3130
integer.
3131
3132
EXAMPLES::
3133
3134
sage: n = Integer(17); float(n)
3135
17.0
3136
sage: n = Integer(902834098234908209348209834092834098); float(n)
3137
9.028340982349081e+35
3138
sage: n = Integer(-57); float(n)
3139
-57.0
3140
sage: n.__float__()
3141
-57.0
3142
sage: type(n.__float__())
3143
<type 'float'>
3144
"""
3145
return mpz_get_d(self.value)
3146
3147
def _rpy_(self):
3148
"""
3149
Returns int(self) so that rpy can convert self into an object it
3150
knows how to work with.
3151
3152
EXAMPLES::
3153
3154
sage: n = 100
3155
sage: n._rpy_()
3156
100
3157
sage: type(n._rpy_())
3158
<type 'int'>
3159
"""
3160
return self.__int__()
3161
3162
def __hash__(self):
3163
"""
3164
Return the hash of this integer.
3165
3166
This agrees with the Python hash of the corresponding Python int or
3167
long.
3168
3169
EXAMPLES::
3170
3171
sage: n = -920384; n.__hash__()
3172
-920384
3173
sage: hash(int(n))
3174
-920384
3175
sage: n = -920390823904823094890238490238484; n.__hash__()
3176
-873977844 # 32-bit
3177
6874330978542788722 # 64-bit
3178
sage: hash(long(n))
3179
-873977844 # 32-bit
3180
6874330978542788722 # 64-bit
3181
3182
TESTS::
3183
3184
sage: hash(0)
3185
0
3186
sage: hash(-1)
3187
-2
3188
sage: n = 2^31 + 2^63 + 2^95 + 2^127 + 2^128*(2^32-2)
3189
sage: hash(n) == hash(long(n))
3190
True
3191
sage: hash(n-1) == hash(long(n-1))
3192
True
3193
sage: hash(-n) == hash(long(-n))
3194
True
3195
sage: hash(1-n) == hash(long(1-n))
3196
True
3197
sage: n = 2^63 + 2^127 + 2^191 + 2^255 + 2^256*(2^64-2)
3198
sage: hash(n) == hash(long(n))
3199
True
3200
sage: hash(n-1) == hash(long(n-1))
3201
True
3202
sage: hash(-n) == hash(long(-n))
3203
True
3204
sage: hash(1-n) == hash(long(1-n))
3205
True
3206
3207
These tests come from Trac #4957:
3208
3209
sage: n = 2^31 + 2^13
3210
sage: hash(n)
3211
-2147475456 # 32-bit
3212
2147491840 # 64-bit
3213
sage: hash(n) == hash(int(n))
3214
True
3215
sage: n = 2^63 + 2^13
3216
sage: hash(n)
3217
-2147475456 # 32-bit
3218
-9223372036854767616 # 64-bit
3219
sage: hash(n) == hash(int(n))
3220
True
3221
"""
3222
return mpz_pythonhash(self.value)
3223
3224
cdef hash_c(self):
3225
"""
3226
A C version of the __hash__ function.
3227
"""
3228
return mpz_pythonhash(self.value)
3229
3230
def trial_division(self, long bound=LONG_MAX, long start=2):
3231
"""
3232
Return smallest prime divisor of self up to bound, beginning
3233
checking at start, or abs(self) if no such divisor is found.
3234
3235
INPUT:
3236
3237
- ``bound`` -- a positive integer that fits in a C signed long
3238
- ``start`` -- a positive integer that fits in a C signed long
3239
3240
OUTPUT:
3241
3242
- a positive integer
3243
3244
EXAMPLES::
3245
3246
sage: n = next_prime(10^6)*next_prime(10^7); n.trial_division()
3247
1000003
3248
sage: (-n).trial_division()
3249
1000003
3250
sage: n.trial_division(bound=100)
3251
10000049000057
3252
sage: n.trial_division(bound=-10)
3253
Traceback (most recent call last):
3254
...
3255
ValueError: bound must be positive
3256
sage: n.trial_division(bound=0)
3257
Traceback (most recent call last):
3258
...
3259
ValueError: bound must be positive
3260
sage: ZZ(0).trial_division()
3261
Traceback (most recent call last):
3262
...
3263
ValueError: self must be nonzero
3264
3265
sage: n = next_prime(10^5) * next_prime(10^40); n.trial_division()
3266
100003
3267
sage: n.trial_division(bound=10^4)
3268
1000030000000000000000000000000000000012100363
3269
sage: (-n).trial_division(bound=10^4)
3270
1000030000000000000000000000000000000012100363
3271
sage: (-n).trial_division()
3272
100003
3273
sage: n = 2 * next_prime(10^40); n.trial_division()
3274
2
3275
sage: n = 3 * next_prime(10^40); n.trial_division()
3276
3
3277
sage: n = 5 * next_prime(10^40); n.trial_division()
3278
5
3279
sage: n = 2 * next_prime(10^4); n.trial_division()
3280
2
3281
sage: n = 3 * next_prime(10^4); n.trial_division()
3282
3
3283
sage: n = 5 * next_prime(10^4); n.trial_division()
3284
5
3285
3286
You can specify a starting point::
3287
3288
sage: n = 3*5*101*103
3289
sage: n.trial_division(start=50)
3290
101
3291
"""
3292
if bound <= 0:
3293
raise ValueError, "bound must be positive"
3294
if mpz_sgn(self.value) == 0:
3295
raise ValueError, "self must be nonzero"
3296
cdef unsigned long n, m=7, i=1, limit, dif[8]
3297
if start > 7:
3298
# We need to find i.
3299
m = start % 30
3300
if 0 <= m <= 1:
3301
i = 0; m = start + (1-m)
3302
elif 1 < m <= 7:
3303
i = 1; m = start + (7-m)
3304
elif 7 < m <= 11:
3305
i = 2; m = start + (11-m)
3306
elif 11 < m <= 13:
3307
i = 3; m = start + (13-m)
3308
elif 13 < m <= 17:
3309
i = 4; m = start + (17-m)
3310
elif 17 < m <= 19:
3311
i = 5; m = start + (19-m)
3312
elif 19 < m <= 23:
3313
i = 6; m = start + (23-m)
3314
elif 23 < m <= 29:
3315
i = 7; m = start + (29-m)
3316
dif[0]=6;dif[1]=4;dif[2]=2;dif[3]=4;dif[4]=2;dif[5]=4;dif[6]=6;dif[7]=2
3317
cdef Integer x = PY_NEW(Integer)
3318
if mpz_fits_ulong_p(self.value):
3319
n = mpz_get_ui(self.value) # ignores the sign automatically
3320
if n == 1: return one
3321
if start <= 2 and n%2==0:
3322
mpz_set_ui(x.value,2); return x
3323
if start <= 3 and n%3==0:
3324
mpz_set_ui(x.value,3); return x
3325
if start <= 5 and n%5==0:
3326
mpz_set_ui(x.value,5); return x
3327
limit = <unsigned long> sqrt_double(<double> n)
3328
if bound < limit: limit = bound
3329
# Algorithm: only trial divide by numbers that
3330
# are congruent to 1,7,11,13,17,19,23,29 mod 30=2*3*5.
3331
while m <= limit:
3332
if n%m == 0:
3333
mpz_set_ui(x.value, m); return x
3334
m += dif[i%8]
3335
i += 1
3336
mpz_abs(x.value, self.value)
3337
return x
3338
else:
3339
# self is big -- it doesn't fit in unsigned long.
3340
if start <= 2 and mpz_even_p(self.value):
3341
mpz_set_ui(x.value,2); return x
3342
if start <= 3 and mpz_divisible_ui_p(self.value,3):
3343
mpz_set_ui(x.value,3); return x
3344
if start <= 5 and mpz_divisible_ui_p(self.value,5):
3345
mpz_set_ui(x.value,5); return x
3346
3347
# x.value = floor(sqrt(self.value))
3348
sig_on()
3349
mpz_abs(x.value, self.value)
3350
mpz_sqrt(x.value, x.value)
3351
if mpz_cmp_si(x.value, bound) < 0:
3352
limit = mpz_get_ui(x.value)
3353
else:
3354
limit = bound
3355
while m <= limit:
3356
if mpz_divisible_ui_p(self.value, m):
3357
mpz_set_ui(x.value, m)
3358
sig_off()
3359
return x
3360
m += dif[i%8]
3361
i += 1
3362
mpz_abs(x.value, self.value)
3363
sig_off()
3364
return x
3365
3366
def factor(self, algorithm='pari', proof=None, limit=None, int_=False,
3367
verbose=0):
3368
"""
3369
Return the prime factorization of this integer as a
3370
formal Factorization object.
3371
3372
INPUT:
3373
3374
- ``algorithm`` - string
3375
3376
- ``'pari'`` - (default) use the PARI library
3377
3378
- ``'kash'`` - use the KASH computer algebra system (requires
3379
the optional kash package)
3380
3381
- ``'magma'`` - use the MAGMA computer algebra system (requires
3382
an installation of MAGMA)
3383
3384
- ``'qsieve'`` - use Bill Hart's quadratic sieve code;
3385
WARNING: this may not work as expected, see qsieve? for
3386
more information
3387
3388
- ``'ecm'`` - use ECM-GMP, an implementation of Hendrik
3389
Lenstra's elliptic curve method; WARNING: the factors
3390
returned may not be prime, see ecm.factor? for more
3391
information
3392
3393
- ``proof`` - bool (default: True) whether or not to
3394
prove primality of each factor (only applicable for PARI).
3395
3396
- ``limit`` - int or None (default: None) if limit is
3397
given it must fit in a signed int, and the factorization is done
3398
using trial division and primes up to limit.
3399
3400
OUTPUT:
3401
3402
- a Factorization object containing the prime factors and
3403
their multiplicities
3404
3405
EXAMPLES::
3406
3407
sage: n = 2^100 - 1; n.factor()
3408
3 * 5^3 * 11 * 31 * 41 * 101 * 251 * 601 * 1801 * 4051 * 8101 * 268501
3409
3410
This factorization can be converted into a list of pairs `(p,
3411
e)`, where `p` is prime and `e` is a positive integer. Each
3412
pair can also be accessed directly by its index (ordered by
3413
increasing size of the prime)::
3414
3415
sage: f = 60.factor()
3416
sage: list(f)
3417
[(2, 2), (3, 1), (5, 1)]
3418
sage: f[2]
3419
(5, 1)
3420
3421
Similarly, the factorization can be converted to a dictionary
3422
so the exponent can be extracted for each prime::
3423
3424
sage: f = (3^6).factor()
3425
sage: dict(f)
3426
{3: 6}
3427
sage: dict(f)[3]
3428
6
3429
3430
We use proof=False, which doesn't prove correctness of the primes
3431
that appear in the factorization::
3432
3433
sage: n = 920384092842390423848290348203948092384082349082
3434
sage: n.factor(proof=False)
3435
2 * 11 * 1531 * 4402903 * 10023679 * 619162955472170540533894518173
3436
sage: n.factor(proof=True)
3437
2 * 11 * 1531 * 4402903 * 10023679 * 619162955472170540533894518173
3438
3439
We factor using trial division only::
3440
3441
sage: n.factor(limit=1000)
3442
2 * 11 * 41835640583745019265831379463815822381094652231
3443
3444
We factor using a quadratic sieve algorithm::
3445
3446
sage: p = next_prime(10^20)
3447
sage: q = next_prime(10^21)
3448
sage: n = p*q
3449
sage: n.factor(algorithm='qsieve')
3450
doctest:... RuntimeWarning: the factorization returned
3451
by qsieve may be incomplete (the factors may not be prime)
3452
or even wrong; see qsieve? for details
3453
100000000000000000039 * 1000000000000000000117
3454
3455
We factor using the elliptic curve method::
3456
3457
sage: p = next_prime(10^15)
3458
sage: q = next_prime(10^21)
3459
sage: n = p*q
3460
sage: n.factor(algorithm='ecm')
3461
doctest:... RuntimeWarning: the factors returned by ecm
3462
are not guaranteed to be prime; see ecm.factor? for details
3463
1000000000000037 * 1000000000000000000117
3464
3465
TESTS::
3466
3467
sage: n.factor(algorithm='foobar')
3468
Traceback (most recent call last):
3469
...
3470
ValueError: Algorithm is not known
3471
"""
3472
from sage.structure.factorization import Factorization
3473
from sage.structure.factorization_integer import IntegerFactorization
3474
3475
cdef Integer n, p, unit
3476
cdef int i
3477
cdef n_factor_t f
3478
3479
if mpz_sgn(self.value) == 0:
3480
raise ArithmeticError, "Prime factorization of 0 not defined."
3481
3482
if mpz_sgn(self.value) > 0:
3483
n = self
3484
unit = one
3485
else:
3486
n = PY_NEW(Integer)
3487
unit = PY_NEW(Integer)
3488
mpz_neg(n.value, self.value)
3489
mpz_set_si(unit.value, -1)
3490
3491
if mpz_cmpabs_ui(n.value, 1) == 0:
3492
return IntegerFactorization([], unit=unit, unsafe=True,
3493
sort=False, simplify=False)
3494
3495
if limit is not None:
3496
from sage.rings.factorint import factor_trial_division
3497
return factor_trial_division(self, limit)
3498
3499
if mpz_fits_slong_p(n.value):
3500
if proof is None:
3501
from sage.structure.proof.proof import get_flag
3502
proof = get_flag(proof, "arithmetic")
3503
n_factor_init(&f)
3504
n_factor(&f, mpz_get_ui(n.value), proof)
3505
F = [(Integer(f.p[i]), int(f.exp[i])) for i from 0 <= i < f.num]
3506
F.sort()
3507
return IntegerFactorization(F, unit=unit, unsafe=True,
3508
sort=False, simplify=False)
3509
3510
if mpz_sizeinbase(n.value, 2) < 40:
3511
from sage.rings.factorint import factor_trial_division
3512
return factor_trial_division(self)
3513
3514
if algorithm == 'pari':
3515
from sage.rings.factorint import factor_using_pari
3516
F = factor_using_pari(n, int_=int_, debug_level=verbose, proof=proof)
3517
F.sort()
3518
return IntegerFactorization(F, unit=unit, unsafe=True,
3519
sort=False, simplify=False)
3520
elif algorithm in ['kash', 'magma']:
3521
if algorithm == 'kash':
3522
from sage.interfaces.all import kash as I
3523
else:
3524
from sage.interfaces.all import magma as I
3525
str_res = I.eval('Factorization(%s)'%n)
3526
# The result looks like "[ <n1, p1>, <p2, e2>, ... ]
3527
str_res = str_res.replace(']', '').replace('[', '').replace('>', '').replace('<', '').split(',')
3528
res = [int(s.strip()) for s in str_res]
3529
exp_type = int if int_ else Integer
3530
F = [(Integer(p), exp_type(e)) for p,e in zip(res[0::2], res[1::2])]
3531
return Factorization(F, unit)
3532
elif algorithm == 'qsieve':
3533
message = "the factorization returned by qsieve may be incomplete (the factors may not be prime) or even wrong; see qsieve? for details"
3534
from warnings import warn
3535
warn(message, RuntimeWarning, stacklevel=5)
3536
from sage.interfaces.qsieve import qsieve
3537
res = [(p, 1) for p in qsieve(n)[0]]
3538
F = IntegerFactorization(res, unit)
3539
return F
3540
elif algorithm == 'ecm':
3541
message = "the factors returned by ecm are not guaranteed to be prime; see ecm.factor? for details"
3542
from warnings import warn
3543
warn(message, RuntimeWarning, stacklevel=2)
3544
from sage.interfaces.ecm import ecm
3545
res = [(p, 1) for p in ecm.factor(n)]
3546
F = IntegerFactorization(res, unit)
3547
return F
3548
else:
3549
raise ValueError, "Algorithm is not known"
3550
3551
def support(self):
3552
"""
3553
Return a sorted list of the primes dividing this integer.
3554
3555
OUTPUT: The sorted list of primes appearing in the factorization of
3556
this rational with positive exponent.
3557
3558
EXAMPLES::
3559
3560
sage: factorial(10).support()
3561
[2, 3, 5, 7]
3562
sage: (-999).support()
3563
[3, 37]
3564
3565
Trying to find the support of 0 gives an arithmetic error::
3566
3567
sage: 0.support()
3568
Traceback (most recent call last):
3569
...
3570
ArithmeticError: Support of 0 not defined.
3571
"""
3572
if self.is_zero():
3573
raise ArithmeticError, "Support of 0 not defined."
3574
return sage.rings.arith.prime_factors(self)
3575
3576
def coprime_integers(self, m):
3577
"""
3578
Return the positive integers `< m` that are coprime to
3579
self.
3580
3581
EXAMPLES::
3582
3583
sage: n = 8
3584
sage: n.coprime_integers(8)
3585
[1, 3, 5, 7]
3586
sage: n.coprime_integers(11)
3587
[1, 3, 5, 7, 9]
3588
sage: n = 5; n.coprime_integers(10)
3589
[1, 2, 3, 4, 6, 7, 8, 9]
3590
sage: n.coprime_integers(5)
3591
[1, 2, 3, 4]
3592
sage: n = 99; n.coprime_integers(99)
3593
[1, 2, 4, 5, 7, 8, 10, 13, 14, 16, 17, 19, 20, 23, 25, 26, 28, 29, 31, 32, 34, 35, 37, 38, 40, 41, 43, 46, 47, 49, 50, 52, 53, 56, 58, 59, 61, 62, 64, 65, 67, 68, 70, 71, 73, 74, 76, 79, 80, 82, 83, 85, 86, 89, 91, 92, 94, 95, 97, 98]
3594
3595
AUTHORS:
3596
3597
- Naqi Jaffery (2006-01-24): examples
3598
3599
ALGORITHM: Naive - compute lots of GCD's. If this isn't good enough
3600
for you, please code something better and submit a patch.
3601
"""
3602
# TODO -- make VASTLY faster
3603
v = []
3604
for n in range(1,m):
3605
if self.gcd(n) == 1:
3606
v.append(Integer(n))
3607
return v
3608
3609
def divides(self, n):
3610
"""
3611
Return True if self divides n.
3612
3613
EXAMPLES::
3614
3615
sage: Z = IntegerRing()
3616
sage: Z(5).divides(Z(10))
3617
True
3618
sage: Z(0).divides(Z(5))
3619
False
3620
sage: Z(10).divides(Z(5))
3621
False
3622
"""
3623
cdef bint t
3624
cdef Integer _n
3625
_n = Integer(n)
3626
if mpz_sgn(self.value) == 0:
3627
return mpz_sgn(_n.value) == 0
3628
sig_on()
3629
t = mpz_divisible_p(_n.value, self.value)
3630
sig_off()
3631
return t
3632
3633
cpdef RingElement _valuation(Integer self, Integer p):
3634
r"""
3635
Return the p-adic valuation of self.
3636
3637
We do not require that p be prime, but it must be at least 2. For
3638
more documentation see ``valuation``
3639
3640
AUTHORS:
3641
3642
- David Roe (3/31/07)
3643
"""
3644
if mpz_sgn(self.value) == 0:
3645
return sage.rings.infinity.infinity
3646
if mpz_cmp_ui(p.value, 2) < 0:
3647
raise ValueError, "You can only compute the valuation with respect to a integer larger than 1."
3648
3649
cdef Integer v = PY_NEW(Integer)
3650
cdef mpz_t u
3651
mpz_init(u)
3652
sig_on()
3653
mpz_set_ui(v.value, mpz_remove(u, self.value, p.value))
3654
sig_off()
3655
mpz_clear(u)
3656
return v
3657
3658
cdef object _val_unit(Integer self, Integer p):
3659
r"""
3660
Returns a pair: the p-adic valuation of self, and the p-adic unit
3661
of self.
3662
3663
We do not require the p be prime, but it must be at least 2. For
3664
more documentation see ``val_unit``
3665
3666
AUTHORS:
3667
3668
- David Roe (2007-03-31)
3669
"""
3670
cdef Integer v, u
3671
if mpz_cmp_ui(p.value, 2) < 0:
3672
raise ValueError, "You can only compute the valuation with respect to a integer larger than 1."
3673
if self == 0:
3674
u = one
3675
return (sage.rings.infinity.infinity, u)
3676
v = PY_NEW(Integer)
3677
u = PY_NEW(Integer)
3678
sig_on()
3679
mpz_set_ui(v.value, mpz_remove(u.value, self.value, p.value))
3680
sig_off()
3681
return (v, u)
3682
3683
def valuation(self, p):
3684
"""
3685
Return the p-adic valuation of self.
3686
3687
INPUT:
3688
3689
- ``p`` - an integer at least 2.
3690
3691
EXAMPLE::
3692
3693
sage: n = 60
3694
sage: n.valuation(2)
3695
2
3696
sage: n.valuation(3)
3697
1
3698
sage: n.valuation(7)
3699
0
3700
sage: n.valuation(1)
3701
Traceback (most recent call last):
3702
...
3703
ValueError: You can only compute the valuation with respect to a integer larger than 1.
3704
3705
We do not require that p is a prime::
3706
3707
sage: (2^11).valuation(4)
3708
5
3709
"""
3710
return self._valuation(Integer(p))
3711
3712
# Alias for valuation
3713
ord = valuation
3714
3715
def val_unit(self, p):
3716
r"""
3717
Returns a pair: the p-adic valuation of self, and the p-adic unit
3718
of self.
3719
3720
INPUT:
3721
3722
- ``p`` - an integer at least 2.
3723
3724
OUTPUT:
3725
3726
- ``v_p(self)`` - the p-adic valuation of ``self``
3727
3728
- ``u_p(self)`` - ``self`` / `p^{v_p(\mathrm{self})}`
3729
3730
EXAMPLE::
3731
3732
sage: n = 60
3733
sage: n.val_unit(2)
3734
(2, 15)
3735
sage: n.val_unit(3)
3736
(1, 20)
3737
sage: n.val_unit(7)
3738
(0, 60)
3739
sage: (2^11).val_unit(4)
3740
(5, 2)
3741
sage: 0.val_unit(2)
3742
(+Infinity, 1)
3743
"""
3744
return self._val_unit(Integer(p))
3745
3746
def odd_part(self):
3747
r"""
3748
The odd part of the integer `n`. This is `n / 2^v`,
3749
where `v = \mathrm{valuation}(n,2)`.
3750
3751
IMPLEMENTATION:
3752
3753
Currently returns 0 when self is 0. This behaviour is fairly arbitrary,
3754
and in Sage 4.6 this special case was not handled at all, eventually
3755
propagating a TypeError. The caller should not rely on the behaviour
3756
in case self is 0.
3757
3758
EXAMPLES::
3759
3760
sage: odd_part(5)
3761
5
3762
sage: odd_part(4)
3763
1
3764
sage: odd_part(factorial(31))
3765
122529844256906551386796875
3766
"""
3767
cdef Integer odd
3768
cdef unsigned long bits
3769
3770
if mpz_cmpabs_ui(self.value, 1) <= 0:
3771
return self
3772
3773
odd = PY_NEW(Integer)
3774
bits = mpz_scan1(self.value, 0)
3775
mpz_tdiv_q_2exp(odd.value, self.value, bits)
3776
return odd
3777
3778
cdef Integer _divide_knowing_divisible_by(Integer self, Integer right):
3779
r"""
3780
Returns the integer self / right when self is divisible by right.
3781
3782
If self is not divisible by right, the return value is undefined,
3783
and may not even be close to self/right. For more documentation see
3784
``divide_knowing_divisible_by``
3785
3786
AUTHORS:
3787
3788
- David Roe (2007-03-31)
3789
"""
3790
if mpz_cmp_ui(right.value, 0) == 0:
3791
raise ZeroDivisionError
3792
cdef Integer x
3793
x = PY_NEW(Integer)
3794
if mpz_size(self.value) + mpz_size((<Integer>right).value) > 100000:
3795
# Only use the signal handler (to enable ctrl-c out) when the
3796
# quotient might take a while to compute
3797
sig_on()
3798
mpz_divexact(x.value, self.value, right.value)
3799
sig_off()
3800
else:
3801
mpz_divexact(x.value, self.value, right.value)
3802
return x
3803
3804
def divide_knowing_divisible_by(self, right):
3805
r"""
3806
Returns the integer self / right when self is divisible by right.
3807
3808
If self is not divisible by right, the return value is undefined,
3809
and may not even be close to self/right for multi-word integers.
3810
3811
EXAMPLES::
3812
3813
sage: a = 8; b = 4
3814
sage: a.divide_knowing_divisible_by(b)
3815
2
3816
sage: (100000).divide_knowing_divisible_by(25)
3817
4000
3818
sage: (100000).divide_knowing_divisible_by(26) # close (random)
3819
3846
3820
3821
However, often it's way off.
3822
3823
::
3824
3825
sage: a = 2^70; a
3826
1180591620717411303424
3827
sage: a // 11 # floor divide
3828
107326510974310118493
3829
sage: a.divide_knowing_divisible_by(11) # way off and possibly random
3830
43215361478743422388970455040
3831
"""
3832
return self._divide_knowing_divisible_by(right)
3833
3834
def _lcm(self, Integer n):
3835
"""
3836
Returns the least common multiple of self and `n`.
3837
3838
EXAMPLES::
3839
3840
sage: n = 60
3841
sage: n._lcm(150)
3842
300
3843
"""
3844
cdef Integer z = PY_NEW(Integer)
3845
sig_on()
3846
mpz_lcm(z.value, self.value, n.value)
3847
sig_off()
3848
return z
3849
3850
def denominator(self):
3851
"""
3852
Return the denominator of this integer, which of course is
3853
always 1.
3854
3855
EXAMPLES::
3856
3857
sage: x = 5
3858
sage: x.denominator()
3859
1
3860
sage: x = 0
3861
sage: x.denominator()
3862
1
3863
"""
3864
return one
3865
3866
def numerator(self):
3867
"""
3868
Return the numerator of this integer.
3869
3870
EXAMPLES::
3871
3872
sage: x = 5
3873
sage: x.numerator()
3874
5
3875
3876
::
3877
3878
sage: x = 0
3879
sage: x.numerator()
3880
0
3881
"""
3882
return self
3883
3884
def factorial(self):
3885
r"""
3886
Return the factorial `n! = 1 \cdot 2 \cdot 3 \cdots n`.
3887
3888
If the input does not fit in an ``unsigned long int`` a symbolic
3889
expression is returned.
3890
3891
EXAMPLES::
3892
3893
sage: for n in srange(7):
3894
... print n, n.factorial()
3895
0 1
3896
1 1
3897
2 2
3898
3 6
3899
4 24
3900
5 120
3901
6 720
3902
sage: 234234209384023842034.factorial()
3903
factorial(234234209384023842034)
3904
"""
3905
if mpz_sgn(self.value) < 0:
3906
raise ValueError, "factorial -- self = (%s) must be nonnegative"%self
3907
3908
if not mpz_fits_uint_p(self.value):
3909
from sage.functions.all import factorial
3910
return factorial(self, hold=True)
3911
3912
cdef Integer z = PY_NEW(Integer)
3913
3914
sig_on()
3915
mpz_fac_ui(z.value, mpz_get_ui(self.value))
3916
sig_off()
3917
3918
return z
3919
3920
@cython.cdivision(True)
3921
def multifactorial(self, int k):
3922
r"""
3923
Computes the k-th factorial `n!^{(k)}` of self. For k=1
3924
this is the standard factorial, and for k greater than one it is
3925
the product of every k-th terms down from self to k. The recursive
3926
definition is used to extend this function to the negative
3927
integers.
3928
3929
EXAMPLES::
3930
3931
sage: 5.multifactorial(1)
3932
120
3933
sage: 5.multifactorial(2)
3934
15
3935
sage: 23.multifactorial(2)
3936
316234143225
3937
sage: prod([1..23, step=2])
3938
316234143225
3939
sage: (-29).multifactorial(7)
3940
1/2640
3941
"""
3942
if k <= 0:
3943
raise ValueError, "multifactorial only defined for positive values of k"
3944
3945
if not mpz_fits_sint_p(self.value):
3946
raise ValueError, "multifactorial not implemented for n >= 2^32.\nThis is probably OK, since the answer would have billions of digits."
3947
3948
cdef int n = mpz_get_si(self.value)
3949
3950
# base case
3951
if 0 < n < k:
3952
return one
3953
3954
# easy to calculate
3955
elif n % k == 0:
3956
factorial = Integer(n/k).factorial()
3957
if k == 2:
3958
return factorial << (n/k)
3959
else:
3960
return factorial * Integer(k)**(n/k)
3961
3962
# negative base case
3963
elif -k < n < 0:
3964
return one / (self+k)
3965
3966
# reflection case
3967
elif n < -k:
3968
if (n/k) % 2:
3969
sign = -one
3970
else:
3971
sign = one
3972
return sign / Integer(-k-n).multifactorial(k)
3973
3974
# compute the actual product, optimizing the number of large
3975
# multiplications
3976
cdef int i,j
3977
3978
# we need (at most) log_2(#factors) concurrent sub-products
3979
cdef int prod_count = <int>ceil_c(log_c(n/k+1)/log_c(2))
3980
cdef mpz_t* sub_prods = <mpz_t*>sage_malloc(prod_count * sizeof(mpz_t))
3981
if sub_prods == NULL:
3982
raise MemoryError
3983
for i from 0 <= i < prod_count:
3984
mpz_init(sub_prods[i])
3985
3986
sig_on()
3987
3988
cdef residue = n % k
3989
cdef int tip = 0
3990
for i from 1 <= i <= n//k:
3991
mpz_set_ui(sub_prods[tip], k*i + residue)
3992
# for the i-th terms we use the bits of i to calculate how many
3993
# times we need to multiply "up" the stack of sub-products
3994
for j from 0 <= j < 32:
3995
if i & (1 << j):
3996
break
3997
tip -= 1
3998
mpz_mul(sub_prods[tip], sub_prods[tip], sub_prods[tip+1])
3999
tip += 1
4000
cdef int last = tip-1
4001
for tip from last > tip >= 0:
4002
mpz_mul(sub_prods[tip], sub_prods[tip], sub_prods[tip+1])
4003
4004
sig_off()
4005
4006
cdef Integer z = PY_NEW(Integer)
4007
mpz_swap(z.value, sub_prods[0])
4008
4009
for i from 0 <= i < prod_count:
4010
mpz_clear(sub_prods[i])
4011
sage_free(sub_prods)
4012
4013
return z
4014
4015
def gamma(self):
4016
r"""
4017
The gamma function on integers is the factorial function (shifted by
4018
one) on positive integers, and `\pm \infty` on non-positive integers.
4019
4020
EXAMPLES::
4021
4022
sage: gamma(5)
4023
24
4024
sage: gamma(0)
4025
Infinity
4026
sage: gamma(-1)
4027
Infinity
4028
sage: gamma(-2^150)
4029
Infinity
4030
"""
4031
if mpz_sgn(self.value) > 0:
4032
return (self-one).factorial()
4033
else:
4034
from sage.rings.infinity import unsigned_infinity
4035
return unsigned_infinity
4036
4037
def floor(self):
4038
"""
4039
Return the floor of self, which is just self since self is an
4040
integer.
4041
4042
EXAMPLES::
4043
4044
sage: n = 6
4045
sage: n.floor()
4046
6
4047
"""
4048
return self
4049
4050
def ceil(self):
4051
"""
4052
Return the ceiling of self, which is self since self is an
4053
integer.
4054
4055
EXAMPLES::
4056
4057
sage: n = 6
4058
sage: n.ceil()
4059
6
4060
"""
4061
return self
4062
4063
def real(self):
4064
"""
4065
Returns the real part of self, which is self.
4066
4067
EXAMPLES::
4068
4069
sage: Integer(-4).real()
4070
-4
4071
"""
4072
return self
4073
4074
def imag(self):
4075
"""
4076
Returns the imaginary part of self, which is zero.
4077
4078
EXAMPLES::
4079
4080
sage: Integer(9).imag()
4081
0
4082
"""
4083
return zero
4084
4085
def is_one(self):
4086
r"""
4087
Returns ``True`` if the integer is `1`, otherwise ``False``.
4088
4089
EXAMPLES::
4090
4091
sage: Integer(1).is_one()
4092
True
4093
sage: Integer(0).is_one()
4094
False
4095
"""
4096
return mpz_cmp_si(self.value, 1) == 0
4097
4098
def __nonzero__(self):
4099
r"""
4100
Returns ``True`` if the integer is not `0`, otherwise ``False``.
4101
4102
EXAMPLES::
4103
4104
sage: Integer(1).is_zero()
4105
False
4106
sage: Integer(0).is_zero()
4107
True
4108
"""
4109
return mpz_sgn(self.value) != 0
4110
4111
def is_integral(self):
4112
"""
4113
Return ``True`` since integers are integral, i.e.,
4114
satisfy a monic polynomial with integer coefficients.
4115
4116
EXAMPLES::
4117
4118
sage: Integer(3).is_integral()
4119
True
4120
"""
4121
return True
4122
4123
def is_unit(self):
4124
r"""
4125
Returns ``true`` if this integer is a unit, i.e., 1 or `-1`.
4126
4127
EXAMPLES::
4128
4129
sage: for n in srange(-2,3):
4130
... print n, n.is_unit()
4131
-2 False
4132
-1 True
4133
0 False
4134
1 True
4135
2 False
4136
"""
4137
return mpz_cmpabs_ui(self.value, 1) == 0
4138
4139
def is_square(self):
4140
r"""
4141
Returns ``True`` if self is a perfect square.
4142
4143
EXAMPLES::
4144
4145
sage: Integer(4).is_square()
4146
True
4147
sage: Integer(41).is_square()
4148
False
4149
"""
4150
return mpz_perfect_square_p(self.value)
4151
4152
is_power = deprecated_function_alias(12116, is_perfect_power)
4153
4154
def perfect_power(self):
4155
r"""
4156
Returns ``(a, b)``, where this integer is `a^b` and `b` is maximal.
4157
4158
If called on `-1`, `0` or `1`, `b` will be `1`, since there is no
4159
maximal value of `b`.
4160
4161
.. seealso::
4162
4163
- :meth:`is_perfect_power`: testing whether an integer is a perfect
4164
power is usually faster than finding `a` and `b`.
4165
- :meth:`is_prime_power`: checks whether the base is prime.
4166
- :meth:`is_power_of`: if you know the base already, this method is
4167
the fastest option.
4168
4169
EXAMPLES::
4170
4171
sage: 144.perfect_power()
4172
(12, 2)
4173
sage: 1.perfect_power()
4174
(1, 1)
4175
sage: 0.perfect_power()
4176
(0, 1)
4177
sage: (-1).perfect_power()
4178
(-1, 1)
4179
sage: (-8).perfect_power()
4180
(-2, 3)
4181
sage: (-4).perfect_power()
4182
(-4, 1)
4183
sage: (101^29).perfect_power()
4184
(101, 29)
4185
sage: (-243).perfect_power()
4186
(-3, 5)
4187
sage: (-64).perfect_power()
4188
(-4, 3)
4189
"""
4190
parians = self._pari_().ispower()
4191
return Integer(parians[1]), Integer(parians[0])
4192
4193
def global_height(self, prec=None):
4194
r"""
4195
Returns the absolute logarithmic height of this rational integer.
4196
4197
INPUT:
4198
4199
- ``prec`` (int) -- desired floating point precision (default:
4200
default RealField precision).
4201
4202
OUTPUT:
4203
4204
(real) The absolute logarithmic height of this rational integer.
4205
4206
ALGORITHM:
4207
4208
The height of the integer `n` is `\log |n|`.
4209
4210
EXAMPLES::
4211
4212
sage: ZZ(5).global_height()
4213
1.60943791243410
4214
sage: ZZ(-2).global_height(prec=100)
4215
0.69314718055994530941723212146
4216
sage: exp(_)
4217
2.0000000000000000000000000000
4218
"""
4219
from sage.rings.real_mpfr import RealField
4220
if prec is None:
4221
R = RealField()
4222
else:
4223
R = RealField(prec)
4224
if self.is_zero():
4225
return R.zero_element()
4226
return R(self).abs().log()
4227
4228
cdef bint _is_power_of(Integer self, Integer n):
4229
r"""
4230
Returns a non-zero int if there is an integer b with
4231
`\mathtt{self} = n^b`.
4232
4233
For more documentation see ``is_power_of``.
4234
4235
AUTHORS:
4236
4237
- David Roe (2007-03-31)
4238
"""
4239
cdef int a
4240
cdef unsigned long b, c
4241
cdef mpz_t u, sabs, nabs
4242
a = mpz_cmp_ui(n.value, 2)
4243
if a <= 0: # n <= 2
4244
if a == 0: # n == 2
4245
if mpz_popcount(self.value) == 1: #number of bits set in self == 1
4246
return 1
4247
else:
4248
return 0
4249
a = mpz_cmp_si(n.value, -2)
4250
if a >= 0: # -2 <= n < 2:
4251
a = mpz_get_si(n.value)
4252
if a == 1: # n == 1
4253
if mpz_cmp_ui(self.value, 1) == 0: # Only 1 is a power of 1
4254
return 1
4255
else:
4256
return 0
4257
elif a == 0: # n == 0
4258
if mpz_cmp_ui(self.value, 0) == 0 or mpz_cmp_ui(self.value, 1) == 0: # 0^0 = 1, 0^x = 0
4259
return 1
4260
else:
4261
return 0
4262
elif a == -1: # n == -1
4263
if mpz_cmp_ui(self.value, 1) == 0 or mpz_cmp_si(self.value, -1) == 0: # 1 and -1 are powers of -1
4264
return 1
4265
else:
4266
return 0
4267
elif a == -2: # n == -2
4268
mpz_init(sabs)
4269
mpz_abs(sabs, self.value)
4270
if mpz_popcount(sabs) == 1: # number of bits set in |self| == 1
4271
b = mpz_scan1(sabs, 0) % 2 # b == 1 if |self| is an odd power of 2, 0 if |self| is an even power
4272
mpz_clear(sabs)
4273
if (b == 1 and mpz_cmp_ui(self.value, 0) < 0) or (b == 0 and mpz_cmp_ui(self.value, 0) > 0):
4274
# An odd power of -2 is negative, an even power must be positive.
4275
return 1
4276
else: # number of bits set in |self| is not 1, so self cannot be a power of -2
4277
return 0
4278
else: # |self| is not a power of 2, so self cannot be a power of -2
4279
return 0
4280
else: # n < -2
4281
mpz_init(nabs)
4282
mpz_neg(nabs, n.value)
4283
if mpz_popcount(nabs) == 1: # |n| = 2^k for k >= 2. We special case this for speed
4284
mpz_init(sabs)
4285
mpz_abs(sabs, self.value)
4286
if mpz_popcount(sabs) == 1: # |self| = 2^L for some L >= 0.
4287
b = mpz_scan1(sabs, 0) # the bit that self is set at
4288
c = mpz_scan1(nabs, 0) # the bit that n is set at
4289
# Having obtained b and c, we're done with nabs and sabs (on this branch anyway)
4290
mpz_clear(nabs)
4291
mpz_clear(sabs)
4292
if b % c == 0: # Now we know that |self| is a power of |n|
4293
b = (b // c) % 2 # Whether b // c is even or odd determines whether (-2^c)^(b // c) is positive or negative
4294
a = mpz_cmp_ui(self.value, 0)
4295
if b == 0 and a > 0 or b == 1 and a < 0:
4296
# These two cases are that b // c is even and self positive, or b // c is odd and self negative
4297
return 1
4298
else: # The sign of self is wrong
4299
return 0
4300
else: # Since |self| is not a power of |n|, self cannot be a power of n
4301
return 0
4302
else: # self is not a power of 2, and thus cannot be a power of n, which is a power of 2.
4303
mpz_clear(nabs)
4304
mpz_clear(sabs)
4305
return 0
4306
else: # |n| is not a power of 2, so we use mpz_remove
4307
mpz_init(u)
4308
sig_on()
4309
b = mpz_remove(u, self.value, nabs)
4310
sig_off()
4311
# Having obtained b and u, we're done with nabs
4312
mpz_clear(nabs)
4313
if mpz_cmp_ui(u, 1) == 0: # self is a power of |n|
4314
mpz_clear(u)
4315
if b % 2 == 0: # an even power of |n|, and since self > 0, this means that self is a power of n
4316
return 1
4317
else:
4318
return 0
4319
elif mpz_cmp_si(u, -1) == 0: # -self is a power of |n|
4320
mpz_clear(u)
4321
if b % 2 == 1: # an odd power of |n|, and thus self is a power of n
4322
return 1
4323
else:
4324
return 0
4325
else: # |self| is not a power of |n|, so self cannot be a power of n
4326
mpz_clear(u)
4327
return 0
4328
elif mpz_popcount(n.value) == 1: # n > 2 and in fact n = 2^k for k >= 2
4329
if mpz_popcount(self.value) == 1: # since n is a power of 2, so must self be.
4330
if mpz_scan1(self.value, 0) % mpz_scan1(n.value, 0) == 0: # log_2(self) is divisible by log_2(n)
4331
return 1
4332
else:
4333
return 0
4334
else: # self is not a power of 2, and thus not a power of n
4335
return 0
4336
else: # n > 2, but not a power of 2, so we use mpz_remove
4337
mpz_init(u)
4338
sig_on()
4339
mpz_remove(u, self.value, n.value)
4340
sig_off()
4341
a = mpz_cmp_ui(u, 1)
4342
mpz_clear(u)
4343
if a == 0:
4344
return 1
4345
else:
4346
return 0
4347
4348
def is_power_of(Integer self, n):
4349
r"""
4350
Returns ``True`` if there is an integer b with
4351
`\mathtt{self} = n^b`.
4352
4353
.. seealso::
4354
4355
- :meth:`perfect_power`: Finds the minimal base for which this
4356
integer is a perfect power.
4357
- :meth:`is_perfect_power`: If you don't know the base but just
4358
want to know if this integer is a perfect power, use this
4359
function.
4360
- :meth:`is_prime_power`: Checks whether the base is prime.
4361
4362
EXAMPLES::
4363
4364
sage: Integer(64).is_power_of(4)
4365
True
4366
sage: Integer(64).is_power_of(16)
4367
False
4368
4369
TESTS::
4370
4371
sage: Integer(-64).is_power_of(-4)
4372
True
4373
sage: Integer(-32).is_power_of(-2)
4374
True
4375
sage: Integer(1).is_power_of(1)
4376
True
4377
sage: Integer(-1).is_power_of(-1)
4378
True
4379
sage: Integer(0).is_power_of(1)
4380
False
4381
sage: Integer(0).is_power_of(0)
4382
True
4383
sage: Integer(1).is_power_of(0)
4384
True
4385
sage: Integer(1).is_power_of(8)
4386
True
4387
sage: Integer(-8).is_power_of(2)
4388
False
4389
sage: Integer(-81).is_power_of(-3)
4390
False
4391
4392
.. note::
4393
4394
For large integers self, is_power_of() is faster than
4395
is_perfect_power(). The following examples gives some indication of
4396
how much faster.
4397
4398
::
4399
4400
sage: b = lcm(range(1,10000))
4401
sage: b.exact_log(2)
4402
14446
4403
sage: t=cputime()
4404
sage: for a in range(2, 1000): k = b.is_perfect_power()
4405
sage: cputime(t) # random
4406
0.53203299999999976
4407
sage: t=cputime()
4408
sage: for a in range(2, 1000): k = b.is_power_of(2)
4409
sage: cputime(t) # random
4410
0.0
4411
sage: t=cputime()
4412
sage: for a in range(2, 1000): k = b.is_power_of(3)
4413
sage: cputime(t) # random
4414
0.032002000000000308
4415
4416
::
4417
4418
sage: b = lcm(range(1, 1000))
4419
sage: b.exact_log(2)
4420
1437
4421
sage: t=cputime()
4422
sage: for a in range(2, 10000): k = b.is_perfect_power() # note that we change the range from the example above
4423
sage: cputime(t) # random
4424
0.17201100000000036
4425
sage: t=cputime(); TWO=int(2)
4426
sage: for a in range(2, 10000): k = b.is_power_of(TWO)
4427
sage: cputime(t) # random
4428
0.0040000000000000036
4429
sage: t=cputime()
4430
sage: for a in range(2, 10000): k = b.is_power_of(3)
4431
sage: cputime(t) # random
4432
0.040003000000000011
4433
sage: t=cputime()
4434
sage: for a in range(2, 10000): k = b.is_power_of(a)
4435
sage: cputime(t) # random
4436
0.02800199999999986
4437
"""
4438
if not PY_TYPE_CHECK(n, Integer):
4439
n = Integer(n)
4440
return self._is_power_of(n)
4441
4442
def is_prime_power(self, flag=0):
4443
r"""
4444
Returns True if this integer is a prime power, and False otherwise.
4445
4446
INPUT:
4447
4448
- ``flag`` (for primality testing) - int. Values are:
4449
4450
- ``0`` (default): use a combination of algorithms.
4451
- ``1``: certify primality using the Pocklington-Lehmer test.
4452
- ``2``: certify primality using the APRCL test.
4453
4454
.. seealso::
4455
4456
- :meth:`perfect_power`: Finds the minimal base for which integer
4457
is a perfect power.
4458
- :meth:`is_perfect_power`: Doesn't test whether the base is prime.
4459
- :meth:`is_power_of`: If you know the base already this method is
4460
the fastest option.
4461
4462
EXAMPLES::
4463
4464
sage: (-10).is_prime_power()
4465
False
4466
sage: (10).is_prime_power()
4467
False
4468
sage: (64).is_prime_power()
4469
True
4470
sage: (3^10000).is_prime_power()
4471
True
4472
sage: (10000).is_prime_power(flag=1)
4473
False
4474
4475
We check that :trac:`4777` is fixed::
4476
4477
sage: n = 150607571^14
4478
sage: n.is_prime_power()
4479
True
4480
"""
4481
if self.is_zero():
4482
return False
4483
elif self.is_one():
4484
return True
4485
elif mpz_sgn(self.value) < 0:
4486
return False
4487
if self.is_prime():
4488
return True
4489
if not self.is_perfect_power():
4490
return False
4491
k, g = self._pari_().ispower()
4492
if k == 1:
4493
raise RuntimeError, "Inconsistent results between GMP and PARI"
4494
return g.isprime(flag=flag)
4495
4496
def is_prime(self, proof=None):
4497
r"""
4498
Returns ``True`` if ``self`` is prime.
4499
4500
INPUT:
4501
4502
- ``proof`` -- If False, use a strong pseudo-primality test.
4503
If True, use a provable primality test. If unset, use the
4504
default arithmetic proof flag.
4505
4506
.. note::
4507
4508
Integer primes are by definition *positive*! This is
4509
different than Magma, but the same as in PARI. See also the
4510
:meth:`is_irreducible()` method.
4511
4512
EXAMPLES::
4513
4514
sage: z = 2^31 - 1
4515
sage: z.is_prime()
4516
True
4517
sage: z = 2^31
4518
sage: z.is_prime()
4519
False
4520
sage: z = 7
4521
sage: z.is_prime()
4522
True
4523
sage: z = -7
4524
sage: z.is_prime()
4525
False
4526
sage: z.is_irreducible()
4527
True
4528
4529
::
4530
4531
sage: z = 10^80 + 129
4532
sage: z.is_prime(proof=False)
4533
True
4534
sage: z.is_prime(proof=True)
4535
True
4536
4537
When starting Sage the arithmetic proof flag is True. We can change
4538
it to False as follows::
4539
4540
sage: proof.arithmetic()
4541
True
4542
sage: n = 10^100 + 267
4543
sage: timeit("n.is_prime()") # random
4544
5 loops, best of 3: 163 ms per loop
4545
sage: proof.arithmetic(False)
4546
sage: proof.arithmetic()
4547
False
4548
sage: timeit("n.is_prime()") # random
4549
1000 loops, best of 3: 573 us per loop
4550
4551
IMPLEMENTATION: Calls the PARI ``isprime`` function.
4552
"""
4553
from sage.structure.proof.proof import get_flag
4554
proof = get_flag(proof, "arithmetic")
4555
if proof:
4556
return bool(self._pari_().isprime())
4557
else:
4558
return bool(self._pari_().ispseudoprime())
4559
4560
def is_irreducible(self):
4561
r"""
4562
Returns ``True`` if self is irreducible, i.e. +/-
4563
prime
4564
4565
EXAMPLES::
4566
4567
sage: z = 2^31 - 1
4568
sage: z.is_irreducible()
4569
True
4570
sage: z = 2^31
4571
sage: z.is_irreducible()
4572
False
4573
sage: z = 7
4574
sage: z.is_irreducible()
4575
True
4576
sage: z = -7
4577
sage: z.is_irreducible()
4578
True
4579
"""
4580
n = self if self >= 0 else -self
4581
return bool(n._pari_().isprime())
4582
4583
def is_pseudoprime(self):
4584
r"""
4585
Returns ``True`` if self is a pseudoprime
4586
4587
EXAMPLES::
4588
4589
sage: z = 2^31 - 1
4590
sage: z.is_pseudoprime()
4591
True
4592
sage: z = 2^31
4593
sage: z.is_pseudoprime()
4594
False
4595
"""
4596
return bool(self._pari_().ispseudoprime())
4597
4598
def is_perfect_power(self):
4599
r"""
4600
Returns ``True`` if ``self`` is a perfect power, ie if there exist integers
4601
`a` and `b`, `b > 1` with ``self`` `= a^b`.
4602
4603
.. seealso::
4604
4605
- :meth:`perfect_power`: Finds the minimal base for which this
4606
integer is a perfect power.
4607
- :meth:`is_power_of`: If you know the base already this method is
4608
the fastest option.
4609
- :meth:`is_prime_power`: Checks whether the base is prime.
4610
4611
EXAMPLES::
4612
4613
sage: Integer(-27).is_perfect_power()
4614
True
4615
sage: Integer(12).is_perfect_power()
4616
False
4617
4618
sage: z = 8
4619
sage: z.is_perfect_power()
4620
True
4621
sage: 144.is_perfect_power()
4622
True
4623
sage: 10.is_perfect_power()
4624
False
4625
sage: (-8).is_perfect_power()
4626
True
4627
sage: (-4).is_perfect_power()
4628
False
4629
4630
sage: (4).is_power()
4631
doctest:...: DeprecationWarning: is_power is deprecated. Please use is_perfect_power instead.
4632
See http://trac.sagemath.org/12116 for details.
4633
True
4634
4635
TESTS:
4636
4637
This is a test to make sure we work around a bug in GMP, see
4638
:trac:`4612`.
4639
4640
::
4641
4642
sage: [ -a for a in srange(100) if not (-a^3).is_perfect_power() ]
4643
[]
4644
"""
4645
cdef mpz_t tmp
4646
cdef int res
4647
if mpz_sgn(self.value) < 0:
4648
if mpz_cmp_si(self.value, -1) == 0:
4649
return True
4650
mpz_init(tmp)
4651
mpz_neg(tmp, self.value)
4652
while mpz_perfect_square_p(tmp):
4653
mpz_sqrt(tmp, tmp)
4654
res = mpz_perfect_power_p(tmp)
4655
mpz_clear(tmp)
4656
if res:
4657
return True
4658
else:
4659
return False
4660
return mpz_perfect_power_p(self.value)
4661
4662
def is_norm(self, K, element=False, proof=True):
4663
r"""
4664
See ``QQ(self).is_norm()``.
4665
4666
EXAMPLES::
4667
4668
sage: K = NumberField(x^2 - 2, 'beta')
4669
sage: n = 4
4670
sage: n.is_norm(K)
4671
True
4672
sage: 5.is_norm(K)
4673
False
4674
sage: 7.is_norm(QQ)
4675
True
4676
sage: n.is_norm(K, element=True)
4677
(True, -4*beta + 6)
4678
sage: n.is_norm(K, element=True)[1].norm()
4679
4
4680
sage: n = 5
4681
sage: n.is_norm(K, element=True)
4682
(False, None)
4683
sage: n = 7
4684
sage: n.is_norm(QQ, element=True)
4685
(True, 7)
4686
4687
"""
4688
from sage.rings.rational_field import QQ
4689
return QQ(self).is_norm(K, element=element, proof=proof)
4690
4691
def _bnfisnorm(self, K, proof=True, extra_primes=0):
4692
r"""
4693
See ``QQ(self)._bnfisnorm()``.
4694
4695
EXAMPLES::
4696
4697
sage: 3._bnfisnorm(QuadraticField(-1, 'i'))
4698
(1, 3)
4699
sage: 7._bnfisnorm(CyclotomicField(7))
4700
(-zeta7 + 1, 1) # 64-bit
4701
(-zeta7^5 + zeta7^4, 1) # 32-bit
4702
"""
4703
from sage.rings.rational_field import QQ
4704
return QQ(self)._bnfisnorm(K, proof=proof, extra_primes=extra_primes)
4705
4706
4707
def jacobi(self, b):
4708
r"""
4709
Calculate the Jacobi symbol `\left(\frac{self}{b}\right)`.
4710
4711
EXAMPLES::
4712
4713
sage: z = -1
4714
sage: z.jacobi(17)
4715
1
4716
sage: z.jacobi(19)
4717
-1
4718
sage: z.jacobi(17*19)
4719
-1
4720
sage: (2).jacobi(17)
4721
1
4722
sage: (3).jacobi(19)
4723
-1
4724
sage: (6).jacobi(17*19)
4725
-1
4726
sage: (6).jacobi(33)
4727
0
4728
sage: a = 3; b = 7
4729
sage: a.jacobi(b) == -b.jacobi(a)
4730
True
4731
"""
4732
cdef long tmp
4733
if PY_TYPE_CHECK(b, int):
4734
tmp = b
4735
if (tmp & 1) == 0:
4736
raise ValueError, "Jacobi symbol not defined for even b."
4737
return mpz_kronecker_si(self.value, tmp)
4738
if not PY_TYPE_CHECK(b, Integer):
4739
b = Integer(b)
4740
if mpz_even_p((<Integer>b).value):
4741
raise ValueError, "Jacobi symbol not defined for even b."
4742
return mpz_jacobi(self.value, (<Integer>b).value)
4743
4744
def kronecker(self, b):
4745
r"""
4746
Calculate the Kronecker symbol `\left(\frac{self}{b}\right)`
4747
with the Kronecker extension `(self/2)=(2/self)` when `self` is odd,
4748
or `(self/2)=0` when `self` is even.
4749
4750
EXAMPLES::
4751
4752
sage: z = 5
4753
sage: z.kronecker(41)
4754
1
4755
sage: z.kronecker(43)
4756
-1
4757
sage: z.kronecker(8)
4758
-1
4759
sage: z.kronecker(15)
4760
0
4761
sage: a = 2; b = 5
4762
sage: a.kronecker(b) == b.kronecker(a)
4763
True
4764
"""
4765
if PY_TYPE_CHECK(b, int):
4766
return mpz_kronecker_si(self.value, b)
4767
if not PY_TYPE_CHECK(b, Integer):
4768
b = Integer(b)
4769
return mpz_kronecker(self.value, (<Integer>b).value)
4770
4771
def radical(self, *args, **kwds):
4772
r"""
4773
Return the product of the prime divisors of self. Computing
4774
the radical of zero gives an error.
4775
4776
EXAMPLES::
4777
4778
sage: Integer(10).radical()
4779
10
4780
sage: Integer(20).radical()
4781
10
4782
sage: Integer(-100).radical()
4783
10
4784
sage: Integer(0).radical()
4785
Traceback (most recent call last):
4786
...
4787
ArithmeticError: Radical of 0 not defined.
4788
"""
4789
if self.is_zero():
4790
raise ArithmeticError, "Radical of 0 not defined."
4791
return self.factor(*args, **kwds).radical_value()
4792
4793
def squarefree_part(self, long bound=-1):
4794
r"""
4795
Return the square free part of `x` (=self), i.e., the unique integer
4796
`z` that `x = z y^2`, with `y^2` a perfect square and `z` square-free.
4797
4798
Use ``self.radical()`` for the product of the primes that divide self.
4799
4800
If self is 0, just returns 0.
4801
4802
EXAMPLES::
4803
4804
sage: squarefree_part(100)
4805
1
4806
sage: squarefree_part(12)
4807
3
4808
sage: squarefree_part(17*37*37)
4809
17
4810
sage: squarefree_part(-17*32)
4811
-34
4812
sage: squarefree_part(1)
4813
1
4814
sage: squarefree_part(-1)
4815
-1
4816
sage: squarefree_part(-2)
4817
-2
4818
sage: squarefree_part(-4)
4819
-1
4820
4821
::
4822
4823
sage: a = 8 * 5^6 * 101^2
4824
sage: a.squarefree_part(bound=2).factor()
4825
2 * 5^6 * 101^2
4826
sage: a.squarefree_part(bound=5).factor()
4827
2 * 101^2
4828
sage: a.squarefree_part(bound=1000)
4829
2
4830
sage: a.squarefree_part(bound=2**14)
4831
2
4832
sage: a = 7^3 * next_prime(2^100)^2 * next_prime(2^200)
4833
sage: a / a.squarefree_part(bound=1000)
4834
49
4835
"""
4836
cdef Integer z
4837
cdef long even_part, p, p2
4838
cdef char switch_p
4839
if mpz_sgn(self.value) == 0:
4840
return self
4841
if 0 <= bound < 2:
4842
return self
4843
elif 2 <= bound <= 10000:
4844
z = PY_NEW(Integer)
4845
even_part = mpz_scan1(self.value, 0)
4846
mpz_fdiv_q_2exp(z.value, self.value, even_part ^ (even_part&1))
4847
sig_on()
4848
if bound >= 3:
4849
while mpz_divisible_ui_p(z.value, 9):
4850
mpz_divexact_ui(z.value, z.value, 9)
4851
if bound >= 5:
4852
while mpz_divisible_ui_p(z.value, 25):
4853
mpz_divexact_ui(z.value, z.value, 25)
4854
for p from 7 <= p <= bound by 2:
4855
switch_p = p % 30
4856
if switch_p in [1, 7, 11, 13, 17, 19, 23, 29]:
4857
p2 = p*p
4858
while mpz_divisible_ui_p(z.value, p2):
4859
mpz_divexact_ui(z.value, z.value, p2)
4860
sig_off()
4861
return z
4862
else:
4863
if bound == -1:
4864
F = self.factor()
4865
else:
4866
from sage.rings.factorint import factor_trial_division
4867
F = factor_trial_division(self,bound)
4868
n = one
4869
for pp, e in F:
4870
if e % 2 != 0:
4871
n = n * pp
4872
return n * F.unit()
4873
4874
def next_probable_prime(self):
4875
"""
4876
Returns the next probable prime after self, as determined by PARI.
4877
4878
EXAMPLES::
4879
4880
sage: (-37).next_probable_prime()
4881
2
4882
sage: (100).next_probable_prime()
4883
101
4884
sage: (2^512).next_probable_prime()
4885
13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084171
4886
sage: 0.next_probable_prime()
4887
2
4888
sage: 126.next_probable_prime()
4889
127
4890
sage: 144168.next_probable_prime()
4891
144169
4892
"""
4893
return Integer( self._pari_().nextprime(True) )
4894
4895
def next_prime(self, proof=None):
4896
r"""
4897
Returns the next prime after self.
4898
4899
INPUT:
4900
4901
- ``proof`` - bool or None (default: None, see
4902
proof.arithmetic or sage.structure.proof) Note that the global Sage
4903
default is proof=True
4904
4905
EXAMPLES::
4906
4907
sage: Integer(100).next_prime()
4908
101
4909
4910
Use Proof = False, which is way faster::
4911
4912
sage: b = (2^1024).next_prime(proof=False)
4913
4914
::
4915
4916
sage: Integer(0).next_prime()
4917
2
4918
sage: Integer(1001).next_prime()
4919
1009
4920
"""
4921
if mpz_cmp(self.value, PARI_PSEUDOPRIME_LIMIT) < 0:
4922
return Integer( self._pari_().nextprime(True) )
4923
if proof is None:
4924
from sage.structure.proof.proof import get_flag
4925
proof = get_flag(proof, "arithmetic")
4926
if not proof:
4927
return Integer( self._pari_().nextprime(True) )
4928
n = self
4929
if n % 2 == 0:
4930
n += 1
4931
else:
4932
n += 2
4933
while not n.is_prime(): # PARI's isprime() is provably correct
4934
n += 2
4935
return integer_ring.ZZ(n)
4936
4937
def additive_order(self):
4938
"""
4939
Return the additive order of self.
4940
4941
EXAMPLES::
4942
4943
sage: ZZ(0).additive_order()
4944
1
4945
sage: ZZ(1).additive_order()
4946
+Infinity
4947
"""
4948
import sage.rings.infinity
4949
if self.is_zero():
4950
return one
4951
else:
4952
return sage.rings.infinity.infinity
4953
4954
def multiplicative_order(self):
4955
r"""
4956
Return the multiplicative order of self.
4957
4958
EXAMPLES::
4959
4960
sage: ZZ(1).multiplicative_order()
4961
1
4962
sage: ZZ(-1).multiplicative_order()
4963
2
4964
sage: ZZ(0).multiplicative_order()
4965
+Infinity
4966
sage: ZZ(2).multiplicative_order()
4967
+Infinity
4968
"""
4969
import sage.rings.infinity
4970
if mpz_cmp_si(self.value, 1) == 0:
4971
return one
4972
elif mpz_cmp_si(self.value, -1) == 0:
4973
return Integer(2)
4974
else:
4975
return sage.rings.infinity.infinity
4976
4977
def is_squarefree(self):
4978
"""
4979
Returns True if this integer is not divisible by the square of any
4980
prime and False otherwise.
4981
4982
EXAMPLES::
4983
4984
sage: Integer(100).is_squarefree()
4985
False
4986
sage: Integer(102).is_squarefree()
4987
True
4988
sage: Integer(0).is_squarefree()
4989
False
4990
"""
4991
return self._pari_().issquarefree()
4992
4993
def _pari_(self):
4994
"""
4995
Returns the PARI version of this integer.
4996
4997
EXAMPLES::
4998
4999
sage: n = 9390823
5000
sage: m = n._pari_(); m
5001
9390823
5002
sage: type(m)
5003
<type 'sage.libs.pari.gen.gen'>
5004
5005
TESTS::
5006
5007
sage: n = 10^10000000
5008
sage: m = n._pari_() ## crash from trac 875
5009
sage: m % 1234567
5010
1041334
5011
"""
5012
return self._pari_c()
5013
5014
cdef _pari_c(self):
5015
return pari.new_gen_from_mpz_t(self.value)
5016
5017
def _interface_init_(self, I=None):
5018
"""
5019
Return canonical string to coerce this integer to any other math
5020
software, i.e., just the string representation of this integer in
5021
base 10.
5022
5023
EXAMPLES::
5024
5025
sage: n = 9390823
5026
sage: n._interface_init_()
5027
'9390823'
5028
"""
5029
return str(self)
5030
5031
property __array_interface__:
5032
def __get__(self):
5033
"""
5034
Used for NumPy conversion.
5035
5036
EXAMPLES::
5037
5038
sage: import numpy
5039
sage: numpy.array([1, 2, 3])
5040
array([1, 2, 3])
5041
sage: numpy.array([1, 2, 3]).dtype
5042
dtype('int32') # 32-bit
5043
dtype('int64') # 64-bit
5044
5045
sage: numpy.array(2**40).dtype
5046
dtype('int64')
5047
sage: numpy.array(2**400).dtype
5048
dtype('O')
5049
5050
sage: numpy.array([1,2,3,0.1]).dtype
5051
dtype('float64')
5052
"""
5053
if mpz_fits_slong_p(self.value):
5054
return numpy_long_interface
5055
elif sizeof(long) == 4 and mpz_sizeinbase(self.value, 2) <= 63:
5056
return numpy_int64_interface
5057
else:
5058
return numpy_object_interface
5059
5060
def _magma_init_(self, magma):
5061
"""
5062
Return string that evaluates in Magma to this element.
5063
5064
For small integers we just use base 10. For large integers we use
5065
base 16, but use Magma's StringToInteger command, which (for no
5066
good reason) is much faster than 0x[string literal]. We only use
5067
base 16 for integers with at least 10000 binary digits, since e.g.,
5068
for a large list of small integers the overhead of calling
5069
StringToInteger can be a killer.
5070
5071
EXAMPLES:
5072
sage: (117)._magma_init_(magma) # optional - magma
5073
'117'
5074
5075
Large integers use hex:
5076
sage: m = 3^(2^20) # optional - magma
5077
sage: s = m._magma_init_(magma) # optional - magma
5078
sage: 'StringToInteger' in s # optional - magma
5079
True
5080
sage: magma(m).sage() == m # optional - magma
5081
True
5082
"""
5083
if self.ndigits(2) > 10000:
5084
return 'StringToInteger("%s",16)'%self.str(16)
5085
else:
5086
return str(self)
5087
5088
def _sage_input_(self, sib, coerced):
5089
r"""
5090
Produce an expression which will reproduce this value when
5091
evaluated.
5092
5093
EXAMPLES::
5094
5095
sage: sage_input(1, verify=True)
5096
# Verified
5097
1
5098
sage: sage_input(1, preparse=False)
5099
ZZ(1)
5100
sage: sage_input(-12435, verify=True)
5101
# Verified
5102
-12435
5103
sage: sage_input(0, verify=True)
5104
# Verified
5105
0
5106
sage: sage_input(-3^70, verify=True)
5107
# Verified
5108
-2503155504993241601315571986085849
5109
sage: sage_input(-37, preparse=False)
5110
-ZZ(37)
5111
sage: sage_input(-37 * polygen(ZZ), preparse=False)
5112
R = ZZ['x']
5113
x = R.gen()
5114
-37*x
5115
sage: from sage.misc.sage_input import SageInputBuilder
5116
sage: (-314159)._sage_input_(SageInputBuilder(preparse=False), False)
5117
{unop:- {call: {atomic:ZZ}({atomic:314159})}}
5118
sage: (314159)._sage_input_(SageInputBuilder(preparse=False), True)
5119
{atomic:314159}
5120
"""
5121
if coerced or sib.preparse():
5122
return sib.int(self)
5123
else:
5124
if self < 0:
5125
return -sib.name('ZZ')(sib.int(-self))
5126
else:
5127
return sib.name('ZZ')(sib.int(self))
5128
5129
def sqrtrem(self):
5130
r"""
5131
Return (s, r) where s is the integer square root of self and
5132
r is the remainder such that `\text{self} = s^2 + r`.
5133
Raises ``ValueError`` if self is negative.
5134
5135
EXAMPLES::
5136
5137
sage: 25.sqrtrem()
5138
(5, 0)
5139
sage: 27.sqrtrem()
5140
(5, 2)
5141
sage: 0.sqrtrem()
5142
(0, 0)
5143
5144
::
5145
5146
sage: Integer(-102).sqrtrem()
5147
Traceback (most recent call last):
5148
...
5149
ValueError: square root of negative integer not defined.
5150
5151
"""
5152
if mpz_sgn(self.value) < 0:
5153
raise ValueError, "square root of negative integer not defined."
5154
cdef Integer s = PY_NEW(Integer)
5155
cdef Integer r = PY_NEW(Integer)
5156
mpz_sqrtrem(s.value, r.value, self.value)
5157
return s, r
5158
5159
def isqrt(self):
5160
r"""
5161
Returns the integer floor of the square root of self, or raises an
5162
``ValueError`` if self is negative.
5163
5164
EXAMPLE::
5165
5166
sage: a = Integer(5)
5167
sage: a.isqrt()
5168
2
5169
5170
::
5171
5172
sage: Integer(-102).isqrt()
5173
Traceback (most recent call last):
5174
...
5175
ValueError: square root of negative integer not defined.
5176
"""
5177
if mpz_sgn(self.value) < 0:
5178
raise ValueError, "square root of negative integer not defined."
5179
5180
cdef Integer x = PY_NEW(Integer)
5181
5182
sig_on()
5183
mpz_sqrt(x.value, self.value)
5184
sig_off()
5185
5186
return x
5187
5188
def sqrt_approx(self, prec=None, all=False):
5189
"""
5190
EXAMPLES::
5191
5192
sage: 5.sqrt_approx(prec=200)
5193
doctest:...: DeprecationWarning: This function is deprecated. Use sqrt with a given number of bits of precision instead.
5194
See http://trac.sagemath.org/10107 for details.
5195
2.2360679774997896964091736687312762354406183596115257242709
5196
sage: 5.sqrt_approx()
5197
2.23606797749979
5198
sage: 4.sqrt_approx()
5199
2
5200
"""
5201
from sage.misc.superseded import deprecation
5202
deprecation(10107, "This function is deprecated. Use sqrt with a given number of bits of precision instead.")
5203
try:
5204
return self.sqrt(extend=False,all=all)
5205
except ValueError:
5206
pass
5207
if prec is None:
5208
prec = max(53, 2*(mpz_sizeinbase(self.value, 2)+2))
5209
return self.sqrt(prec=prec, all=all)
5210
5211
def sqrt(self, prec=None, extend=True, all=False):
5212
"""
5213
The square root function.
5214
5215
INPUT:
5216
5217
- ``prec`` - integer (default: None): if None, returns
5218
an exact square root; otherwise returns a numerical square root if
5219
necessary, to the given bits of precision.
5220
5221
- ``extend`` - bool (default: True); if True, return a
5222
square root in an extension ring, if necessary. Otherwise, raise a
5223
ValueError if the square is not in the base ring. Ignored if prec
5224
is not None.
5225
5226
- ``all`` - bool (default: False); if True, return all
5227
square roots of self, instead of just one.
5228
5229
EXAMPLES::
5230
5231
sage: Integer(144).sqrt()
5232
12
5233
sage: sqrt(Integer(144))
5234
12
5235
sage: Integer(102).sqrt()
5236
sqrt(102)
5237
5238
::
5239
5240
sage: n = 2
5241
sage: n.sqrt(all=True)
5242
[sqrt(2), -sqrt(2)]
5243
sage: n.sqrt(prec=10)
5244
1.4
5245
sage: n.sqrt(prec=100)
5246
1.4142135623730950488016887242
5247
sage: n.sqrt(prec=100,all=True)
5248
[1.4142135623730950488016887242, -1.4142135623730950488016887242]
5249
sage: n.sqrt(extend=False)
5250
Traceback (most recent call last):
5251
...
5252
ValueError: square root of 2 not an integer
5253
sage: Integer(144).sqrt(all=True)
5254
[12, -12]
5255
sage: Integer(0).sqrt(all=True)
5256
[0]
5257
sage: type(Integer(5).sqrt())
5258
<type 'sage.symbolic.expression.Expression'>
5259
sage: type(Integer(5).sqrt(prec=53))
5260
<type 'sage.rings.real_mpfr.RealNumber'>
5261
sage: type(Integer(-5).sqrt(prec=53))
5262
<type 'sage.rings.complex_number.ComplexNumber'>
5263
5264
TESTS:
5265
5266
Check that :trac:`9466` is fixed::
5267
5268
sage: 3.sqrt(extend=False, all=True)
5269
[]
5270
"""
5271
if mpz_sgn(self.value) == 0:
5272
return [self] if all else self
5273
5274
if mpz_sgn(self.value) < 0:
5275
if not extend:
5276
raise ValueError, "square root of negative number not an integer"
5277
from sage.functions.other import _do_sqrt
5278
return _do_sqrt(self, prec=prec, all=all)
5279
5280
cdef int non_square
5281
cdef Integer z = PY_NEW(Integer)
5282
cdef mpz_t tmp
5283
sig_on()
5284
mpz_init(tmp)
5285
mpz_sqrtrem(z.value, tmp, self.value)
5286
non_square = mpz_sgn(tmp) != 0
5287
mpz_clear(tmp)
5288
sig_off()
5289
5290
if non_square:
5291
if not extend:
5292
if not all:
5293
raise ValueError, "square root of %s not an integer"%self
5294
else:
5295
return []
5296
from sage.functions.other import _do_sqrt
5297
return _do_sqrt(self, prec=prec, all=all)
5298
5299
if prec:
5300
from sage.functions.other import _do_sqrt
5301
return _do_sqrt(self, prec=prec, all=all)
5302
5303
if all:
5304
return [z, -z]
5305
return z
5306
5307
@coerce_binop
5308
def xgcd(self, Integer n):
5309
r"""
5310
Return the extended gcd of this element and ``n``.
5311
5312
INPUT:
5313
5314
- ``n`` -- an integer
5315
5316
OUTPUT:
5317
5318
A triple ``(g, s, t)`` such that ``g`` is the non-negative gcd of
5319
``self`` and ``n``, and ``s`` and ``t`` are cofactors satisfying the
5320
Bezout identity
5321
5322
.. MATH::
5323
5324
g = s \cdot \mathrm{self} + t \cdot n.
5325
5326
.. NOTE::
5327
5328
There is no guarantee that the cofactors will be minimal. If you
5329
need the cofactors to be minimal use :meth:`_xgcd`. Also, using
5330
:meth:`_xgcd` directly might be faster in some cases, see
5331
:trac:`13628`.
5332
5333
EXAMPLES::
5334
5335
sage: 6.xgcd(4)
5336
(2, 1, -1)
5337
5338
"""
5339
return self._xgcd(n)
5340
5341
def _xgcd(self, Integer n, bint minimal=0):
5342
r"""
5343
Return the exteded gcd of ``self`` and ``n``.
5344
5345
INPUT:
5346
5347
- ``n`` -- an integer
5348
- ``minimal`` -- a boolean (default: ``False``), whether to compute
5349
minimal cofactors (see below)
5350
5351
OUTPUT:
5352
5353
A triple ``(g, s, t)`` such that ``g`` is the non-negative gcd of
5354
``self`` and ``n``, and ``s`` and ``t`` are cofactors satisfying the
5355
Bezout identity
5356
5357
.. MATH::
5358
5359
g = s \cdot \mathrm{self} + t \cdot n.
5360
5361
.. NOTE::
5362
5363
If ``minimal`` is ``False``, then there is no guarantee that the
5364
returned cofactors will be minimal in any sense; the only guarantee
5365
is that the Bezout identity will be satisfied (see examples below).
5366
5367
If ``minimal`` is ``True``, the cofactors will satisfy the following
5368
conditions. If either ``self`` or ``n`` are zero, the trivial
5369
solution is returned. If both ``self`` and ``n`` are nonzero, the
5370
function returns the unique solution such that `0 \leq s < |n|/g`
5371
(which then must also satisfy
5372
`0 \leq |t| \leq |\mbox{\rm self}|/g`).
5373
5374
EXAMPLES::
5375
5376
sage: 5._xgcd(7)
5377
(1, 3, -2)
5378
sage: 5*3 + 7*-2
5379
1
5380
sage: g,s,t = 58526524056._xgcd(101294172798)
5381
sage: g
5382
22544886
5383
sage: 58526524056 * s + 101294172798 * t
5384
22544886
5385
5386
Try ``minimal`` option with various edge cases::
5387
5388
sage: 5._xgcd(0, minimal=True)
5389
(5, 1, 0)
5390
sage: (-5)._xgcd(0, minimal=True)
5391
(5, -1, 0)
5392
sage: 0._xgcd(5, minimal=True)
5393
(5, 0, 1)
5394
sage: 0._xgcd(-5, minimal=True)
5395
(5, 0, -1)
5396
sage: 0._xgcd(0, minimal=True)
5397
(0, 1, 0)
5398
5399
Output may differ with and without the ``minimal`` option::
5400
5401
sage: 2._xgcd(-2)
5402
(2, 1, 0)
5403
sage: 2._xgcd(-2, minimal=True)
5404
(2, 0, -1)
5405
5406
Exhaustive tests, checking minimality conditions::
5407
5408
sage: for a in srange(-20, 20):
5409
....: for b in srange(-20, 20):
5410
....: if a == 0 or b == 0: continue
5411
....: g, s, t = a._xgcd(b)
5412
....: assert g > 0
5413
....: assert a % g == 0 and b % g == 0
5414
....: assert a*s + b*t == g
5415
....: g, s, t = a._xgcd(b, minimal=True)
5416
....: assert g > 0
5417
....: assert a % g == 0 and b % g == 0
5418
....: assert a*s + b*t == g
5419
....: assert s >= 0 and s < abs(b)/g
5420
....: assert abs(t) <= abs(a)/g
5421
5422
AUTHORS:
5423
5424
- David Harvey (2007-12-26): added minimality option
5425
"""
5426
cdef Integer g = PY_NEW(Integer)
5427
cdef Integer s = PY_NEW(Integer)
5428
cdef Integer t = PY_NEW(Integer)
5429
5430
sig_on()
5431
mpz_gcdext(g.value, s.value, t.value, self.value, n.value)
5432
sig_off()
5433
5434
# Note: the GMP documentation for mpz_gcdext (or mpn_gcdext for that
5435
# matter) makes absolutely no claims about any minimality conditions
5436
# satisfied by the returned cofactors. They guarantee a non-negative
5437
# gcd, but that's it. So we have to do some work ourselves.
5438
5439
if not minimal:
5440
return g, s, t
5441
5442
# handle degenerate cases n == 0 and self == 0
5443
5444
if not mpz_sgn(n.value):
5445
mpz_set_ui(t.value, 0)
5446
mpz_abs(g.value, self.value)
5447
mpz_set_si(s.value, 1 if mpz_sgn(self.value) >= 0 else -1)
5448
return g, s, t
5449
5450
if not mpz_sgn(self.value):
5451
mpz_set_ui(s.value, 0)
5452
mpz_abs(g.value, n.value)
5453
mpz_set_si(t.value, 1 if mpz_sgn(n.value) >= 0 else -1)
5454
return g, s, t
5455
5456
# both n and self are nonzero, so we need to do a division and
5457
# make the appropriate adjustment
5458
5459
cdef mpz_t u1, u2
5460
mpz_init(u1)
5461
mpz_init(u2)
5462
mpz_divexact(u1, n.value, g.value)
5463
mpz_divexact(u2, self.value, g.value)
5464
if mpz_sgn(u1) > 0:
5465
mpz_fdiv_qr(u1, s.value, s.value, u1)
5466
else:
5467
mpz_cdiv_qr(u1, s.value, s.value, u1)
5468
mpz_addmul(t.value, u1, u2)
5469
mpz_clear(u2)
5470
mpz_clear(u1)
5471
5472
return g, s, t
5473
5474
cpdef _shift_helper(Integer self, y, int sign):
5475
"""
5476
Function used to compute left and right shifts of integers.
5477
Shifts self y bits to the left if sign is 1, and to the right
5478
if sign is -1.
5479
5480
WARNING: This function does no error checking. In particular,
5481
it assumes that sign is either 1 or -1,
5482
5483
EXAMPLES::
5484
5485
sage: n = 1234
5486
sage: factor(n)
5487
2 * 617
5488
sage: n._shift_helper(1, 1)
5489
2468
5490
sage: n._shift_helper(1, -1)
5491
617
5492
sage: n._shift_helper(100, 1)
5493
1564280840681635081446931755433984
5494
sage: n._shift_helper(100, -1)
5495
0
5496
sage: n._shift_helper(-100, 1)
5497
0
5498
sage: n._shift_helper(-100, -1)
5499
1564280840681635081446931755433984
5500
"""
5501
cdef long n
5502
5503
if PyInt_CheckExact(y):
5504
# For a Python int, we can just use the Python/C API.
5505
n = PyInt_AS_LONG(y)
5506
else:
5507
# If it's not already an Integer, try to convert it.
5508
if not PY_TYPE_CHECK(y, Integer):
5509
try:
5510
y = Integer(y)
5511
except TypeError:
5512
raise TypeError, "unsupported operands for %s: %s, %s"%(("<<" if sign == 1 else ">>"), self, y)
5513
except ValueError:
5514
return bin_op(self, y, operator.lshift if sign == 1 else operator.rshift)
5515
5516
# If y wasn't a Python int, it's now an Integer, so set n
5517
# accordingly.
5518
if mpz_fits_slong_p((<Integer>y).value):
5519
n = mpz_get_si((<Integer>y).value)
5520
elif sign * mpz_sgn((<Integer>y).value) < 0:
5521
# Doesn't fit in a long so shifting to the right by
5522
# this much will be 0.
5523
return PY_NEW(Integer)
5524
else:
5525
# Doesn't fit in a long so shifting to the left by
5526
# this much will raise appropriate overflow error
5527
n = y
5528
5529
# Decide which way we're shifting
5530
n *= sign
5531
5532
# Now finally call into MPIR to do the shifting.
5533
cdef Integer z = PY_NEW(Integer)
5534
if n < 0:
5535
mpz_fdiv_q_2exp(z.value, self.value, -n)
5536
else:
5537
mpz_mul_2exp(z.value, self.value, n)
5538
return z
5539
5540
def __lshift__(x, y):
5541
"""
5542
Shift x to the left by y bits.
5543
5544
EXAMPLES::
5545
5546
sage: 32 << 2
5547
128
5548
sage: 32 << int(2)
5549
128
5550
sage: int(32) << 2
5551
128
5552
sage: 1 << 2.5
5553
Traceback (most recent call last):
5554
...
5555
TypeError: unsupported operands for <<: 1, 2.5000...
5556
5557
sage: 32 << (4/2)
5558
128
5559
5560
A negative shift to the left is treated as a right shift::
5561
5562
sage: 128 << -2
5563
32
5564
sage: 128 << (-2^100)
5565
0
5566
"""
5567
# note that x need not be self -- int(3) << ZZ(2) will
5568
# dispatch this function
5569
if not PY_TYPE_CHECK(x, Integer):
5570
return x << int(y)
5571
return (<Integer>x)._shift_helper(y, 1)
5572
5573
def __rshift__(x, y):
5574
"""
5575
Shift x to the right by y bits.
5576
5577
EXAMPLES::
5578
5579
sage: 32 >> 2
5580
8
5581
sage: 32 >> int(2)
5582
8
5583
sage: int(32) >> 2
5584
8
5585
sage: 1 >> 2.5
5586
Traceback (most recent call last):
5587
...
5588
TypeError: unsupported operands for >>: 1, 2.5000...
5589
sage: 10^5 >> 10^100
5590
0
5591
5592
A negative shift to the right is treated as a left shift::
5593
5594
sage: 8 >> -2
5595
32
5596
"""
5597
# note that x need not be self -- int(3) >> ZZ(2) will
5598
# dispatch this function
5599
if not PY_TYPE_CHECK(x, Integer):
5600
return x >> int(y)
5601
return (<Integer>x)._shift_helper(y, -1)
5602
5603
cdef _and(Integer self, Integer other):
5604
cdef Integer x = PY_NEW(Integer)
5605
mpz_and(x.value, self.value, other.value)
5606
return x
5607
5608
def __and__(x, y):
5609
"""
5610
Return the bitwise and two integers.
5611
5612
EXAMPLES::
5613
5614
sage: n = Integer(6); m = Integer(2)
5615
sage: n & m
5616
2
5617
sage: n.__and__(m)
5618
2
5619
"""
5620
if PY_TYPE_CHECK(x, Integer) and PY_TYPE_CHECK(y, Integer):
5621
return (<Integer>x)._and(y)
5622
return bin_op(x, y, operator.and_)
5623
5624
cdef _or(Integer self, Integer other):
5625
cdef Integer x = PY_NEW(Integer)
5626
mpz_ior(x.value, self.value, other.value)
5627
return x
5628
5629
def __or__(x, y):
5630
"""
5631
Return the bitwise or of the integers x and y.
5632
5633
EXAMPLES::
5634
5635
sage: n = 8; m = 4
5636
sage: n.__or__(m)
5637
12
5638
"""
5639
if PY_TYPE_CHECK(x, Integer) and PY_TYPE_CHECK(y, Integer):
5640
return (<Integer>x)._or(y)
5641
return bin_op(x, y, operator.or_)
5642
5643
def __invert__(self):
5644
"""
5645
Return the multiplicative inverse of self, as a rational number.
5646
5647
EXAMPLE::
5648
5649
sage: n = 10
5650
sage: 1/n
5651
1/10
5652
sage: n.__invert__()
5653
1/10
5654
"""
5655
return one / self
5656
5657
def inverse_of_unit(self):
5658
"""
5659
Return inverse of self if self is a unit in the integers, i.e.,
5660
self is -1 or 1. Otherwise, raise a ZeroDivisionError.
5661
5662
EXAMPLES::
5663
5664
sage: (1).inverse_of_unit()
5665
1
5666
sage: (-1).inverse_of_unit()
5667
-1
5668
sage: 5.inverse_of_unit()
5669
Traceback (most recent call last):
5670
...
5671
ZeroDivisionError: Inverse does not exist.
5672
sage: 0.inverse_of_unit()
5673
Traceback (most recent call last):
5674
...
5675
ZeroDivisionError: Inverse does not exist.
5676
"""
5677
if mpz_cmpabs_ui(self.value, 1) == 0:
5678
return self
5679
else:
5680
raise ZeroDivisionError, "Inverse does not exist."
5681
5682
def inverse_mod(self, n):
5683
"""
5684
Returns the inverse of self modulo `n`, if this inverse exists.
5685
Otherwise, raises a ``ZeroDivisionError`` exception.
5686
5687
INPUT:
5688
5689
- ``self`` - Integer
5690
5691
- ``n`` - Integer, or ideal of integer ring
5692
5693
OUTPUT:
5694
5695
- ``x`` - Integer such that x\*self = 1 (mod m), or
5696
raises ZeroDivisionError.
5697
5698
IMPLEMENTATION:
5699
5700
Call the mpz_invert GMP library function.
5701
5702
EXAMPLES::
5703
5704
sage: a = Integer(189)
5705
sage: a.inverse_mod(10000)
5706
4709
5707
sage: a.inverse_mod(-10000)
5708
4709
5709
sage: a.inverse_mod(1890)
5710
Traceback (most recent call last):
5711
...
5712
ZeroDivisionError: Inverse does not exist.
5713
sage: a = Integer(19)**100000
5714
sage: b = a*a
5715
sage: c = a.inverse_mod(b)
5716
Traceback (most recent call last):
5717
...
5718
ZeroDivisionError: Inverse does not exist.
5719
5720
We check that #10625 is fixed::
5721
5722
sage: ZZ(2).inverse_mod(ZZ.ideal(3))
5723
2
5724
5725
We check that #9955 is fixed::
5726
5727
sage: Rational(3)%Rational(-1)
5728
0
5729
"""
5730
cdef int r
5731
if isinstance(n, sage.rings.ideal.Ideal_pid) and n.ring() == the_integer_ring:
5732
n = n.gen()
5733
cdef Integer m = as_Integer(n)
5734
cdef Integer ans = <Integer>PY_NEW(Integer)
5735
if mpz_cmpabs_ui(m.value, 1) == 0:
5736
return zero
5737
sig_on()
5738
r = mpz_invert(ans.value, self.value, m.value)
5739
sig_off()
5740
if r == 0:
5741
raise ZeroDivisionError, "Inverse does not exist."
5742
return ans
5743
5744
def gcd(self, n):
5745
"""
5746
Return the greatest common divisor of self and `n`.
5747
5748
EXAMPLE::
5749
5750
sage: gcd(-1,1)
5751
1
5752
sage: gcd(0,1)
5753
1
5754
sage: gcd(0,0)
5755
0
5756
sage: gcd(2,2^6)
5757
2
5758
sage: gcd(21,2^6)
5759
1
5760
"""
5761
if not isinstance(n, Integer) and not isinstance(n, int):
5762
left, right = canonical_coercion(self, n)
5763
return left.gcd(right)
5764
cdef Integer m = as_Integer(n)
5765
cdef Integer g = PY_NEW(Integer)
5766
sig_on()
5767
mpz_gcd(g.value, self.value, m.value)
5768
sig_off()
5769
return g
5770
5771
def crt(self, y, m, n):
5772
"""
5773
Return the unique integer between `0` and `mn` that is congruent to
5774
the integer modulo `m` and to `y` modulo `n`. We assume that `m` and
5775
`n` are coprime.
5776
5777
EXAMPLES::
5778
5779
sage: n = 17
5780
sage: m = n.crt(5, 23, 11); m
5781
247
5782
sage: m%23
5783
17
5784
sage: m%11
5785
5
5786
"""
5787
cdef object g, s, t
5788
cdef Integer _y, _m, _n
5789
_y = Integer(y); _m = Integer(m); _n = Integer(n)
5790
g, s, t = _m.xgcd(_n)
5791
if not g.is_one():
5792
raise ArithmeticError, "CRT requires that gcd of moduli is 1."
5793
# Now s*m + t*n = 1, so the answer is x + (y-x)*s*m, where x=self.
5794
return (self + (_y - self) * s * _m) % (_m * _n)
5795
5796
def test_bit(self, long index):
5797
r"""
5798
Return the bit at ``index``.
5799
5800
If the index is negative, returns 0.
5801
5802
Although internally a sign-magnitude representation is used
5803
for integers, this method pretends to use a two's complement
5804
representation. This is illustrated with a negative integer
5805
below.
5806
5807
EXAMPLES::
5808
5809
sage: w = 6
5810
sage: w.str(2)
5811
'110'
5812
sage: w.test_bit(2)
5813
1
5814
sage: w.test_bit(-1)
5815
0
5816
sage: x = -20
5817
sage: x.str(2)
5818
'-10100'
5819
sage: x.test_bit(4)
5820
0
5821
sage: x.test_bit(5)
5822
1
5823
sage: x.test_bit(6)
5824
1
5825
"""
5826
if index < 0:
5827
return 0
5828
else:
5829
return mpz_tstbit(self.value, index)
5830
5831
def popcount(self):
5832
"""
5833
Return the number of 1 bits in the binary representation.
5834
If self<0, we return Infinity.
5835
5836
EXAMPLES::
5837
5838
sage: n = 123
5839
sage: n.str(2)
5840
'1111011'
5841
sage: n.popcount()
5842
6
5843
5844
sage: n = -17
5845
sage: n.popcount()
5846
+Infinity
5847
"""
5848
if self<0:
5849
return sage.rings.infinity.Infinity
5850
return int(mpz_popcount(self.value))
5851
5852
5853
def conjugate(self):
5854
"""
5855
Return the complex conjugate of this integer, which is the
5856
integer itself.
5857
5858
EXAMPLES:
5859
sage: n = 205
5860
sage: n.conjugate()
5861
205
5862
"""
5863
return self
5864
5865
def binomial(self, m, algorithm='mpir'):
5866
"""
5867
Return the binomial coefficient "self choose m".
5868
5869
INPUT:
5870
5871
- ``m`` -- an integer
5872
5873
- ``algorithm`` -- ``'mpir'`` (default) or ``'pari'``; ``'mpir'`` is
5874
faster for small ``m``, and ``'pari'`` tends to be faster for
5875
large ``m``
5876
5877
OUTPUT:
5878
5879
- integer
5880
5881
EXAMPLES::
5882
5883
sage: 10.binomial(2)
5884
45
5885
sage: 10.binomial(2, algorithm='pari')
5886
45
5887
sage: 10.binomial(-2)
5888
0
5889
"""
5890
cdef Integer x
5891
if m < 0:
5892
return the_integer_ring.zero()
5893
if algorithm == 'mpir':
5894
x = PY_NEW(Integer)
5895
sig_on()
5896
mpz_bin_ui(x.value, self.value, m)
5897
sig_off()
5898
return x
5899
elif algorithm == 'pari':
5900
return the_integer_ring(self._pari_().binomial(m))
5901
else:
5902
raise ValueError("algorithm must be one of: 'pari', 'mpir'")
5903
5904
5905
cpdef LCM_list(v):
5906
"""
5907
Return the LCM of a list v of integers. Elements of v are converted
5908
to Sage integers if they aren't already.
5909
5910
This function is used, e.g., by rings/arith.py
5911
5912
INPUT:
5913
5914
- ``v`` - list or tuple
5915
5916
OUTPUT: integer
5917
5918
EXAMPLES::
5919
5920
sage: from sage.rings.integer import LCM_list
5921
sage: w = LCM_list([3,9,30]); w
5922
90
5923
sage: type(w)
5924
<type 'sage.rings.integer.Integer'>
5925
5926
The inputs are converted to Sage integers.
5927
5928
::
5929
5930
sage: w = LCM_list([int(3), int(9), '30']); w
5931
90
5932
sage: type(w)
5933
<type 'sage.rings.integer.Integer'>
5934
"""
5935
cdef int i, n = len(v)
5936
cdef Integer z = <Integer>PY_NEW(Integer)
5937
5938
for i from 0 <= i < n:
5939
if not isinstance(v[i], Integer):
5940
if not isinstance(v, list):
5941
v = list(v)
5942
v[i] = Integer(v[i])
5943
5944
if n == 0:
5945
return one
5946
elif n == 1:
5947
return v[0].abs()
5948
5949
sig_on()
5950
mpz_lcm(z.value, (<Integer>v[0]).value, (<Integer>v[1]).value)
5951
for i from 2 <= i < n:
5952
mpz_lcm(z.value, z.value, (<Integer>v[i]).value)
5953
sig_off()
5954
5955
return z
5956
5957
def GCD_list(v):
5958
r"""
5959
Return the GCD of a list v of integers. Elements of v are converted
5960
to Sage integers if they aren't already.
5961
5962
This function is used, e.g., by rings/arith.py
5963
5964
INPUT:
5965
5966
- ``v`` - list or tuple
5967
5968
OUTPUT: integer
5969
5970
EXAMPLES::
5971
5972
sage: from sage.rings.integer import GCD_list
5973
sage: w = GCD_list([3,9,30]); w
5974
3
5975
sage: type(w)
5976
<type 'sage.rings.integer.Integer'>
5977
5978
Check that the bug reported in trac #3118 has been fixed::
5979
5980
sage: sage.rings.integer.GCD_list([2,2,3])
5981
1
5982
5983
The inputs are converted to Sage integers.
5984
5985
::
5986
5987
sage: w = GCD_list([int(3), int(9), '30']); w
5988
3
5989
sage: type(w)
5990
<type 'sage.rings.integer.Integer'>
5991
"""
5992
cdef int i, n = len(v)
5993
cdef Integer z = <Integer>PY_NEW(Integer)
5994
5995
for i from 0 <= i < n:
5996
if not isinstance(v[i], Integer):
5997
if not isinstance(v, list):
5998
v = list(v)
5999
v[i] = Integer(v[i])
6000
6001
if n == 0:
6002
return one
6003
elif n == 1:
6004
return v[0].abs()
6005
6006
sig_on()
6007
mpz_gcd(z.value, (<Integer>v[0]).value, (<Integer>v[1]).value)
6008
for i from 2 <= i < n:
6009
if mpz_cmp_ui(z.value, 1) == 0:
6010
break
6011
mpz_gcd(z.value, z.value, (<Integer>v[i]).value)
6012
sig_off()
6013
6014
return z
6015
6016
def make_integer(s):
6017
"""
6018
Create a Sage integer from the base-32 Python *string* s. This is
6019
used in unpickling integers.
6020
6021
EXAMPLES::
6022
6023
sage: from sage.rings.integer import make_integer
6024
sage: make_integer('-29')
6025
-73
6026
sage: make_integer(29)
6027
Traceback (most recent call last):
6028
...
6029
TypeError: expected string or Unicode object, sage.rings.integer.Integer found
6030
"""
6031
cdef Integer r = PY_NEW(Integer)
6032
r._reduce_set(s)
6033
return r
6034
6035
cdef class int_to_Z(Morphism):
6036
def __init__(self):
6037
import integer_ring
6038
import sage.categories.homset
6039
from sage.structure.parent import Set_PythonType
6040
Morphism.__init__(self, sage.categories.homset.Hom(Set_PythonType(int), integer_ring.ZZ))
6041
cpdef Element _call_(self, a):
6042
cdef Integer r
6043
r = <Integer>PY_NEW(Integer)
6044
mpz_set_si(r.value, PyInt_AS_LONG(a))
6045
return r
6046
def _repr_type(self):
6047
return "Native"
6048
6049
cdef class long_to_Z(Morphism):
6050
"""
6051
EXAMPLES::
6052
6053
sage: f = ZZ.coerce_map_from(long); f
6054
Native morphism:
6055
From: Set of Python objects of type 'long'
6056
To: Integer Ring
6057
sage: f(1rL)
6058
1
6059
sage: f(-10000000000000000000001r)
6060
-10000000000000000000001
6061
"""
6062
def __init__(self):
6063
import integer_ring
6064
import sage.categories.homset
6065
from sage.structure.parent import Set_PythonType
6066
Morphism.__init__(self, sage.categories.homset.Hom(Set_PythonType(long), integer_ring.ZZ))
6067
cpdef Element _call_(self, a):
6068
cdef Integer r
6069
r = <Integer>PY_NEW(Integer)
6070
mpz_set_pylong(r.value, a)
6071
return r
6072
def _repr_type(self):
6073
return "Native"
6074
6075
############### INTEGER CREATION CODE #####################
6076
6077
# We need a couple of internal GMP datatypes.
6078
6079
# This may be potentially very dangerous as it reaches
6080
# deeply into the internal structure of GMP which may not
6081
# be consistent across future versions of GMP.
6082
# See extensive note in the fast_tp_new() function below.
6083
6084
include "sage/ext/python_rich_object.pxi"
6085
cdef extern from "gmp.h":
6086
ctypedef long mp_limb_t
6087
ctypedef mp_limb_t* mp_ptr #"mp_ptr"
6088
6089
# We allocate _mp_d directly (mpz_t is typedef of this in GMP)
6090
ctypedef struct __mpz_struct "__mpz_struct":
6091
int _mp_alloc
6092
int _mp_size
6093
mp_ptr _mp_d
6094
6095
# sets the three free, alloc, and realloc function pointers to the
6096
# memory management functions set in GMP. Accepts NULL pointer.
6097
# Potentially dangerous if changed by calling
6098
# mp_set_memory_functions again after we initialized this module.
6099
void mp_get_memory_functions (void *(**alloc) (size_t), void *(**realloc)(void *, size_t, size_t), void (**free) (void *, size_t))
6100
6101
# GMP's configuration of how many Bits are stuffed into a limb
6102
cdef int GMP_LIMB_BITS
6103
6104
# This variable holds the size of any Integer object in bytes.
6105
cdef int sizeof_Integer
6106
6107
# We use a global Integer element to steal all the references
6108
# from. DO NOT INITIALIZE IT AGAIN and DO NOT REFERENCE IT!
6109
cdef Integer global_dummy_Integer
6110
global_dummy_Integer = Integer()
6111
6112
# Accessing the .value attribute of an Integer object causes Cython to
6113
# refcount it. This is problematic, because that causes overhead and
6114
# more importantly an infinite loop in the destructor. If you refcount
6115
# in the destructor and the refcount reaches zero (which is true
6116
# every time) the destructor is called.
6117
#
6118
# To avoid this we calculate the byte offset of the value member and
6119
# remember it in this variable.
6120
#
6121
# Eventually this may be rendered obsolete by a change in Cython allowing
6122
# non-reference counted extension types.
6123
cdef long mpz_t_offset
6124
mpz_t_offset_python = None
6125
6126
6127
# stores the GMP alloc function
6128
cdef void * (* mpz_alloc)(size_t)
6129
6130
# stores the GMP free function
6131
cdef void (* mpz_free)(void *, size_t)
6132
6133
# A global pool for performance when integers are rapidly created and destroyed.
6134
# It operates on the following principles:
6135
#
6136
# - The pool starts out empty.
6137
# - When an new integer is needed, one from the pool is returned
6138
# if available, otherwise a new Integer object is created
6139
# - When an integer is collected, it will add it to the pool
6140
# if there is room, otherwise it will be deallocated.
6141
6142
6143
cdef int integer_pool_size = 100
6144
6145
cdef PyObject** integer_pool
6146
cdef int integer_pool_count = 0
6147
6148
# used for profiling the pool
6149
cdef int total_alloc = 0
6150
cdef int use_pool = 0
6151
6152
6153
cdef PyObject* fast_tp_new(PyTypeObject *t, PyObject *a, PyObject *k):
6154
6155
global integer_pool, integer_pool_count, total_alloc, use_pool
6156
6157
cdef PyObject* new
6158
6159
# for profiling pool usage
6160
# total_alloc += 1
6161
6162
# If there is a ready integer in the pool, we will
6163
# decrement the counter and return that.
6164
6165
if integer_pool_count > 0:
6166
6167
# for profiling pool usage
6168
# use_pool += 1
6169
6170
integer_pool_count -= 1
6171
new = <PyObject *> integer_pool[integer_pool_count]
6172
6173
# Otherwise, we have to create one.
6174
6175
else:
6176
6177
# allocate enough room for the Integer, sizeof_Integer is
6178
# sizeof(Integer). The use of PyObject_MALLOC directly
6179
# assumes that Integers are not garbage collected, i.e.
6180
# they do not possess references to other Python
6181
# objects (as indicated by the Py_TPFLAGS_HAVE_GC flag).
6182
# See below for a more detailed description.
6183
new = PyObject_MALLOC( sizeof_Integer )
6184
6185
# Now set every member as set in z, the global dummy Integer
6186
# created before this tp_new started to operate.
6187
6188
memcpy(new, (<void*>global_dummy_Integer), sizeof_Integer )
6189
6190
# We take the address 'new' and move mpz_t_offset bytes (chars)
6191
# to the address of 'value'. We treat that address as a pointer
6192
# to a mpz_t struct and allocate memory for the _mp_d element of
6193
# that struct. We allocate one limb.
6194
#
6195
# What is done here is potentially very dangerous as it reaches
6196
# deeply into the internal structure of GMP. Consequently things
6197
# may break if a new release of GMP changes some internals. To
6198
# emphasize this, this is what the GMP manual has to say about
6199
# the documentation for the struct we are using:
6200
#
6201
# "This chapter is provided only for informational purposes and the
6202
# various internals described here may change in future GMP releases.
6203
# Applications expecting to be compatible with future releases should use
6204
# only the documented interfaces described in previous chapters."
6205
#
6206
# If this line is used Sage is not such an application.
6207
#
6208
# The clean version of the following line is:
6209
#
6210
# mpz_init( <mpz_t>(<char *>new + mpz_t_offset) )
6211
#
6212
# We save time both by avoiding an extra function call and
6213
# because the rest of the mpz struct was already initialized
6214
# fully using the memcpy above.
6215
6216
(<__mpz_struct *>( <char *>new + mpz_t_offset) )._mp_d = <mp_ptr>mpz_alloc(GMP_LIMB_BITS >> 3)
6217
6218
# This line is only needed if Python is compiled in debugging mode
6219
# './configure --with-pydebug' or SAGE_DEBUG=yes. If that is the
6220
# case a Python object has a bunch of debugging fields which are
6221
# initialized with this macro.
6222
6223
if_Py_TRACE_REFS_then_PyObject_INIT\
6224
(new, (<PyObject*>global_dummy_Integer).ob_type)
6225
6226
# The global_dummy_Integer may have a reference count larger than
6227
# one, but it is expected that newly created objects have a
6228
# reference count of one. This is potentially unneeded if
6229
# everybody plays nice, because the gobal_dummy_Integer has only
6230
# one reference in that case.
6231
6232
# Objects from the pool have reference count zero, so this
6233
# needs to be set in this case.
6234
6235
new.ob_refcnt = 1
6236
6237
return new
6238
6239
cdef void fast_tp_dealloc(PyObject* o):
6240
6241
# If there is room in the pool for a used integer object,
6242
# then put it in rather than deallocating it.
6243
6244
global integer_pool, integer_pool_count
6245
6246
if integer_pool_count < integer_pool_size:
6247
6248
# Here we free any extra memory used by the mpz_t by
6249
# setting it to a single limb.
6250
if (<__mpz_struct *>( <char *>o + mpz_t_offset))._mp_alloc > 10:
6251
_mpz_realloc(<mpz_t *>( <char *>o + mpz_t_offset), 10)
6252
6253
# It's cheap to zero out an integer, so do it here.
6254
(<__mpz_struct *>( <char *>o + mpz_t_offset))._mp_size = 0
6255
6256
# And add it to the pool.
6257
integer_pool[integer_pool_count] = o
6258
integer_pool_count += 1
6259
return
6260
6261
# Again, we move to the mpz_t and clear it. See above, why this is evil.
6262
# The clean version of this line would be:
6263
# mpz_clear(<mpz_t>(<char *>o + mpz_t_offset))
6264
6265
mpz_free((<__mpz_struct *>( <char *>o + mpz_t_offset) )._mp_d, 0)
6266
6267
# Free the object. This assumes that Py_TPFLAGS_HAVE_GC is not
6268
# set. If it was set another free function would need to be
6269
# called.
6270
6271
PyObject_FREE(o)
6272
6273
from sage.misc.allocator cimport hook_tp_functions
6274
cdef hook_fast_tp_functions():
6275
"""
6276
Initialize the fast integer creation functions.
6277
"""
6278
global global_dummy_Integer, mpz_t_offset, sizeof_Integer, integer_pool
6279
6280
integer_pool = <PyObject**>sage_malloc(integer_pool_size * sizeof(PyObject*))
6281
6282
cdef PyObject* o
6283
o = <PyObject *>global_dummy_Integer
6284
6285
# calculate the offset of the GMP mpz_t to avoid casting to/from
6286
# an Integer which includes reference counting. Reference counting
6287
# is bad in constructors and destructors as it potentially calls
6288
# the destructor.
6289
# Eventually this may be rendered obsolete by a change in Cython allowing
6290
# non-reference counted extension types.
6291
mpz_t_offset = <char *>(&global_dummy_Integer.value) - <char *>o
6292
global mpz_t_offset_python
6293
mpz_t_offset_python = mpz_t_offset
6294
6295
# store how much memory needs to be allocated for an Integer.
6296
sizeof_Integer = (<RichPyTypeObject *>o.ob_type).tp_basicsize
6297
6298
# get the functions to do memory management for the GMP elements
6299
# WARNING: if the memory management functions are changed after
6300
# this initialisation, we are/you are doomed.
6301
6302
mp_get_memory_functions(&mpz_alloc, NULL, &mpz_free)
6303
6304
# Finally replace the functions called when an Integer needs
6305
# to be constructed/destructed.
6306
hook_tp_functions(global_dummy_Integer, NULL, &fast_tp_new, NULL, &fast_tp_dealloc, False)
6307
6308
cdef integer(x):
6309
if PY_TYPE_CHECK(x, Integer):
6310
return x
6311
return Integer(x)
6312
6313
6314
def free_integer_pool():
6315
cdef int i
6316
cdef PyObject *o
6317
6318
global integer_pool_count, integer_pool_size
6319
6320
for i from 0 <= i < integer_pool_count:
6321
o = integer_pool[i]
6322
mpz_clear(<__mpz_struct *>(<char*>o + mpz_t_offset))
6323
# Free the object. This assumes that Py_TPFLAGS_HAVE_GC is not
6324
# set. If it was set another free function would need to be
6325
# called.
6326
PyObject_FREE(o)
6327
6328
integer_pool_size = 0
6329
integer_pool_count = 0
6330
sage_free(integer_pool)
6331
6332
# Replace default allocation and deletion with faster custom ones
6333
hook_fast_tp_functions()
6334
6335
# zero and one initialization
6336
initialized = False
6337
cdef set_zero_one_elements():
6338
global the_integer_ring, initialized
6339
if initialized: return
6340
the_integer_ring._zero_element = Integer(0)
6341
the_integer_ring._one_element = Integer(1)
6342
init_mpz_globals()
6343
initialized = True
6344
set_zero_one_elements()
6345
6346
cdef Integer zero = the_integer_ring._zero_element
6347
cdef Integer one = the_integer_ring._one_element
6348
6349
# pool of small integer for fast sign computation
6350
cdef long small_pool_min = -1
6351
cdef long small_pool_max = 1
6352
# we could use the above zero and one here
6353
cdef list small_pool = [Integer(k) for k in range(small_pool_min, small_pool_max+1)]
6354
cdef inline Integer smallInteger(long value):
6355
cdef Integer z
6356
if small_pool_min <= value <= small_pool_max:
6357
return <Integer>small_pool[value - small_pool_min]
6358
else:
6359
z = PY_NEW(Integer)
6360
mpz_set_si(z.value, value)
6361
return z
6362
6363