3 /* Long (arbitrary precision) integer object implementation */
5 /* XXX The functional organization of this file is terrible */
8 #include "longintrepr.h"
12 /* For long multiplication, use the O(N**2) school algorithm unless
13 * both operands contain more than KARATSUBA_CUTOFF digits (this
14 * being an internal Python long digit, in base BASE).
16 #define KARATSUBA_CUTOFF 70
17 #define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)
19 /* For exponentiation, use the binary left-to-right algorithm
20 * unless the exponent contains more than FIVEARY_CUTOFF digits.
21 * In that case, do 5 bits at a time. The potential drawback is that
22 * a table of 2**5 intermediate results is computed.
24 #define FIVEARY_CUTOFF 8
26 #define ABS(x) ((x) < 0 ? -(x) : (x))
30 #define MAX(x, y) ((x) < (y) ? (y) : (x))
31 #define MIN(x, y) ((x) > (y) ? (y) : (x))
34 static PyLongObject
*long_normalize(PyLongObject
*);
35 static PyLongObject
*mul1(PyLongObject
*, wdigit
);
36 static PyLongObject
*muladd1(PyLongObject
*, wdigit
, wdigit
);
37 static PyLongObject
*divrem1(PyLongObject
*, digit
, digit
*);
38 static PyObject
*long_format(PyObject
*aa
, int base
, int addL
);
40 #define SIGCHECK(PyTryBlock) \
41 if (--_Py_Ticker < 0) { \
42 _Py_Ticker = _Py_CheckInterval; \
43 if (PyErr_CheckSignals()) PyTryBlock \
46 /* Normalize (remove leading zeros from) a long int object.
47 Doesn't attempt to free the storage--in most cases, due to the nature
48 of the algorithms used, this could save at most be one word anyway. */
51 long_normalize(register PyLongObject
*v
)
53 Py_ssize_t j
= ABS(v
->ob_size
);
56 while (i
> 0 && v
->ob_digit
[i
-1] == 0)
59 v
->ob_size
= (v
->ob_size
< 0) ? -(i
) : i
;
63 /* Allocate a new long int object with size digits.
64 Return NULL and set exception if we run out of memory. */
67 _PyLong_New(Py_ssize_t size
)
69 if (size
> PY_SSIZE_T_MAX
) {
73 return PyObject_NEW_VAR(PyLongObject
, &PyLong_Type
, size
);
77 _PyLong_Copy(PyLongObject
*src
)
86 result
= _PyLong_New(i
);
88 result
->ob_size
= src
->ob_size
;
90 result
->ob_digit
[i
] = src
->ob_digit
[i
];
92 return (PyObject
*)result
;
95 /* Create a new long int object from a C long int */
98 PyLong_FromLong(long ival
)
101 unsigned long t
; /* unsigned so >> doesn't propagate sign bit */
110 /* Count the number of Python digits.
111 We used to pick 5 ("big enough for anything"), but that's a
112 waste of time and space given that 5*15 = 75 bits are rarely
114 t
= (unsigned long)ival
;
119 v
= _PyLong_New(ndigits
);
121 digit
*p
= v
->ob_digit
;
122 v
->ob_size
= negative
? -ndigits
: ndigits
;
123 t
= (unsigned long)ival
;
125 *p
++ = (digit
)(t
& MASK
);
129 return (PyObject
*)v
;
132 /* Create a new long int object from a C unsigned long int */
135 PyLong_FromUnsignedLong(unsigned long ival
)
141 /* Count the number of Python digits. */
142 t
= (unsigned long)ival
;
147 v
= _PyLong_New(ndigits
);
149 digit
*p
= v
->ob_digit
;
150 v
->ob_size
= ndigits
;
152 *p
++ = (digit
)(ival
& MASK
);
156 return (PyObject
*)v
;
159 /* Create a new long int object from a C double */
162 PyLong_FromDouble(double dval
)
166 int i
, ndig
, expo
, neg
;
168 if (Py_IS_INFINITY(dval
)) {
169 PyErr_SetString(PyExc_OverflowError
,
170 "cannot convert float infinity to long");
177 frac
= frexp(dval
, &expo
); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
179 return PyLong_FromLong(0L);
180 ndig
= (expo
-1) / SHIFT
+ 1; /* Number of 'digits' in result */
181 v
= _PyLong_New(ndig
);
184 frac
= ldexp(frac
, (expo
-1) % SHIFT
+ 1);
185 for (i
= ndig
; --i
>= 0; ) {
186 long bits
= (long)frac
;
187 v
->ob_digit
[i
] = (digit
) bits
;
188 frac
= frac
- (double)bits
;
189 frac
= ldexp(frac
, SHIFT
);
192 v
->ob_size
= -(v
->ob_size
);
193 return (PyObject
*)v
;
196 /* Get a C long int from a long int object.
197 Returns -1 and sets an error condition if overflow occurs. */
200 PyLong_AsLong(PyObject
*vv
)
202 /* This version by Tim Peters */
203 register PyLongObject
*v
;
204 unsigned long x
, prev
;
208 if (vv
== NULL
|| !PyLong_Check(vv
)) {
209 if (vv
!= NULL
&& PyInt_Check(vv
))
210 return PyInt_AsLong(vv
);
211 PyErr_BadInternalCall();
214 v
= (PyLongObject
*)vv
;
224 x
= (x
<< SHIFT
) + v
->ob_digit
[i
];
225 if ((x
>> SHIFT
) != prev
)
228 /* Haven't lost any bits, but if the sign bit is set we're in
229 * trouble *unless* this is the min negative number. So,
230 * trouble iff sign bit set && (positive || some bit set other
231 * than the sign bit).
233 if ((long)x
< 0 && (sign
> 0 || (x
<< 1) != 0))
235 return (long)x
* sign
;
238 PyErr_SetString(PyExc_OverflowError
,
239 "long int too large to convert to int");
244 _long_as_ssize_t(PyObject
*vv
) {
245 register PyLongObject
*v
;
250 if (vv
== NULL
|| !PyLong_Check(vv
)) {
251 PyErr_BadInternalCall();
254 v
= (PyLongObject
*)vv
;
264 x
= (x
<< SHIFT
) + v
->ob_digit
[i
];
265 if ((x
>> SHIFT
) != prev
)
268 /* Haven't lost any bits, but if the sign bit is set we're in
269 * trouble *unless* this is the min negative number. So,
270 * trouble iff sign bit set && (positive || some bit set other
271 * than the sign bit).
273 if ((Py_ssize_t
)x
< 0 && (sign
> 0 || (x
<< 1) != 0))
275 return (Py_ssize_t
)x
* sign
;
278 PyErr_SetString(PyExc_OverflowError
,
279 "long int too large to convert to int");
281 return PY_SSIZE_T_MAX
;
283 return PY_SSIZE_T_MIN
;
286 /* Get a Py_ssize_t from a long int object.
287 Returns -1 and sets an error condition if overflow occurs. */
290 _PyLong_AsSsize_t(PyObject
*vv
)
294 x
= _long_as_ssize_t(vv
);
295 if (PyErr_Occurred()) return -1;
300 /* Get a Py_ssize_t from a long int object.
301 Silently reduce values larger than PY_SSIZE_T_MAX to PY_SSIZE_T_MAX,
302 and silently boost values less than -PY_SSIZE_T_MAX-1 to -PY_SSIZE_T_MAX-1.
303 On error, return -1 with an exception set.
307 long_index(PyObject
*vv
)
311 x
= _long_as_ssize_t(vv
);
312 if (PyErr_Occurred()) {
313 /* If overflow error, ignore the error */
321 /* Get a C unsigned long int from a long int object.
322 Returns -1 and sets an error condition if overflow occurs. */
325 PyLong_AsUnsignedLong(PyObject
*vv
)
327 register PyLongObject
*v
;
328 unsigned long x
, prev
;
331 if (vv
== NULL
|| !PyLong_Check(vv
)) {
332 if (vv
!= NULL
&& PyInt_Check(vv
)) {
333 long val
= PyInt_AsLong(vv
);
335 PyErr_SetString(PyExc_OverflowError
,
336 "can't convert negative value to unsigned long");
337 return (unsigned long) -1;
341 PyErr_BadInternalCall();
342 return (unsigned long) -1;
344 v
= (PyLongObject
*)vv
;
348 PyErr_SetString(PyExc_OverflowError
,
349 "can't convert negative value to unsigned long");
350 return (unsigned long) -1;
354 x
= (x
<< SHIFT
) + v
->ob_digit
[i
];
355 if ((x
>> SHIFT
) != prev
) {
356 PyErr_SetString(PyExc_OverflowError
,
357 "long int too large to convert");
358 return (unsigned long) -1;
364 /* Get a C unsigned long int from a long int object, ignoring the high bits.
365 Returns -1 and sets an error condition if an error occurs. */
368 PyLong_AsUnsignedLongMask(PyObject
*vv
)
370 register PyLongObject
*v
;
375 if (vv
== NULL
|| !PyLong_Check(vv
)) {
376 if (vv
!= NULL
&& PyInt_Check(vv
))
377 return PyInt_AsUnsignedLongMask(vv
);
378 PyErr_BadInternalCall();
379 return (unsigned long) -1;
381 v
= (PyLongObject
*)vv
;
390 x
= (x
<< SHIFT
) + v
->ob_digit
[i
];
396 _PyLong_Sign(PyObject
*vv
)
398 PyLongObject
*v
= (PyLongObject
*)vv
;
401 assert(PyLong_Check(v
));
403 return v
->ob_size
== 0 ? 0 : (v
->ob_size
< 0 ? -1 : 1);
407 _PyLong_NumBits(PyObject
*vv
)
409 PyLongObject
*v
= (PyLongObject
*)vv
;
414 assert(PyLong_Check(v
));
415 ndigits
= ABS(v
->ob_size
);
416 assert(ndigits
== 0 || v
->ob_digit
[ndigits
- 1] != 0);
418 digit msd
= v
->ob_digit
[ndigits
- 1];
420 result
= (ndigits
- 1) * SHIFT
;
421 if (result
/ SHIFT
!= (size_t)(ndigits
- 1))
433 PyErr_SetString(PyExc_OverflowError
, "long has too many bits "
434 "to express in a platform size_t");
439 _PyLong_FromByteArray(const unsigned char* bytes
, size_t n
,
440 int little_endian
, int is_signed
)
442 const unsigned char* pstartbyte
;/* LSB of bytes */
443 int incr
; /* direction to move pstartbyte */
444 const unsigned char* pendbyte
; /* MSB of bytes */
445 size_t numsignificantbytes
; /* number of bytes that matter */
446 size_t ndigits
; /* number of Python long digits */
447 PyLongObject
* v
; /* result */
448 int idigit
= 0; /* next free index in v->ob_digit */
451 return PyLong_FromLong(0L);
455 pendbyte
= bytes
+ n
- 1;
459 pstartbyte
= bytes
+ n
- 1;
465 is_signed
= *pendbyte
>= 0x80;
467 /* Compute numsignificantbytes. This consists of finding the most
468 significant byte. Leading 0 bytes are insignficant if the number
469 is positive, and leading 0xff bytes if negative. */
472 const unsigned char* p
= pendbyte
;
473 const int pincr
= -incr
; /* search MSB to LSB */
474 const unsigned char insignficant
= is_signed
? 0xff : 0x00;
476 for (i
= 0; i
< n
; ++i
, p
+= pincr
) {
477 if (*p
!= insignficant
)
480 numsignificantbytes
= n
- i
;
481 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
482 actually has 2 significant bytes. OTOH, 0xff0001 ==
483 -0x00ffff, so we wouldn't *need* to bump it there; but we
484 do for 0xffff = -0x0001. To be safe without bothering to
485 check every case, bump it regardless. */
486 if (is_signed
&& numsignificantbytes
< n
)
487 ++numsignificantbytes
;
490 /* How many Python long digits do we need? We have
491 8*numsignificantbytes bits, and each Python long digit has SHIFT
492 bits, so it's the ceiling of the quotient. */
493 ndigits
= (numsignificantbytes
* 8 + SHIFT
- 1) / SHIFT
;
494 if (ndigits
> (size_t)INT_MAX
)
495 return PyErr_NoMemory();
496 v
= _PyLong_New((int)ndigits
);
500 /* Copy the bits over. The tricky parts are computing 2's-comp on
501 the fly for signed numbers, and dealing with the mismatch between
502 8-bit bytes and (probably) 15-bit Python digits.*/
505 twodigits carry
= 1; /* for 2's-comp calculation */
506 twodigits accum
= 0; /* sliding register */
507 unsigned int accumbits
= 0; /* number of bits in accum */
508 const unsigned char* p
= pstartbyte
;
510 for (i
= 0; i
< numsignificantbytes
; ++i
, p
+= incr
) {
511 twodigits thisbyte
= *p
;
512 /* Compute correction for 2's comp, if needed. */
514 thisbyte
= (0xff ^ thisbyte
) + carry
;
515 carry
= thisbyte
>> 8;
518 /* Because we're going LSB to MSB, thisbyte is
519 more significant than what's already in accum,
520 so needs to be prepended to accum. */
521 accum
|= thisbyte
<< accumbits
;
523 if (accumbits
>= SHIFT
) {
524 /* There's enough to fill a Python digit. */
525 assert(idigit
< (int)ndigits
);
526 v
->ob_digit
[idigit
] = (digit
)(accum
& MASK
);
530 assert(accumbits
< SHIFT
);
533 assert(accumbits
< SHIFT
);
535 assert(idigit
< (int)ndigits
);
536 v
->ob_digit
[idigit
] = (digit
)accum
;
541 v
->ob_size
= is_signed
? -idigit
: idigit
;
542 return (PyObject
*)long_normalize(v
);
546 _PyLong_AsByteArray(PyLongObject
* v
,
547 unsigned char* bytes
, size_t n
,
548 int little_endian
, int is_signed
)
550 int i
; /* index into v->ob_digit */
551 Py_ssize_t ndigits
; /* |v->ob_size| */
552 twodigits accum
; /* sliding register */
553 unsigned int accumbits
; /* # bits in accum */
554 int do_twos_comp
; /* store 2's-comp? is_signed and v < 0 */
555 twodigits carry
; /* for computing 2's-comp */
556 size_t j
; /* # bytes filled */
557 unsigned char* p
; /* pointer to next byte in bytes */
558 int pincr
; /* direction to move p */
560 assert(v
!= NULL
&& PyLong_Check(v
));
562 if (v
->ob_size
< 0) {
563 ndigits
= -(v
->ob_size
);
565 PyErr_SetString(PyExc_TypeError
,
566 "can't convert negative long to unsigned");
572 ndigits
= v
->ob_size
;
585 /* Copy over all the Python digits.
586 It's crucial that every Python digit except for the MSD contribute
587 exactly SHIFT bits to the total, so first assert that the long is
589 assert(ndigits
== 0 || v
->ob_digit
[ndigits
- 1] != 0);
593 carry
= do_twos_comp
? 1 : 0;
594 for (i
= 0; i
< ndigits
; ++i
) {
595 twodigits thisdigit
= v
->ob_digit
[i
];
597 thisdigit
= (thisdigit
^ MASK
) + carry
;
598 carry
= thisdigit
>> SHIFT
;
601 /* Because we're going LSB to MSB, thisdigit is more
602 significant than what's already in accum, so needs to be
603 prepended to accum. */
604 accum
|= thisdigit
<< accumbits
;
607 /* The most-significant digit may be (probably is) at least
609 if (i
== ndigits
- 1) {
610 /* Count # of sign bits -- they needn't be stored,
611 * although for signed conversion we need later to
612 * make sure at least one sign bit gets stored.
613 * First shift conceptual sign bit to real sign bit.
615 stwodigits s
= (stwodigits
)(thisdigit
<<
616 (8*sizeof(stwodigits
) - SHIFT
));
617 unsigned int nsignbits
= 0;
618 while ((s
< 0) == do_twos_comp
&& nsignbits
< SHIFT
) {
622 accumbits
-= nsignbits
;
625 /* Store as many bytes as possible. */
626 while (accumbits
>= 8) {
630 *p
= (unsigned char)(accum
& 0xff);
637 /* Store the straggler (if any). */
638 assert(accumbits
< 8);
639 assert(carry
== 0); /* else do_twos_comp and *every* digit was 0 */
645 /* Fill leading bits of the byte with sign bits
646 (appropriately pretending that the long had an
647 infinite supply of sign bits). */
648 accum
|= (~(twodigits
)0) << accumbits
;
650 *p
= (unsigned char)(accum
& 0xff);
653 else if (j
== n
&& n
> 0 && is_signed
) {
654 /* The main loop filled the byte array exactly, so the code
655 just above didn't get to ensure there's a sign bit, and the
656 loop below wouldn't add one either. Make sure a sign bit
658 unsigned char msb
= *(p
- pincr
);
659 int sign_bit_set
= msb
>= 0x80;
660 assert(accumbits
== 0);
661 if (sign_bit_set
== do_twos_comp
)
667 /* Fill remaining bytes with copies of the sign bit. */
669 unsigned char signbyte
= do_twos_comp
? 0xffU
: 0U;
670 for ( ; j
< n
; ++j
, p
+= pincr
)
677 PyErr_SetString(PyExc_OverflowError
, "long too big to convert");
683 _PyLong_AsScaledDouble(PyObject
*vv
, int *exponent
)
685 /* NBITS_WANTED should be > the number of bits in a double's precision,
686 but small enough so that 2**NBITS_WANTED is within the normal double
687 range. nbitsneeded is set to 1 less than that because the most-significant
688 Python digit contains at least 1 significant bit, but we don't want to
689 bother counting them (catering to the worst case cheaply).
691 57 is one more than VAX-D double precision; I (Tim) don't know of a double
692 format with more precision than that; it's 1 larger so that we add in at
693 least one round bit to stand in for the ignored least-significant bits.
695 #define NBITS_WANTED 57
698 const double multiplier
= (double)(1L << SHIFT
);
703 if (vv
== NULL
|| !PyLong_Check(vv
)) {
704 PyErr_BadInternalCall();
707 v
= (PyLongObject
*)vv
;
719 x
= (double)v
->ob_digit
[i
];
720 nbitsneeded
= NBITS_WANTED
- 1;
721 /* Invariant: i Python digits remain unaccounted for. */
722 while (i
> 0 && nbitsneeded
> 0) {
724 x
= x
* multiplier
+ (double)v
->ob_digit
[i
];
725 nbitsneeded
-= SHIFT
;
727 /* There are i digits we didn't shift in. Pretending they're all
728 zeroes, the true value is x * 2**(i*SHIFT). */
735 /* Get a C double from a long int object. */
738 PyLong_AsDouble(PyObject
*vv
)
743 if (vv
== NULL
|| !PyLong_Check(vv
)) {
744 PyErr_BadInternalCall();
747 x
= _PyLong_AsScaledDouble(vv
, &e
);
748 if (x
== -1.0 && PyErr_Occurred())
750 /* 'e' initialized to -1 to silence gcc-4.0.x, but it should be
751 set correctly after a successful _PyLong_AsScaledDouble() call */
753 if (e
> INT_MAX
/ SHIFT
)
756 x
= ldexp(x
, e
* SHIFT
);
757 if (Py_OVERFLOWED(x
))
762 PyErr_SetString(PyExc_OverflowError
,
763 "long int too large to convert to float");
767 /* Create a new long (or int) object from a C pointer */
770 PyLong_FromVoidPtr(void *p
)
772 #if SIZEOF_VOID_P <= SIZEOF_LONG
774 return PyLong_FromUnsignedLong((unsigned long)p
);
775 return PyInt_FromLong((long)p
);
778 #ifndef HAVE_LONG_LONG
779 # error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
781 #if SIZEOF_LONG_LONG < SIZEOF_VOID_P
782 # error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
784 /* optimize null pointers */
786 return PyInt_FromLong(0);
787 return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG
)p
);
789 #endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
792 /* Get a C pointer from a long object (or an int object in some cases) */
795 PyLong_AsVoidPtr(PyObject
*vv
)
797 /* This function will allow int or long objects. If vv is neither,
798 then the PyLong_AsLong*() functions will raise the exception:
799 PyExc_SystemError, "bad argument to internal function"
801 #if SIZEOF_VOID_P <= SIZEOF_LONG
805 x
= PyInt_AS_LONG(vv
);
806 else if (PyLong_Check(vv
) && _PyLong_Sign(vv
) < 0)
807 x
= PyLong_AsLong(vv
);
809 x
= PyLong_AsUnsignedLong(vv
);
812 #ifndef HAVE_LONG_LONG
813 # error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
815 #if SIZEOF_LONG_LONG < SIZEOF_VOID_P
816 # error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
821 x
= PyInt_AS_LONG(vv
);
822 else if (PyLong_Check(vv
) && _PyLong_Sign(vv
) < 0)
823 x
= PyLong_AsLongLong(vv
);
825 x
= PyLong_AsUnsignedLongLong(vv
);
827 #endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
829 if (x
== -1 && PyErr_Occurred())
834 #ifdef HAVE_LONG_LONG
836 /* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later
837 * rewritten to use the newer PyLong_{As,From}ByteArray API.
840 #define IS_LITTLE_ENDIAN (int)*(unsigned char*)&one
842 /* Create a new long int object from a C PY_LONG_LONG int. */
845 PyLong_FromLongLong(PY_LONG_LONG ival
)
848 unsigned PY_LONG_LONG t
; /* unsigned so >> doesn't propagate sign bit */
857 /* Count the number of Python digits.
858 We used to pick 5 ("big enough for anything"), but that's a
859 waste of time and space given that 5*15 = 75 bits are rarely
861 t
= (unsigned PY_LONG_LONG
)ival
;
866 v
= _PyLong_New(ndigits
);
868 digit
*p
= v
->ob_digit
;
869 v
->ob_size
= negative
? -ndigits
: ndigits
;
870 t
= (unsigned PY_LONG_LONG
)ival
;
872 *p
++ = (digit
)(t
& MASK
);
876 return (PyObject
*)v
;
879 /* Create a new long int object from a C unsigned PY_LONG_LONG int. */
882 PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival
)
885 unsigned PY_LONG_LONG t
;
888 /* Count the number of Python digits. */
889 t
= (unsigned PY_LONG_LONG
)ival
;
894 v
= _PyLong_New(ndigits
);
896 digit
*p
= v
->ob_digit
;
897 v
->ob_size
= ndigits
;
899 *p
++ = (digit
)(ival
& MASK
);
903 return (PyObject
*)v
;
906 /* Create a new long int object from a C Py_ssize_t. */
909 _PyLong_FromSsize_t(Py_ssize_t ival
)
911 Py_ssize_t bytes
= ival
;
913 return _PyLong_FromByteArray(
914 (unsigned char *)&bytes
,
915 SIZEOF_SIZE_T
, IS_LITTLE_ENDIAN
, 0);
918 /* Create a new long int object from a C size_t. */
921 _PyLong_FromSize_t(size_t ival
)
925 return _PyLong_FromByteArray(
926 (unsigned char *)&bytes
,
927 SIZEOF_SIZE_T
, IS_LITTLE_ENDIAN
, 0);
930 /* Get a C PY_LONG_LONG int from a long int object.
931 Return -1 and set an error if overflow occurs. */
934 PyLong_AsLongLong(PyObject
*vv
)
941 PyErr_BadInternalCall();
944 if (!PyLong_Check(vv
)) {
948 return (PY_LONG_LONG
)PyInt_AsLong(vv
);
949 if ((nb
= vv
->ob_type
->tp_as_number
) == NULL
||
950 nb
->nb_int
== NULL
) {
951 PyErr_SetString(PyExc_TypeError
, "an integer is required");
954 io
= (*nb
->nb_int
) (vv
);
957 if (PyInt_Check(io
)) {
958 bytes
= PyInt_AsLong(io
);
962 if (PyLong_Check(io
)) {
963 bytes
= PyLong_AsLongLong(io
);
968 PyErr_SetString(PyExc_TypeError
, "integer conversion failed");
972 res
= _PyLong_AsByteArray(
973 (PyLongObject
*)vv
, (unsigned char *)&bytes
,
974 SIZEOF_LONG_LONG
, IS_LITTLE_ENDIAN
, 1);
976 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
978 return (PY_LONG_LONG
)-1;
983 /* Get a C unsigned PY_LONG_LONG int from a long int object.
984 Return -1 and set an error if overflow occurs. */
986 unsigned PY_LONG_LONG
987 PyLong_AsUnsignedLongLong(PyObject
*vv
)
989 unsigned PY_LONG_LONG bytes
;
993 if (vv
== NULL
|| !PyLong_Check(vv
)) {
994 PyErr_BadInternalCall();
995 return (unsigned PY_LONG_LONG
)-1;
998 res
= _PyLong_AsByteArray(
999 (PyLongObject
*)vv
, (unsigned char *)&bytes
,
1000 SIZEOF_LONG_LONG
, IS_LITTLE_ENDIAN
, 0);
1002 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
1004 return (unsigned PY_LONG_LONG
)res
;
1009 /* Get a C unsigned long int from a long int object, ignoring the high bits.
1010 Returns -1 and sets an error condition if an error occurs. */
1012 unsigned PY_LONG_LONG
1013 PyLong_AsUnsignedLongLongMask(PyObject
*vv
)
1015 register PyLongObject
*v
;
1016 unsigned PY_LONG_LONG x
;
1020 if (vv
== NULL
|| !PyLong_Check(vv
)) {
1021 PyErr_BadInternalCall();
1022 return (unsigned long) -1;
1024 v
= (PyLongObject
*)vv
;
1033 x
= (x
<< SHIFT
) + v
->ob_digit
[i
];
1037 #undef IS_LITTLE_ENDIAN
1039 #endif /* HAVE_LONG_LONG */
1043 convert_binop(PyObject
*v
, PyObject
*w
, PyLongObject
**a
, PyLongObject
**b
) {
1044 if (PyLong_Check(v
)) {
1045 *a
= (PyLongObject
*) v
;
1048 else if (PyInt_Check(v
)) {
1049 *a
= (PyLongObject
*) PyLong_FromLong(PyInt_AS_LONG(v
));
1054 if (PyLong_Check(w
)) {
1055 *b
= (PyLongObject
*) w
;
1058 else if (PyInt_Check(w
)) {
1059 *b
= (PyLongObject
*) PyLong_FromLong(PyInt_AS_LONG(w
));
1068 #define CONVERT_BINOP(v, w, a, b) \
1069 if (!convert_binop(v, w, a, b)) { \
1070 Py_INCREF(Py_NotImplemented); \
1071 return Py_NotImplemented; \
1074 /* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1075 * is modified in place, by adding y to it. Carries are propagated as far as
1076 * x[m-1], and the remaining carry (0 or 1) is returned.
1079 v_iadd(digit
*x
, Py_ssize_t m
, digit
*y
, Py_ssize_t n
)
1085 for (i
= 0; i
< n
; ++i
) {
1086 carry
+= x
[i
] + y
[i
];
1087 x
[i
] = carry
& MASK
;
1089 assert((carry
& 1) == carry
);
1091 for (; carry
&& i
< m
; ++i
) {
1093 x
[i
] = carry
& MASK
;
1095 assert((carry
& 1) == carry
);
1100 /* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1101 * is modified in place, by subtracting y from it. Borrows are propagated as
1102 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1105 v_isub(digit
*x
, Py_ssize_t m
, digit
*y
, Py_ssize_t n
)
1111 for (i
= 0; i
< n
; ++i
) {
1112 borrow
= x
[i
] - y
[i
] - borrow
;
1113 x
[i
] = borrow
& MASK
;
1115 borrow
&= 1; /* keep only 1 sign bit */
1117 for (; borrow
&& i
< m
; ++i
) {
1118 borrow
= x
[i
] - borrow
;
1119 x
[i
] = borrow
& MASK
;
1126 /* Multiply by a single digit, ignoring the sign. */
1128 static PyLongObject
*
1129 mul1(PyLongObject
*a
, wdigit n
)
1131 return muladd1(a
, n
, (digit
)0);
1134 /* Multiply by a single digit and add a single digit, ignoring the sign. */
1136 static PyLongObject
*
1137 muladd1(PyLongObject
*a
, wdigit n
, wdigit extra
)
1139 Py_ssize_t size_a
= ABS(a
->ob_size
);
1140 PyLongObject
*z
= _PyLong_New(size_a
+1);
1141 twodigits carry
= extra
;
1146 for (i
= 0; i
< size_a
; ++i
) {
1147 carry
+= (twodigits
)a
->ob_digit
[i
] * n
;
1148 z
->ob_digit
[i
] = (digit
) (carry
& MASK
);
1151 z
->ob_digit
[i
] = (digit
) carry
;
1152 return long_normalize(z
);
1155 /* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1156 in pout, and returning the remainder. pin and pout point at the LSD.
1157 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
1158 long_format, but that should be done with great care since longs are
1162 inplace_divrem1(digit
*pout
, digit
*pin
, Py_ssize_t size
, digit n
)
1166 assert(n
> 0 && n
<= MASK
);
1169 while (--size
>= 0) {
1171 rem
= (rem
<< SHIFT
) + *--pin
;
1172 *--pout
= hi
= (digit
)(rem
/ n
);
1178 /* Divide a long integer by a digit, returning both the quotient
1179 (as function result) and the remainder (through *prem).
1180 The sign of a is ignored; n should not be zero. */
1182 static PyLongObject
*
1183 divrem1(PyLongObject
*a
, digit n
, digit
*prem
)
1185 const Py_ssize_t size
= ABS(a
->ob_size
);
1188 assert(n
> 0 && n
<= MASK
);
1189 z
= _PyLong_New(size
);
1192 *prem
= inplace_divrem1(z
->ob_digit
, a
->ob_digit
, size
, n
);
1193 return long_normalize(z
);
1196 /* Convert a long int object to a string, using a given conversion base.
1197 Return a string object.
1198 If base is 8 or 16, add the proper prefix '0' or '0x'. */
1201 long_format(PyObject
*aa
, int base
, int addL
)
1203 register PyLongObject
*a
= (PyLongObject
*)aa
;
1204 PyStringObject
*str
;
1206 const Py_ssize_t size_a
= ABS(a
->ob_size
);
1211 if (a
== NULL
|| !PyLong_Check(a
)) {
1212 PyErr_BadInternalCall();
1215 assert(base
>= 2 && base
<= 36);
1217 /* Compute a rough upper bound for the length of the string */
1224 i
= 5 + (addL
? 1 : 0) + (size_a
*SHIFT
+ bits
-1) / bits
;
1225 str
= (PyStringObject
*) PyString_FromStringAndSize((char *)0, i
);
1228 p
= PyString_AS_STRING(str
) + i
;
1235 if (a
->ob_size
== 0) {
1238 else if ((base
& (base
- 1)) == 0) {
1239 /* JRH: special case for power-of-2 bases */
1240 twodigits accum
= 0;
1241 int accumbits
= 0; /* # of bits in accum */
1242 int basebits
= 1; /* # of bits in base-1 */
1244 while ((i
>>= 1) > 1)
1247 for (i
= 0; i
< size_a
; ++i
) {
1248 accum
|= (twodigits
)a
->ob_digit
[i
] << accumbits
;
1250 assert(accumbits
>= basebits
);
1252 char cdigit
= (char)(accum
& (base
- 1));
1253 cdigit
+= (cdigit
< 10) ? '0' : 'a'-10;
1254 assert(p
> PyString_AS_STRING(str
));
1256 accumbits
-= basebits
;
1258 } while (i
< size_a
-1 ? accumbits
>= basebits
:
1263 /* Not 0, and base not a power of 2. Divide repeatedly by
1264 base, but for speed use the highest power of base that
1266 Py_ssize_t size
= size_a
;
1267 digit
*pin
= a
->ob_digit
;
1268 PyLongObject
*scratch
;
1269 /* powbasw <- largest power of base that fits in a digit. */
1270 digit powbase
= base
; /* powbase == base ** power */
1273 unsigned long newpow
= powbase
* (unsigned long)base
;
1274 if (newpow
>> SHIFT
) /* doesn't fit in a digit */
1276 powbase
= (digit
)newpow
;
1280 /* Get a scratch area for repeated division. */
1281 scratch
= _PyLong_New(size
);
1282 if (scratch
== NULL
) {
1287 /* Repeatedly divide by powbase. */
1289 int ntostore
= power
;
1290 digit rem
= inplace_divrem1(scratch
->ob_digit
,
1291 pin
, size
, powbase
);
1292 pin
= scratch
->ob_digit
; /* no need to use a again */
1293 if (pin
[size
- 1] == 0)
1301 /* Break rem into digits. */
1302 assert(ntostore
> 0);
1304 digit nextrem
= (digit
)(rem
/ base
);
1305 char c
= (char)(rem
- nextrem
* base
);
1306 assert(p
> PyString_AS_STRING(str
));
1307 c
+= (c
< 10) ? '0' : 'a'-10;
1311 /* Termination is a bit delicate: must not
1312 store leading zeroes, so must get out if
1313 remaining quotient and rem are both 0. */
1314 } while (ntostore
&& (size
|| rem
));
1315 } while (size
!= 0);
1323 else if (base
== 16) {
1327 else if (base
!= 10) {
1329 *--p
= '0' + base
%10;
1331 *--p
= '0' + base
/10;
1335 if (p
!= PyString_AS_STRING(str
)) {
1336 char *q
= PyString_AS_STRING(str
);
1339 } while ((*q
++ = *p
++) != '\0');
1341 _PyString_Resize((PyObject
**)&str
,
1342 (int) (q
- PyString_AS_STRING(str
)));
1344 return (PyObject
*)str
;
1347 /* Table of digit values for 8-bit string -> integer conversion.
1348 * '0' maps to 0, ..., '9' maps to 9.
1349 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1350 * All other indices map to 37.
1351 * Note that when converting a base B string, a char c is a legitimate
1352 * base B digit iff _PyLong_DigitValue[Py_CHARMASK(c)] < B.
1354 int _PyLong_DigitValue
[256] = {
1355 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1356 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1357 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1358 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1359 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1360 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1361 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1362 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1363 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1364 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1365 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1366 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1367 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1368 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1369 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1370 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1373 /* *str points to the first digit in a string of base `base` digits. base
1374 * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first
1375 * non-digit (which may be *str!). A normalized long is returned.
1376 * The point to this routine is that it takes time linear in the number of
1377 * string characters.
1379 static PyLongObject
*
1380 long_from_binary_base(char **str
, int base
)
1391 assert(base
>= 2 && base
<= 32 && (base
& (base
- 1)) == 0);
1393 for (bits_per_char
= -1; n
; ++bits_per_char
)
1395 /* n <- total # of bits needed, while setting p to end-of-string */
1397 while (_PyLong_DigitValue
[Py_CHARMASK(*p
)] < base
)
1400 n
= (p
- start
) * bits_per_char
;
1401 if (n
/ bits_per_char
!= p
- start
) {
1402 PyErr_SetString(PyExc_ValueError
,
1403 "long string too large to convert");
1406 /* n <- # of Python digits needed, = ceiling(n/SHIFT). */
1407 n
= (n
+ SHIFT
- 1) / SHIFT
;
1411 /* Read string from right, and fill in long from left; i.e.,
1412 * from least to most significant in both.
1416 pdigit
= z
->ob_digit
;
1417 while (--p
>= start
) {
1418 int k
= _PyLong_DigitValue
[Py_CHARMASK(*p
)];
1419 assert(k
>= 0 && k
< base
);
1420 accum
|= (twodigits
)(k
<< bits_in_accum
);
1421 bits_in_accum
+= bits_per_char
;
1422 if (bits_in_accum
>= SHIFT
) {
1423 *pdigit
++ = (digit
)(accum
& MASK
);
1424 assert(pdigit
- z
->ob_digit
<= (int)n
);
1426 bits_in_accum
-= SHIFT
;
1427 assert(bits_in_accum
< SHIFT
);
1430 if (bits_in_accum
) {
1431 assert(bits_in_accum
<= SHIFT
);
1432 *pdigit
++ = (digit
)accum
;
1433 assert(pdigit
- z
->ob_digit
<= (int)n
);
1435 while (pdigit
- z
->ob_digit
< n
)
1437 return long_normalize(z
);
1441 PyLong_FromString(char *str
, char **pend
, int base
)
1444 char *start
, *orig_str
= str
;
1446 PyObject
*strobj
, *strrepr
;
1449 if ((base
!= 0 && base
< 2) || base
> 36) {
1450 PyErr_SetString(PyExc_ValueError
,
1451 "long() arg 2 must be >= 2 and <= 36");
1454 while (*str
!= '\0' && isspace(Py_CHARMASK(*str
)))
1458 else if (*str
== '-') {
1462 while (*str
!= '\0' && isspace(Py_CHARMASK(*str
)))
1467 else if (str
[1] == 'x' || str
[1] == 'X')
1472 if (base
== 16 && str
[0] == '0' && (str
[1] == 'x' || str
[1] == 'X'))
1476 if ((base
& (base
- 1)) == 0)
1477 z
= long_from_binary_base(&str
, base
);
1480 Binary bases can be converted in time linear in the number of digits, because
1481 Python's representation base is binary. Other bases (including decimal!) use
1482 the simple quadratic-time algorithm below, complicated by some speed tricks.
1484 First some math: the largest integer that can be expressed in N base-B digits
1485 is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
1486 case number of Python digits needed to hold it is the smallest integer n s.t.
1488 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
1489 BASE**n >= B**N [taking logs to base BASE]
1490 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
1492 The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
1493 this quickly. A Python long with that much space is reserved near the start,
1494 and the result is computed into it.
1496 The input string is actually treated as being in base base**i (i.e., i digits
1497 are processed at a time), where two more static arrays hold:
1499 convwidth_base[base] = the largest integer i such that base**i <= BASE
1500 convmultmax_base[base] = base ** convwidth_base[base]
1502 The first of these is the largest i such that i consecutive input digits
1503 must fit in a single Python digit. The second is effectively the input
1504 base we're really using.
1506 Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
1507 convmultmax_base[base], the result is "simply"
1509 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
1511 where B = convmultmax_base[base].
1513 Error analysis: as above, the number of Python digits `n` needed is worst-
1516 n >= N * log(B)/log(BASE)
1518 where `N` is the number of input digits in base `B`. This is computed via
1520 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
1522 below. Two numeric concerns are how much space this can waste, and whether
1523 the computed result can be too small. To be concrete, assume BASE = 2**15,
1524 which is the default (and it's unlikely anyone changes that).
1526 Waste isn't a problem: provided the first input digit isn't 0, the difference
1527 between the worst-case input with N digits and the smallest input with N
1528 digits is about a factor of B, but B is small compared to BASE so at most
1529 one allocated Python digit can remain unused on that count. If
1530 N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
1531 and adding 1 returns a result 1 larger than necessary. However, that can't
1532 happen: whenever B is a power of 2, long_from_binary_base() is called
1533 instead, and it's impossible for B**i to be an integer power of 2**15 when
1534 B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
1535 an exact integer when B is not a power of 2, since B**i has a prime factor
1536 other than 2 in that case, but (2**15)**j's only prime factor is 2).
1538 The computed result can be too small if the true value of N*log(B)/log(BASE)
1539 is a little bit larger than an exact integer, but due to roundoff errors (in
1540 computing log(B), log(BASE), their quotient, and/or multiplying that by N)
1541 yields a numeric result a little less than that integer. Unfortunately, "how
1542 close can a transcendental function get to an integer over some range?"
1543 questions are generally theoretically intractable. Computer analysis via
1544 continued fractions is practical: expand log(B)/log(BASE) via continued
1545 fractions, giving a sequence i/j of "the best" rational approximations. Then
1546 j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
1547 we can get very close to being in trouble, but very rarely. For example,
1548 76573 is a denominator in one of the continued-fraction approximations to
1549 log(10)/log(2**15), and indeed:
1551 >>> log(10)/log(2**15)*76573
1554 is very close to an integer. If we were working with IEEE single-precision,
1555 rounding errors could kill us. Finding worst cases in IEEE double-precision
1556 requires better-than-double-precision log() functions, and Tim didn't bother.
1557 Instead the code checks to see whether the allocated space is enough as each
1558 new Python digit is added, and copies the whole thing to a larger long if not.
1559 This should happen extremely rarely, and in fact I don't have a test case
1560 that triggers it(!). Instead the code was tested by artificially allocating
1561 just 1 digit at the start, so that the copying code was exercised for every
1562 digit beyond the first.
1564 register twodigits c
; /* current input character */
1568 twodigits convmultmax
, convmult
;
1572 static double log_base_BASE
[37] = {0.0e0
,};
1573 static int convwidth_base
[37] = {0,};
1574 static twodigits convmultmax_base
[37] = {0,};
1576 if (log_base_BASE
[base
] == 0.0) {
1577 twodigits convmax
= base
;
1580 log_base_BASE
[base
] = log((double)base
) /
1583 twodigits next
= convmax
* base
;
1589 convmultmax_base
[base
] = convmax
;
1591 convwidth_base
[base
] = i
;
1594 /* Find length of the string of numeric characters. */
1596 while (_PyLong_DigitValue
[Py_CHARMASK(*scan
)] < base
)
1599 /* Create a long object that can contain the largest possible
1600 * integer with this base and length. Note that there's no
1601 * need to initialize z->ob_digit -- no slot is read up before
1602 * being stored into.
1604 size_z
= (Py_ssize_t
)((scan
- str
) * log_base_BASE
[base
]) + 1;
1605 /* Uncomment next line to test exceedingly rare copy code */
1608 z
= _PyLong_New(size_z
);
1613 /* `convwidth` consecutive input digits are treated as a single
1614 * digit in base `convmultmax`.
1616 convwidth
= convwidth_base
[base
];
1617 convmultmax
= convmultmax_base
[base
];
1620 while (str
< scan
) {
1621 /* grab up to convwidth digits from the input string */
1622 c
= (digit
)_PyLong_DigitValue
[Py_CHARMASK(*str
++)];
1623 for (i
= 1; i
< convwidth
&& str
!= scan
; ++i
, ++str
) {
1624 c
= (twodigits
)(c
* base
+
1625 _PyLong_DigitValue
[Py_CHARMASK(*str
)]);
1629 convmult
= convmultmax
;
1630 /* Calculate the shift only if we couldn't get
1633 if (i
!= convwidth
) {
1639 /* Multiply z by convmult, and add c. */
1641 pzstop
= pz
+ z
->ob_size
;
1642 for (; pz
< pzstop
; ++pz
) {
1643 c
+= (twodigits
)*pz
* convmult
;
1644 *pz
= (digit
)(c
& MASK
);
1647 /* carry off the current end? */
1650 if (z
->ob_size
< size_z
) {
1656 /* Extremely rare. Get more space. */
1657 assert(z
->ob_size
== size_z
);
1658 tmp
= _PyLong_New(size_z
+ 1);
1663 memcpy(tmp
->ob_digit
,
1665 sizeof(digit
) * size_z
);
1668 z
->ob_digit
[size_z
] = (digit
)c
;
1679 z
->ob_size
= -(z
->ob_size
);
1680 if (*str
== 'L' || *str
== 'l')
1682 while (*str
&& isspace(Py_CHARMASK(*str
)))
1688 return (PyObject
*) z
;
1692 slen
= strlen(orig_str
) < 200 ? strlen(orig_str
) : 200;
1693 strobj
= PyString_FromStringAndSize(orig_str
, slen
);
1696 strrepr
= PyObject_Repr(strobj
);
1698 if (strrepr
== NULL
)
1700 PyErr_Format(PyExc_ValueError
,
1701 "invalid literal for long() with base %d: %s",
1702 base
, PyString_AS_STRING(strrepr
));
1707 #ifdef Py_USING_UNICODE
1709 PyLong_FromUnicode(Py_UNICODE
*u
, Py_ssize_t length
, int base
)
1712 char *buffer
= (char *)PyMem_MALLOC(length
+1);
1717 if (PyUnicode_EncodeDecimal(u
, length
, buffer
, NULL
)) {
1721 result
= PyLong_FromString(buffer
, NULL
, base
);
1728 static PyLongObject
*x_divrem
1729 (PyLongObject
*, PyLongObject
*, PyLongObject
**);
1730 static PyObject
*long_pos(PyLongObject
*);
1731 static int long_divrem(PyLongObject
*, PyLongObject
*,
1732 PyLongObject
**, PyLongObject
**);
1734 /* Long division with remainder, top-level routine */
1737 long_divrem(PyLongObject
*a
, PyLongObject
*b
,
1738 PyLongObject
**pdiv
, PyLongObject
**prem
)
1740 Py_ssize_t size_a
= ABS(a
->ob_size
), size_b
= ABS(b
->ob_size
);
1744 PyErr_SetString(PyExc_ZeroDivisionError
,
1745 "long division or modulo by zero");
1748 if (size_a
< size_b
||
1749 (size_a
== size_b
&&
1750 a
->ob_digit
[size_a
-1] < b
->ob_digit
[size_b
-1])) {
1752 *pdiv
= _PyLong_New(0);
1754 *prem
= (PyLongObject
*) a
;
1759 z
= divrem1(a
, b
->ob_digit
[0], &rem
);
1762 *prem
= (PyLongObject
*) PyLong_FromLong((long)rem
);
1765 z
= x_divrem(a
, b
, prem
);
1770 The quotient z has the sign of a*b;
1771 the remainder r has the sign of a,
1773 if ((a
->ob_size
< 0) != (b
->ob_size
< 0))
1774 z
->ob_size
= -(z
->ob_size
);
1775 if (a
->ob_size
< 0 && (*prem
)->ob_size
!= 0)
1776 (*prem
)->ob_size
= -((*prem
)->ob_size
);
1781 /* Unsigned long division with remainder -- the algorithm */
1783 static PyLongObject
*
1784 x_divrem(PyLongObject
*v1
, PyLongObject
*w1
, PyLongObject
**prem
)
1786 Py_ssize_t size_v
= ABS(v1
->ob_size
), size_w
= ABS(w1
->ob_size
);
1787 digit d
= (digit
) ((twodigits
)BASE
/ (w1
->ob_digit
[size_w
-1] + 1));
1788 PyLongObject
*v
= mul1(v1
, d
);
1789 PyLongObject
*w
= mul1(w1
, d
);
1793 if (v
== NULL
|| w
== NULL
) {
1799 assert(size_v
>= size_w
&& size_w
> 1); /* Assert checks by div() */
1800 assert(v
->ob_refcnt
== 1); /* Since v will be used as accumulator! */
1801 assert(size_w
== ABS(w
->ob_size
)); /* That's how d was calculated */
1803 size_v
= ABS(v
->ob_size
);
1804 k
= size_v
- size_w
;
1805 a
= _PyLong_New(k
+ 1);
1807 for (j
= size_v
; a
!= NULL
&& k
>= 0; --j
, --k
) {
1808 digit vj
= (j
>= size_v
) ? 0 : v
->ob_digit
[j
];
1810 stwodigits carry
= 0;
1818 if (vj
== w
->ob_digit
[size_w
-1])
1821 q
= (((twodigits
)vj
<< SHIFT
) + v
->ob_digit
[j
-1]) /
1822 w
->ob_digit
[size_w
-1];
1824 while (w
->ob_digit
[size_w
-2]*q
>
1826 ((twodigits
)vj
<< SHIFT
)
1828 - q
*w
->ob_digit
[size_w
-1]
1833 for (i
= 0; i
< size_w
&& i
+k
< size_v
; ++i
) {
1834 twodigits z
= w
->ob_digit
[i
] * q
;
1835 digit zz
= (digit
) (z
>> SHIFT
);
1836 carry
+= v
->ob_digit
[i
+k
] - z
1837 + ((twodigits
)zz
<< SHIFT
);
1838 v
->ob_digit
[i
+k
] = (digit
)(carry
& MASK
);
1839 carry
= Py_ARITHMETIC_RIGHT_SHIFT(BASE_TWODIGITS_TYPE
,
1845 carry
+= v
->ob_digit
[i
+k
];
1846 v
->ob_digit
[i
+k
] = 0;
1850 a
->ob_digit
[k
] = (digit
) q
;
1852 assert(carry
== -1);
1853 a
->ob_digit
[k
] = (digit
) q
-1;
1855 for (i
= 0; i
< size_w
&& i
+k
< size_v
; ++i
) {
1856 carry
+= v
->ob_digit
[i
+k
] + w
->ob_digit
[i
];
1857 v
->ob_digit
[i
+k
] = (digit
)(carry
& MASK
);
1858 carry
= Py_ARITHMETIC_RIGHT_SHIFT(
1859 BASE_TWODIGITS_TYPE
,
1868 a
= long_normalize(a
);
1869 *prem
= divrem1(v
, d
, &d
);
1870 /* d receives the (unused) remainder */
1871 if (*prem
== NULL
) {
1884 long_dealloc(PyObject
*v
)
1886 v
->ob_type
->tp_free(v
);
1890 long_repr(PyObject
*v
)
1892 return long_format(v
, 10, 1);
1896 long_str(PyObject
*v
)
1898 return long_format(v
, 10, 0);
1902 long_compare(PyLongObject
*a
, PyLongObject
*b
)
1906 if (a
->ob_size
!= b
->ob_size
) {
1907 if (ABS(a
->ob_size
) == 0 && ABS(b
->ob_size
) == 0)
1910 sign
= a
->ob_size
- b
->ob_size
;
1913 Py_ssize_t i
= ABS(a
->ob_size
);
1914 while (--i
>= 0 && a
->ob_digit
[i
] == b
->ob_digit
[i
])
1919 sign
= (int)a
->ob_digit
[i
] - (int)b
->ob_digit
[i
];
1924 return sign
< 0 ? -1 : sign
> 0 ? 1 : 0;
1928 long_hash(PyLongObject
*v
)
1934 /* This is designed so that Python ints and longs with the
1935 same value hash to the same value, otherwise comparisons
1936 of mapping keys will turn out weird */
1944 #define LONG_BIT_SHIFT (8*sizeof(long) - SHIFT)
1946 /* Force a native long #-bits (32 or 64) circular shift */
1947 x
= ((x
<< SHIFT
) & ~MASK
) | ((x
>> LONG_BIT_SHIFT
) & MASK
);
1948 x
+= v
->ob_digit
[i
];
1950 #undef LONG_BIT_SHIFT
1958 /* Add the absolute values of two long integers. */
1960 static PyLongObject
*
1961 x_add(PyLongObject
*a
, PyLongObject
*b
)
1963 Py_ssize_t size_a
= ABS(a
->ob_size
), size_b
= ABS(b
->ob_size
);
1968 /* Ensure a is the larger of the two: */
1969 if (size_a
< size_b
) {
1970 { PyLongObject
*temp
= a
; a
= b
; b
= temp
; }
1971 { Py_ssize_t size_temp
= size_a
;
1973 size_b
= size_temp
; }
1975 z
= _PyLong_New(size_a
+1);
1978 for (i
= 0; i
< size_b
; ++i
) {
1979 carry
+= a
->ob_digit
[i
] + b
->ob_digit
[i
];
1980 z
->ob_digit
[i
] = carry
& MASK
;
1983 for (; i
< size_a
; ++i
) {
1984 carry
+= a
->ob_digit
[i
];
1985 z
->ob_digit
[i
] = carry
& MASK
;
1988 z
->ob_digit
[i
] = carry
;
1989 return long_normalize(z
);
1992 /* Subtract the absolute values of two integers. */
1994 static PyLongObject
*
1995 x_sub(PyLongObject
*a
, PyLongObject
*b
)
1997 Py_ssize_t size_a
= ABS(a
->ob_size
), size_b
= ABS(b
->ob_size
);
2003 /* Ensure a is the larger of the two: */
2004 if (size_a
< size_b
) {
2006 { PyLongObject
*temp
= a
; a
= b
; b
= temp
; }
2007 { Py_ssize_t size_temp
= size_a
;
2009 size_b
= size_temp
; }
2011 else if (size_a
== size_b
) {
2012 /* Find highest digit where a and b differ: */
2014 while (--i
>= 0 && a
->ob_digit
[i
] == b
->ob_digit
[i
])
2017 return _PyLong_New(0);
2018 if (a
->ob_digit
[i
] < b
->ob_digit
[i
]) {
2020 { PyLongObject
*temp
= a
; a
= b
; b
= temp
; }
2022 size_a
= size_b
= i
+1;
2024 z
= _PyLong_New(size_a
);
2027 for (i
= 0; i
< size_b
; ++i
) {
2028 /* The following assumes unsigned arithmetic
2029 works module 2**N for some N>SHIFT. */
2030 borrow
= a
->ob_digit
[i
] - b
->ob_digit
[i
] - borrow
;
2031 z
->ob_digit
[i
] = borrow
& MASK
;
2033 borrow
&= 1; /* Keep only one sign bit */
2035 for (; i
< size_a
; ++i
) {
2036 borrow
= a
->ob_digit
[i
] - borrow
;
2037 z
->ob_digit
[i
] = borrow
& MASK
;
2039 borrow
&= 1; /* Keep only one sign bit */
2041 assert(borrow
== 0);
2043 z
->ob_size
= -(z
->ob_size
);
2044 return long_normalize(z
);
2048 long_add(PyLongObject
*v
, PyLongObject
*w
)
2050 PyLongObject
*a
, *b
, *z
;
2052 CONVERT_BINOP((PyObject
*)v
, (PyObject
*)w
, &a
, &b
);
2054 if (a
->ob_size
< 0) {
2055 if (b
->ob_size
< 0) {
2057 if (z
!= NULL
&& z
->ob_size
!= 0)
2058 z
->ob_size
= -(z
->ob_size
);
2071 return (PyObject
*)z
;
2075 long_sub(PyLongObject
*v
, PyLongObject
*w
)
2077 PyLongObject
*a
, *b
, *z
;
2079 CONVERT_BINOP((PyObject
*)v
, (PyObject
*)w
, &a
, &b
);
2081 if (a
->ob_size
< 0) {
2086 if (z
!= NULL
&& z
->ob_size
!= 0)
2087 z
->ob_size
= -(z
->ob_size
);
2097 return (PyObject
*)z
;
2100 /* Grade school multiplication, ignoring the signs.
2101 * Returns the absolute value of the product, or NULL if error.
2103 static PyLongObject
*
2104 x_mul(PyLongObject
*a
, PyLongObject
*b
)
2107 Py_ssize_t size_a
= ABS(a
->ob_size
);
2108 Py_ssize_t size_b
= ABS(b
->ob_size
);
2111 z
= _PyLong_New(size_a
+ size_b
);
2115 memset(z
->ob_digit
, 0, z
->ob_size
* sizeof(digit
));
2117 /* Efficient squaring per HAC, Algorithm 14.16:
2118 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
2119 * Gives slightly less than a 2x speedup when a == b,
2120 * via exploiting that each entry in the multiplication
2121 * pyramid appears twice (except for the size_a squares).
2123 for (i
= 0; i
< size_a
; ++i
) {
2125 twodigits f
= a
->ob_digit
[i
];
2126 digit
*pz
= z
->ob_digit
+ (i
<< 1);
2127 digit
*pa
= a
->ob_digit
+ i
+ 1;
2128 digit
*paend
= a
->ob_digit
+ size_a
;
2135 carry
= *pz
+ f
* f
;
2136 *pz
++ = (digit
)(carry
& MASK
);
2138 assert(carry
<= MASK
);
2140 /* Now f is added in twice in each column of the
2141 * pyramid it appears. Same as adding f<<1 once.
2144 while (pa
< paend
) {
2145 carry
+= *pz
+ *pa
++ * f
;
2146 *pz
++ = (digit
)(carry
& MASK
);
2148 assert(carry
<= (MASK
<< 1));
2152 *pz
++ = (digit
)(carry
& MASK
);
2156 *pz
+= (digit
)(carry
& MASK
);
2157 assert((carry
>> SHIFT
) == 0);
2160 else { /* a is not the same as b -- gradeschool long mult */
2161 for (i
= 0; i
< size_a
; ++i
) {
2162 twodigits carry
= 0;
2163 twodigits f
= a
->ob_digit
[i
];
2164 digit
*pz
= z
->ob_digit
+ i
;
2165 digit
*pb
= b
->ob_digit
;
2166 digit
*pbend
= b
->ob_digit
+ size_b
;
2173 while (pb
< pbend
) {
2174 carry
+= *pz
+ *pb
++ * f
;
2175 *pz
++ = (digit
)(carry
& MASK
);
2177 assert(carry
<= MASK
);
2180 *pz
+= (digit
)(carry
& MASK
);
2181 assert((carry
>> SHIFT
) == 0);
2184 return long_normalize(z
);
2187 /* A helper for Karatsuba multiplication (k_mul).
2188 Takes a long "n" and an integer "size" representing the place to
2189 split, and sets low and high such that abs(n) == (high << size) + low,
2190 viewing the shift as being by digits. The sign bit is ignored, and
2191 the return values are >= 0.
2192 Returns 0 on success, -1 on failure.
2195 kmul_split(PyLongObject
*n
, Py_ssize_t size
, PyLongObject
**high
, PyLongObject
**low
)
2197 PyLongObject
*hi
, *lo
;
2198 Py_ssize_t size_lo
, size_hi
;
2199 const Py_ssize_t size_n
= ABS(n
->ob_size
);
2201 size_lo
= MIN(size_n
, size
);
2202 size_hi
= size_n
- size_lo
;
2204 if ((hi
= _PyLong_New(size_hi
)) == NULL
)
2206 if ((lo
= _PyLong_New(size_lo
)) == NULL
) {
2211 memcpy(lo
->ob_digit
, n
->ob_digit
, size_lo
* sizeof(digit
));
2212 memcpy(hi
->ob_digit
, n
->ob_digit
+ size_lo
, size_hi
* sizeof(digit
));
2214 *high
= long_normalize(hi
);
2215 *low
= long_normalize(lo
);
2219 static PyLongObject
*k_lopsided_mul(PyLongObject
*a
, PyLongObject
*b
);
2221 /* Karatsuba multiplication. Ignores the input signs, and returns the
2222 * absolute value of the product (or NULL if error).
2223 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
2225 static PyLongObject
*
2226 k_mul(PyLongObject
*a
, PyLongObject
*b
)
2228 Py_ssize_t asize
= ABS(a
->ob_size
);
2229 Py_ssize_t bsize
= ABS(b
->ob_size
);
2230 PyLongObject
*ah
= NULL
;
2231 PyLongObject
*al
= NULL
;
2232 PyLongObject
*bh
= NULL
;
2233 PyLongObject
*bl
= NULL
;
2234 PyLongObject
*ret
= NULL
;
2235 PyLongObject
*t1
, *t2
, *t3
;
2236 Py_ssize_t shift
; /* the number of digits we split off */
2239 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
2240 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
2241 * Then the original product is
2242 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
2243 * By picking X to be a power of 2, "*X" is just shifting, and it's
2244 * been reduced to 3 multiplies on numbers half the size.
2247 /* We want to split based on the larger number; fiddle so that b
2250 if (asize
> bsize
) {
2260 /* Use gradeschool math when either number is too small. */
2261 i
= a
== b
? KARATSUBA_SQUARE_CUTOFF
: KARATSUBA_CUTOFF
;
2264 return _PyLong_New(0);
2269 /* If a is small compared to b, splitting on b gives a degenerate
2270 * case with ah==0, and Karatsuba may be (even much) less efficient
2271 * than "grade school" then. However, we can still win, by viewing
2272 * b as a string of "big digits", each of width a->ob_size. That
2273 * leads to a sequence of balanced calls to k_mul.
2275 if (2 * asize
<= bsize
)
2276 return k_lopsided_mul(a
, b
);
2278 /* Split a & b into hi & lo pieces. */
2280 if (kmul_split(a
, shift
, &ah
, &al
) < 0) goto fail
;
2281 assert(ah
->ob_size
> 0); /* the split isn't degenerate */
2289 else if (kmul_split(b
, shift
, &bh
, &bl
) < 0) goto fail
;
2292 * 1. Allocate result space (asize + bsize digits: that's always
2294 * 2. Compute ah*bh, and copy into result at 2*shift.
2295 * 3. Compute al*bl, and copy into result at 0. Note that this
2296 * can't overlap with #2.
2297 * 4. Subtract al*bl from the result, starting at shift. This may
2298 * underflow (borrow out of the high digit), but we don't care:
2299 * we're effectively doing unsigned arithmetic mod
2300 * BASE**(sizea + sizeb), and so long as the *final* result fits,
2301 * borrows and carries out of the high digit can be ignored.
2302 * 5. Subtract ah*bh from the result, starting at shift.
2303 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
2307 /* 1. Allocate result space. */
2308 ret
= _PyLong_New(asize
+ bsize
);
2309 if (ret
== NULL
) goto fail
;
2311 /* Fill with trash, to catch reference to uninitialized digits. */
2312 memset(ret
->ob_digit
, 0xDF, ret
->ob_size
* sizeof(digit
));
2315 /* 2. t1 <- ah*bh, and copy into high digits of result. */
2316 if ((t1
= k_mul(ah
, bh
)) == NULL
) goto fail
;
2317 assert(t1
->ob_size
>= 0);
2318 assert(2*shift
+ t1
->ob_size
<= ret
->ob_size
);
2319 memcpy(ret
->ob_digit
+ 2*shift
, t1
->ob_digit
,
2320 t1
->ob_size
* sizeof(digit
));
2322 /* Zero-out the digits higher than the ah*bh copy. */
2323 i
= ret
->ob_size
- 2*shift
- t1
->ob_size
;
2325 memset(ret
->ob_digit
+ 2*shift
+ t1
->ob_size
, 0,
2328 /* 3. t2 <- al*bl, and copy into the low digits. */
2329 if ((t2
= k_mul(al
, bl
)) == NULL
) {
2333 assert(t2
->ob_size
>= 0);
2334 assert(t2
->ob_size
<= 2*shift
); /* no overlap with high digits */
2335 memcpy(ret
->ob_digit
, t2
->ob_digit
, t2
->ob_size
* sizeof(digit
));
2337 /* Zero out remaining digits. */
2338 i
= 2*shift
- t2
->ob_size
; /* number of uninitialized digits */
2340 memset(ret
->ob_digit
+ t2
->ob_size
, 0, i
* sizeof(digit
));
2342 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
2343 * because it's fresher in cache.
2345 i
= ret
->ob_size
- shift
; /* # digits after shift */
2346 (void)v_isub(ret
->ob_digit
+ shift
, i
, t2
->ob_digit
, t2
->ob_size
);
2349 (void)v_isub(ret
->ob_digit
+ shift
, i
, t1
->ob_digit
, t1
->ob_size
);
2352 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
2353 if ((t1
= x_add(ah
, al
)) == NULL
) goto fail
;
2362 else if ((t2
= x_add(bh
, bl
)) == NULL
) {
2373 if (t3
== NULL
) goto fail
;
2374 assert(t3
->ob_size
>= 0);
2376 /* Add t3. It's not obvious why we can't run out of room here.
2377 * See the (*) comment after this function.
2379 (void)v_iadd(ret
->ob_digit
+ shift
, i
, t3
->ob_digit
, t3
->ob_size
);
2382 return long_normalize(ret
);
2393 /* (*) Why adding t3 can't "run out of room" above.
2395 Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
2398 1. For any integer i, i = c(i/2) + f(i/2). In particular,
2399 bsize = c(bsize/2) + f(bsize/2).
2400 2. shift = f(bsize/2)
2402 4. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
2403 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
2405 We allocated asize + bsize result digits, and add t3 into them at an offset
2406 of shift. This leaves asize+bsize-shift allocated digit positions for t3
2407 to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
2408 asize + c(bsize/2) available digit positions.
2410 bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
2411 at most c(bsize/2) digits + 1 bit.
2413 If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
2414 digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
2415 most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
2417 The product (ah+al)*(bh+bl) therefore has at most
2419 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
2421 and we have asize + c(bsize/2) available digit positions. We need to show
2422 this is always enough. An instance of c(bsize/2) cancels out in both, so
2423 the question reduces to whether asize digits is enough to hold
2424 (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
2425 then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
2426 asize is at least f(bsize/2)+1 digits, so this in turn reduces to whether 1
2427 digit is enough to hold 2 bits. This is so since SHIFT=15 >= 2. If
2428 asize == bsize, then we're asking whether bsize digits is enough to hold
2429 c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
2430 is enough to hold 2 bits. This is so if bsize >= 2, which holds because
2431 bsize >= KARATSUBA_CUTOFF >= 2.
2433 Note that since there's always enough room for (ah+al)*(bh+bl), and that's
2434 clearly >= each of ah*bh and al*bl, there's always enough room to subtract
2435 ah*bh and al*bl too.
2438 /* b has at least twice the digits of a, and a is big enough that Karatsuba
2439 * would pay off *if* the inputs had balanced sizes. View b as a sequence
2440 * of slices, each with a->ob_size digits, and multiply the slices by a,
2441 * one at a time. This gives k_mul balanced inputs to work with, and is
2442 * also cache-friendly (we compute one double-width slice of the result
2443 * at a time, then move on, never bactracking except for the helpful
2444 * single-width slice overlap between successive partial sums).
2446 static PyLongObject
*
2447 k_lopsided_mul(PyLongObject
*a
, PyLongObject
*b
)
2449 const Py_ssize_t asize
= ABS(a
->ob_size
);
2450 Py_ssize_t bsize
= ABS(b
->ob_size
);
2451 Py_ssize_t nbdone
; /* # of b digits already multiplied */
2453 PyLongObject
*bslice
= NULL
;
2455 assert(asize
> KARATSUBA_CUTOFF
);
2456 assert(2 * asize
<= bsize
);
2458 /* Allocate result space, and zero it out. */
2459 ret
= _PyLong_New(asize
+ bsize
);
2462 memset(ret
->ob_digit
, 0, ret
->ob_size
* sizeof(digit
));
2464 /* Successive slices of b are copied into bslice. */
2465 bslice
= _PyLong_New(asize
);
2471 PyLongObject
*product
;
2472 const Py_ssize_t nbtouse
= MIN(bsize
, asize
);
2474 /* Multiply the next slice of b by a. */
2475 memcpy(bslice
->ob_digit
, b
->ob_digit
+ nbdone
,
2476 nbtouse
* sizeof(digit
));
2477 bslice
->ob_size
= nbtouse
;
2478 product
= k_mul(a
, bslice
);
2479 if (product
== NULL
)
2482 /* Add into result. */
2483 (void)v_iadd(ret
->ob_digit
+ nbdone
, ret
->ob_size
- nbdone
,
2484 product
->ob_digit
, product
->ob_size
);
2492 return long_normalize(ret
);
2501 long_mul(PyLongObject
*v
, PyLongObject
*w
)
2503 PyLongObject
*a
, *b
, *z
;
2505 if (!convert_binop((PyObject
*)v
, (PyObject
*)w
, &a
, &b
)) {
2506 Py_INCREF(Py_NotImplemented
);
2507 return Py_NotImplemented
;
2511 /* Negate if exactly one of the inputs is negative. */
2512 if (((a
->ob_size
^ b
->ob_size
) < 0) && z
)
2513 z
->ob_size
= -(z
->ob_size
);
2516 return (PyObject
*)z
;
2519 /* The / and % operators are now defined in terms of divmod().
2520 The expression a mod b has the value a - b*floor(a/b).
2521 The long_divrem function gives the remainder after division of
2522 |a| by |b|, with the sign of a. This is also expressed
2523 as a - b*trunc(a/b), if trunc truncates towards zero.
2530 So, to get from rem to mod, we have to add b if a and b
2531 have different signs. We then subtract one from the 'div'
2532 part of the outcome to keep the invariant intact. */
2535 * *pdiv, *pmod = divmod(v, w)
2536 * NULL can be passed for pdiv or pmod, in which case that part of
2537 * the result is simply thrown away. The caller owns a reference to
2538 * each of these it requests (does not pass NULL for).
2541 l_divmod(PyLongObject
*v
, PyLongObject
*w
,
2542 PyLongObject
**pdiv
, PyLongObject
**pmod
)
2544 PyLongObject
*div
, *mod
;
2546 if (long_divrem(v
, w
, &div
, &mod
) < 0)
2548 if ((mod
->ob_size
< 0 && w
->ob_size
> 0) ||
2549 (mod
->ob_size
> 0 && w
->ob_size
< 0)) {
2552 temp
= (PyLongObject
*) long_add(mod
, w
);
2559 one
= (PyLongObject
*) PyLong_FromLong(1L);
2561 (temp
= (PyLongObject
*) long_sub(div
, one
)) == NULL
) {
2585 long_div(PyObject
*v
, PyObject
*w
)
2587 PyLongObject
*a
, *b
, *div
;
2589 CONVERT_BINOP(v
, w
, &a
, &b
);
2590 if (l_divmod(a
, b
, &div
, NULL
) < 0)
2594 return (PyObject
*)div
;
2598 long_classic_div(PyObject
*v
, PyObject
*w
)
2600 PyLongObject
*a
, *b
, *div
;
2602 CONVERT_BINOP(v
, w
, &a
, &b
);
2603 if (Py_DivisionWarningFlag
&&
2604 PyErr_Warn(PyExc_DeprecationWarning
, "classic long division") < 0)
2606 else if (l_divmod(a
, b
, &div
, NULL
) < 0)
2610 return (PyObject
*)div
;
2614 long_true_divide(PyObject
*v
, PyObject
*w
)
2616 PyLongObject
*a
, *b
;
2618 int failed
, aexp
= -1, bexp
= -1;
2620 CONVERT_BINOP(v
, w
, &a
, &b
);
2621 ad
= _PyLong_AsScaledDouble((PyObject
*)a
, &aexp
);
2622 bd
= _PyLong_AsScaledDouble((PyObject
*)b
, &bexp
);
2623 failed
= (ad
== -1.0 || bd
== -1.0) && PyErr_Occurred();
2628 /* 'aexp' and 'bexp' were initialized to -1 to silence gcc-4.0.x,
2629 but should really be set correctly after sucessful calls to
2630 _PyLong_AsScaledDouble() */
2631 assert(aexp
>= 0 && bexp
>= 0);
2634 PyErr_SetString(PyExc_ZeroDivisionError
,
2635 "long division or modulo by zero");
2639 /* True value is very close to ad/bd * 2**(SHIFT*(aexp-bexp)) */
2640 ad
/= bd
; /* overflow/underflow impossible here */
2642 if (aexp
> INT_MAX
/ SHIFT
)
2644 else if (aexp
< -(INT_MAX
/ SHIFT
))
2645 return PyFloat_FromDouble(0.0); /* underflow to 0 */
2647 ad
= ldexp(ad
, aexp
* SHIFT
);
2648 if (Py_OVERFLOWED(ad
)) /* ignore underflow to 0.0 */
2650 return PyFloat_FromDouble(ad
);
2653 PyErr_SetString(PyExc_OverflowError
,
2654 "long/long too large for a float");
2660 long_mod(PyObject
*v
, PyObject
*w
)
2662 PyLongObject
*a
, *b
, *mod
;
2664 CONVERT_BINOP(v
, w
, &a
, &b
);
2666 if (l_divmod(a
, b
, NULL
, &mod
) < 0)
2670 return (PyObject
*)mod
;
2674 long_divmod(PyObject
*v
, PyObject
*w
)
2676 PyLongObject
*a
, *b
, *div
, *mod
;
2679 CONVERT_BINOP(v
, w
, &a
, &b
);
2681 if (l_divmod(a
, b
, &div
, &mod
) < 0) {
2688 PyTuple_SetItem(z
, 0, (PyObject
*) div
);
2689 PyTuple_SetItem(z
, 1, (PyObject
*) mod
);
2702 long_pow(PyObject
*v
, PyObject
*w
, PyObject
*x
)
2704 PyLongObject
*a
, *b
, *c
; /* a,b,c = v,w,x */
2705 int negativeOutput
= 0; /* if x<0 return negative output */
2707 PyLongObject
*z
= NULL
; /* accumulated result */
2708 Py_ssize_t i
, j
, k
; /* counters */
2709 PyLongObject
*temp
= NULL
;
2711 /* 5-ary values. If the exponent is large enough, table is
2712 * precomputed so that table[i] == a**i % c for i in range(32).
2714 PyLongObject
*table
[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
2715 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
2717 /* a, b, c = v, w, x */
2718 CONVERT_BINOP(v
, w
, &a
, &b
);
2719 if (PyLong_Check(x
)) {
2720 c
= (PyLongObject
*)x
;
2723 else if (PyInt_Check(x
)) {
2724 c
= (PyLongObject
*)PyLong_FromLong(PyInt_AS_LONG(x
));
2728 else if (x
== Py_None
)
2733 Py_INCREF(Py_NotImplemented
);
2734 return Py_NotImplemented
;
2737 if (b
->ob_size
< 0) { /* if exponent is negative */
2739 PyErr_SetString(PyExc_TypeError
, "pow() 2nd argument "
2740 "cannot be negative when 3rd argument specified");
2744 /* else return a float. This works because we know
2745 that this calls float_pow() which converts its
2746 arguments to double. */
2749 return PyFloat_Type
.tp_as_number
->nb_power(v
, w
, x
);
2755 raise ValueError() */
2756 if (c
->ob_size
== 0) {
2757 PyErr_SetString(PyExc_ValueError
,
2758 "pow() 3rd argument cannot be 0");
2763 negativeOutput = True
2764 modulus = -modulus */
2765 if (c
->ob_size
< 0) {
2767 temp
= (PyLongObject
*)_PyLong_Copy(c
);
2773 c
->ob_size
= - c
->ob_size
;
2778 if ((c
->ob_size
== 1) && (c
->ob_digit
[0] == 1)) {
2779 z
= (PyLongObject
*)PyLong_FromLong(0L);
2784 base = base % modulus
2785 Having the base positive just makes things easier. */
2786 if (a
->ob_size
< 0) {
2787 if (l_divmod(a
, c
, NULL
, &temp
) < 0)
2795 /* At this point a, b, and c are guaranteed non-negative UNLESS
2796 c is NULL, in which case a may be negative. */
2798 z
= (PyLongObject
*)PyLong_FromLong(1L);
2802 /* Perform a modular reduction, X = X % c, but leave X alone if c
2807 if (l_divmod(X, c, NULL, &temp) < 0) \
2814 /* Multiply two values, then reduce the result:
2815 result = X*Y % c. If c is NULL, skip the mod. */
2816 #define MULT(X, Y, result) \
2818 temp = (PyLongObject *)long_mul(X, Y); \
2821 Py_XDECREF(result); \
2827 if (b
->ob_size
<= FIVEARY_CUTOFF
) {
2828 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
2829 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
2830 for (i
= b
->ob_size
- 1; i
>= 0; --i
) {
2831 digit bi
= b
->ob_digit
[i
];
2833 for (j
= 1 << (SHIFT
-1); j
!= 0; j
>>= 1) {
2841 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
2842 Py_INCREF(z
); /* still holds 1L */
2844 for (i
= 1; i
< 32; ++i
)
2845 MULT(table
[i
-1], a
, table
[i
])
2847 for (i
= b
->ob_size
- 1; i
>= 0; --i
) {
2848 const digit bi
= b
->ob_digit
[i
];
2850 for (j
= SHIFT
- 5; j
>= 0; j
-= 5) {
2851 const int index
= (bi
>> j
) & 0x1f;
2852 for (k
= 0; k
< 5; ++k
)
2855 MULT(z
, table
[index
], z
)
2860 if (negativeOutput
&& (z
->ob_size
!= 0)) {
2861 temp
= (PyLongObject
*)long_sub(z
, c
);
2877 if (b
->ob_size
> FIVEARY_CUTOFF
) {
2878 for (i
= 0; i
< 32; ++i
)
2879 Py_XDECREF(table
[i
]);
2885 return (PyObject
*)z
;
2889 long_invert(PyLongObject
*v
)
2891 /* Implement ~x as -(x+1) */
2894 w
= (PyLongObject
*)PyLong_FromLong(1L);
2897 x
= (PyLongObject
*) long_add(v
, w
);
2901 x
->ob_size
= -(x
->ob_size
);
2902 return (PyObject
*)x
;
2906 long_pos(PyLongObject
*v
)
2908 if (PyLong_CheckExact(v
)) {
2910 return (PyObject
*)v
;
2913 return _PyLong_Copy(v
);
2917 long_neg(PyLongObject
*v
)
2920 if (v
->ob_size
== 0 && PyLong_CheckExact(v
)) {
2923 return (PyObject
*) v
;
2925 z
= (PyLongObject
*)_PyLong_Copy(v
);
2927 z
->ob_size
= -(v
->ob_size
);
2928 return (PyObject
*)z
;
2932 long_abs(PyLongObject
*v
)
2941 long_nonzero(PyLongObject
*v
)
2943 return ABS(v
->ob_size
) != 0;
2947 long_rshift(PyLongObject
*v
, PyLongObject
*w
)
2949 PyLongObject
*a
, *b
;
2950 PyLongObject
*z
= NULL
;
2952 Py_ssize_t newsize
, wordshift
, loshift
, hishift
, i
, j
;
2953 digit lomask
, himask
;
2955 CONVERT_BINOP((PyObject
*)v
, (PyObject
*)w
, &a
, &b
);
2957 if (a
->ob_size
< 0) {
2958 /* Right shifting negative numbers is harder */
2959 PyLongObject
*a1
, *a2
;
2960 a1
= (PyLongObject
*) long_invert(a
);
2963 a2
= (PyLongObject
*) long_rshift(a1
, b
);
2967 z
= (PyLongObject
*) long_invert(a2
);
2972 shiftby
= PyLong_AsLong((PyObject
*)b
);
2973 if (shiftby
== -1L && PyErr_Occurred())
2976 PyErr_SetString(PyExc_ValueError
,
2977 "negative shift count");
2980 wordshift
= shiftby
/ SHIFT
;
2981 newsize
= ABS(a
->ob_size
) - wordshift
;
2986 return (PyObject
*)z
;
2988 loshift
= shiftby
% SHIFT
;
2989 hishift
= SHIFT
- loshift
;
2990 lomask
= ((digit
)1 << hishift
) - 1;
2991 himask
= MASK
^ lomask
;
2992 z
= _PyLong_New(newsize
);
2996 z
->ob_size
= -(z
->ob_size
);
2997 for (i
= 0, j
= wordshift
; i
< newsize
; i
++, j
++) {
2998 z
->ob_digit
[i
] = (a
->ob_digit
[j
] >> loshift
) & lomask
;
3001 (a
->ob_digit
[j
+1] << hishift
) & himask
;
3003 z
= long_normalize(z
);
3008 return (PyObject
*) z
;
3013 long_lshift(PyObject
*v
, PyObject
*w
)
3015 /* This version due to Tim Peters */
3016 PyLongObject
*a
, *b
;
3017 PyLongObject
*z
= NULL
;
3019 Py_ssize_t oldsize
, newsize
, wordshift
, remshift
, i
, j
;
3022 CONVERT_BINOP(v
, w
, &a
, &b
);
3024 shiftby
= PyLong_AsLong((PyObject
*)b
);
3025 if (shiftby
== -1L && PyErr_Occurred())
3028 PyErr_SetString(PyExc_ValueError
, "negative shift count");
3031 if ((long)(int)shiftby
!= shiftby
) {
3032 PyErr_SetString(PyExc_ValueError
,
3033 "outrageous left shift count");
3036 /* wordshift, remshift = divmod(shiftby, SHIFT) */
3037 wordshift
= (int)shiftby
/ SHIFT
;
3038 remshift
= (int)shiftby
- wordshift
* SHIFT
;
3040 oldsize
= ABS(a
->ob_size
);
3041 newsize
= oldsize
+ wordshift
;
3044 z
= _PyLong_New(newsize
);
3048 z
->ob_size
= -(z
->ob_size
);
3049 for (i
= 0; i
< wordshift
; i
++)
3052 for (i
= wordshift
, j
= 0; j
< oldsize
; i
++, j
++) {
3053 accum
|= (twodigits
)a
->ob_digit
[j
] << remshift
;
3054 z
->ob_digit
[i
] = (digit
)(accum
& MASK
);
3058 z
->ob_digit
[newsize
-1] = (digit
)accum
;
3061 z
= long_normalize(z
);
3065 return (PyObject
*) z
;
3069 /* Bitwise and/xor/or operations */
3072 long_bitwise(PyLongObject
*a
,
3073 int op
, /* '&', '|', '^' */
3076 digit maska
, maskb
; /* 0 or MASK */
3078 Py_ssize_t size_a
, size_b
, size_z
;
3084 if (a
->ob_size
< 0) {
3085 a
= (PyLongObject
*) long_invert(a
);
3094 if (b
->ob_size
< 0) {
3095 b
= (PyLongObject
*) long_invert(b
);
3110 if (maska
!= maskb
) {
3116 if (maska
&& maskb
) {
3124 if (maska
|| maskb
) {
3133 /* JRH: The original logic here was to allocate the result value (z)
3134 as the longer of the two operands. However, there are some cases
3135 where the result is guaranteed to be shorter than that: AND of two
3136 positives, OR of two negatives: use the shorter number. AND with
3137 mixed signs: use the positive number. OR with mixed signs: use the
3138 negative number. After the transformations above, op will be '&'
3139 iff one of these cases applies, and mask will be non-0 for operands
3140 whose length should be ignored.
3143 size_a
= a
->ob_size
;
3144 size_b
= b
->ob_size
;
3148 : (maskb
? size_a
: MIN(size_a
, size_b
)))
3149 : MAX(size_a
, size_b
);
3150 z
= _PyLong_New(size_z
);
3158 for (i
= 0; i
< size_z
; ++i
) {
3159 diga
= (i
< size_a
? a
->ob_digit
[i
] : 0) ^ maska
;
3160 digb
= (i
< size_b
? b
->ob_digit
[i
] : 0) ^ maskb
;
3162 case '&': z
->ob_digit
[i
] = diga
& digb
; break;
3163 case '|': z
->ob_digit
[i
] = diga
| digb
; break;
3164 case '^': z
->ob_digit
[i
] = diga
^ digb
; break;
3170 z
= long_normalize(z
);
3172 return (PyObject
*) z
;
3179 long_and(PyObject
*v
, PyObject
*w
)
3181 PyLongObject
*a
, *b
;
3183 CONVERT_BINOP(v
, w
, &a
, &b
);
3184 c
= long_bitwise(a
, '&', b
);
3191 long_xor(PyObject
*v
, PyObject
*w
)
3193 PyLongObject
*a
, *b
;
3195 CONVERT_BINOP(v
, w
, &a
, &b
);
3196 c
= long_bitwise(a
, '^', b
);
3203 long_or(PyObject
*v
, PyObject
*w
)
3205 PyLongObject
*a
, *b
;
3207 CONVERT_BINOP(v
, w
, &a
, &b
);
3208 c
= long_bitwise(a
, '|', b
);
3215 long_coerce(PyObject
**pv
, PyObject
**pw
)
3217 if (PyInt_Check(*pw
)) {
3218 *pw
= PyLong_FromLong(PyInt_AS_LONG(*pw
));
3222 else if (PyLong_Check(*pw
)) {
3227 return 1; /* Can't do it */
3231 long_long(PyObject
*v
)
3233 if (PyLong_CheckExact(v
))
3236 v
= _PyLong_Copy((PyLongObject
*)v
);
3241 long_int(PyObject
*v
)
3244 x
= PyLong_AsLong(v
);
3245 if (PyErr_Occurred()) {
3246 if (PyErr_ExceptionMatches(PyExc_OverflowError
)) {
3248 if (PyLong_CheckExact(v
)) {
3253 return _PyLong_Copy((PyLongObject
*)v
);
3258 return PyInt_FromLong(x
);
3262 long_float(PyObject
*v
)
3265 result
= PyLong_AsDouble(v
);
3266 if (result
== -1.0 && PyErr_Occurred())
3268 return PyFloat_FromDouble(result
);
3272 long_oct(PyObject
*v
)
3274 return long_format(v
, 8, 1);
3278 long_hex(PyObject
*v
)
3280 return long_format(v
, 16, 1);
3284 long_subtype_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
);
3287 long_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
3290 int base
= -909; /* unlikely! */
3291 static char *kwlist
[] = {"x", "base", 0};
3293 if (type
!= &PyLong_Type
)
3294 return long_subtype_new(type
, args
, kwds
); /* Wimp out */
3295 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "|Oi:long", kwlist
,
3299 return PyLong_FromLong(0L);
3301 return PyNumber_Long(x
);
3302 else if (PyString_Check(x
))
3303 return PyLong_FromString(PyString_AS_STRING(x
), NULL
, base
);
3304 #ifdef Py_USING_UNICODE
3305 else if (PyUnicode_Check(x
))
3306 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x
),
3307 PyUnicode_GET_SIZE(x
),
3311 PyErr_SetString(PyExc_TypeError
,
3312 "long() can't convert non-string with explicit base");
3317 /* Wimpy, slow approach to tp_new calls for subtypes of long:
3318 first create a regular long from whatever arguments we got,
3319 then allocate a subtype instance and initialize it from
3320 the regular long. The regular long is then thrown away.
3323 long_subtype_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
3325 PyLongObject
*tmp
, *newobj
;
3328 assert(PyType_IsSubtype(type
, &PyLong_Type
));
3329 tmp
= (PyLongObject
*)long_new(&PyLong_Type
, args
, kwds
);
3332 assert(PyLong_CheckExact(tmp
));
3336 newobj
= (PyLongObject
*)type
->tp_alloc(type
, n
);
3337 if (newobj
== NULL
) {
3341 assert(PyLong_Check(newobj
));
3342 newobj
->ob_size
= tmp
->ob_size
;
3343 for (i
= 0; i
< n
; i
++)
3344 newobj
->ob_digit
[i
] = tmp
->ob_digit
[i
];
3346 return (PyObject
*)newobj
;
3350 long_getnewargs(PyLongObject
*v
)
3352 return Py_BuildValue("(N)", _PyLong_Copy(v
));
3355 static PyMethodDef long_methods
[] = {
3356 {"__getnewargs__", (PyCFunction
)long_getnewargs
, METH_NOARGS
},
3357 {NULL
, NULL
} /* sentinel */
3360 PyDoc_STRVAR(long_doc
,
3361 "long(x[, base]) -> integer\n\
3363 Convert a string or number to a long integer, if possible. A floating\n\
3364 point argument will be truncated towards zero (this does not include a\n\
3365 string representation of a floating point number!) When converting a\n\
3366 string, use the optional base. It is an error to supply a base when\n\
3367 converting a non-string.");
3369 static PyNumberMethods long_as_number
= {
3370 (binaryfunc
) long_add
, /*nb_add*/
3371 (binaryfunc
) long_sub
, /*nb_subtract*/
3372 (binaryfunc
) long_mul
, /*nb_multiply*/
3373 long_classic_div
, /*nb_divide*/
3374 long_mod
, /*nb_remainder*/
3375 long_divmod
, /*nb_divmod*/
3376 long_pow
, /*nb_power*/
3377 (unaryfunc
) long_neg
, /*nb_negative*/
3378 (unaryfunc
) long_pos
, /*tp_positive*/
3379 (unaryfunc
) long_abs
, /*tp_absolute*/
3380 (inquiry
) long_nonzero
, /*tp_nonzero*/
3381 (unaryfunc
) long_invert
, /*nb_invert*/
3382 long_lshift
, /*nb_lshift*/
3383 (binaryfunc
) long_rshift
, /*nb_rshift*/
3384 long_and
, /*nb_and*/
3385 long_xor
, /*nb_xor*/
3387 long_coerce
, /*nb_coerce*/
3388 long_int
, /*nb_int*/
3389 long_long
, /*nb_long*/
3390 long_float
, /*nb_float*/
3391 long_oct
, /*nb_oct*/
3392 long_hex
, /*nb_hex*/
3393 0, /* nb_inplace_add */
3394 0, /* nb_inplace_subtract */
3395 0, /* nb_inplace_multiply */
3396 0, /* nb_inplace_divide */
3397 0, /* nb_inplace_remainder */
3398 0, /* nb_inplace_power */
3399 0, /* nb_inplace_lshift */
3400 0, /* nb_inplace_rshift */
3401 0, /* nb_inplace_and */
3402 0, /* nb_inplace_xor */
3403 0, /* nb_inplace_or */
3404 long_div
, /* nb_floor_divide */
3405 long_true_divide
, /* nb_true_divide */
3406 0, /* nb_inplace_floor_divide */
3407 0, /* nb_inplace_true_divide */
3408 long_index
, /* nb_index */
3411 PyTypeObject PyLong_Type
= {
3412 PyObject_HEAD_INIT(&PyType_Type
)
3414 "long", /* tp_name */
3415 sizeof(PyLongObject
) - sizeof(digit
), /* tp_basicsize */
3416 sizeof(digit
), /* tp_itemsize */
3417 long_dealloc
, /* tp_dealloc */
3421 (cmpfunc
)long_compare
, /* tp_compare */
3422 long_repr
, /* tp_repr */
3423 &long_as_number
, /* tp_as_number */
3424 0, /* tp_as_sequence */
3425 0, /* tp_as_mapping */
3426 (hashfunc
)long_hash
, /* tp_hash */
3428 long_str
, /* tp_str */
3429 PyObject_GenericGetAttr
, /* tp_getattro */
3430 0, /* tp_setattro */
3431 0, /* tp_as_buffer */
3432 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_CHECKTYPES
|
3433 Py_TPFLAGS_BASETYPE
, /* tp_flags */
3434 long_doc
, /* tp_doc */
3435 0, /* tp_traverse */
3437 0, /* tp_richcompare */
3438 0, /* tp_weaklistoffset */
3440 0, /* tp_iternext */
3441 long_methods
, /* tp_methods */
3446 0, /* tp_descr_get */
3447 0, /* tp_descr_set */
3448 0, /* tp_dictoffset */
3451 long_new
, /* tp_new */
3452 PyObject_Del
, /* tp_free */