2 /* Long (arbitrary precision) integer object implementation */
4 /* XXX The functional organization of this file is terrible */
7 #include "longintrepr.h"
11 /* For long multiplication, use the O(N**2) school algorithm unless
12 * both operands contain more than KARATSUBA_CUTOFF digits (this
13 * being an internal Python long digit, in base BASE).
15 #define KARATSUBA_CUTOFF 35
17 #define ABS(x) ((x) < 0 ? -(x) : (x))
21 #define MAX(x, y) ((x) < (y) ? (y) : (x))
22 #define MIN(x, y) ((x) > (y) ? (y) : (x))
25 static PyLongObject
*long_normalize(PyLongObject
*);
26 static PyLongObject
*mul1(PyLongObject
*, wdigit
);
27 static PyLongObject
*muladd1(PyLongObject
*, wdigit
, wdigit
);
28 static PyLongObject
*divrem1(PyLongObject
*, digit
, digit
*);
29 static PyObject
*long_format(PyObject
*aa
, int base
, int addL
);
31 #define SIGCHECK(PyTryBlock) \
32 if (--_Py_Ticker < 0) { \
33 _Py_Ticker = _Py_CheckInterval; \
34 if (PyErr_CheckSignals()) { PyTryBlock; } \
37 /* Normalize (remove leading zeros from) a long int object.
38 Doesn't attempt to free the storage--in most cases, due to the nature
39 of the algorithms used, this could save at most be one word anyway. */
42 long_normalize(register PyLongObject
*v
)
44 int j
= ABS(v
->ob_size
);
47 while (i
> 0 && v
->ob_digit
[i
-1] == 0)
50 v
->ob_size
= (v
->ob_size
< 0) ? -(i
) : i
;
54 /* Allocate a new long int object with size digits.
55 Return NULL and set exception if we run out of memory. */
60 return PyObject_NEW_VAR(PyLongObject
, &PyLong_Type
, size
);
64 _PyLong_Copy(PyLongObject
*src
)
73 result
= _PyLong_New(i
);
75 result
->ob_size
= src
->ob_size
;
77 result
->ob_digit
[i
] = src
->ob_digit
[i
];
79 return (PyObject
*)result
;
82 /* Create a new long int object from a C long int */
85 PyLong_FromLong(long ival
)
88 unsigned long t
; /* unsigned so >> doesn't propagate sign bit */
97 /* Count the number of Python digits.
98 We used to pick 5 ("big enough for anything"), but that's a
99 waste of time and space given that 5*15 = 75 bits are rarely
101 t
= (unsigned long)ival
;
106 v
= _PyLong_New(ndigits
);
108 digit
*p
= v
->ob_digit
;
109 v
->ob_size
= negative
? -ndigits
: ndigits
;
110 t
= (unsigned long)ival
;
112 *p
++ = (digit
)(t
& MASK
);
116 return (PyObject
*)v
;
119 /* Create a new long int object from a C unsigned long int */
122 PyLong_FromUnsignedLong(unsigned long ival
)
128 /* Count the number of Python digits. */
129 t
= (unsigned long)ival
;
134 v
= _PyLong_New(ndigits
);
136 digit
*p
= v
->ob_digit
;
137 v
->ob_size
= ndigits
;
139 *p
++ = (digit
)(ival
& MASK
);
143 return (PyObject
*)v
;
146 /* Create a new long int object from a C double */
149 PyLong_FromDouble(double dval
)
153 int i
, ndig
, expo
, neg
;
155 if (Py_IS_INFINITY(dval
)) {
156 PyErr_SetString(PyExc_OverflowError
,
157 "cannot convert float infinity to long");
164 frac
= frexp(dval
, &expo
); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
166 return PyLong_FromLong(0L);
167 ndig
= (expo
-1) / SHIFT
+ 1; /* Number of 'digits' in result */
168 v
= _PyLong_New(ndig
);
171 frac
= ldexp(frac
, (expo
-1) % SHIFT
+ 1);
172 for (i
= ndig
; --i
>= 0; ) {
173 long bits
= (long)frac
;
174 v
->ob_digit
[i
] = (digit
) bits
;
175 frac
= frac
- (double)bits
;
176 frac
= ldexp(frac
, SHIFT
);
179 v
->ob_size
= -(v
->ob_size
);
180 return (PyObject
*)v
;
183 /* Get a C long int from a long int object.
184 Returns -1 and sets an error condition if overflow occurs. */
187 PyLong_AsLong(PyObject
*vv
)
189 /* This version by Tim Peters */
190 register PyLongObject
*v
;
191 unsigned long x
, prev
;
194 if (vv
== NULL
|| !PyLong_Check(vv
)) {
195 if (vv
!= NULL
&& PyInt_Check(vv
))
196 return PyInt_AsLong(vv
);
197 PyErr_BadInternalCall();
200 v
= (PyLongObject
*)vv
;
210 x
= (x
<< SHIFT
) + v
->ob_digit
[i
];
211 if ((x
>> SHIFT
) != prev
)
214 /* Haven't lost any bits, but if the sign bit is set we're in
215 * trouble *unless* this is the min negative number. So,
216 * trouble iff sign bit set && (positive || some bit set other
217 * than the sign bit).
219 if ((long)x
< 0 && (sign
> 0 || (x
<< 1) != 0))
221 return (long)x
* sign
;
224 PyErr_SetString(PyExc_OverflowError
,
225 "long int too large to convert to int");
229 /* Get a C unsigned long int from a long int object.
230 Returns -1 and sets an error condition if overflow occurs. */
233 PyLong_AsUnsignedLong(PyObject
*vv
)
235 register PyLongObject
*v
;
236 unsigned long x
, prev
;
239 if (vv
== NULL
|| !PyLong_Check(vv
)) {
240 PyErr_BadInternalCall();
241 return (unsigned long) -1;
243 v
= (PyLongObject
*)vv
;
247 PyErr_SetString(PyExc_OverflowError
,
248 "can't convert negative value to unsigned long");
249 return (unsigned long) -1;
253 x
= (x
<< SHIFT
) + v
->ob_digit
[i
];
254 if ((x
>> SHIFT
) != prev
) {
255 PyErr_SetString(PyExc_OverflowError
,
256 "long int too large to convert");
257 return (unsigned long) -1;
264 _PyLong_FromByteArray(const unsigned char* bytes
, size_t n
,
265 int little_endian
, int is_signed
)
267 const unsigned char* pstartbyte
;/* LSB of bytes */
268 int incr
; /* direction to move pstartbyte */
269 const unsigned char* pendbyte
; /* MSB of bytes */
270 size_t numsignificantbytes
; /* number of bytes that matter */
271 size_t ndigits
; /* number of Python long digits */
272 PyLongObject
* v
; /* result */
273 int idigit
= 0; /* next free index in v->ob_digit */
276 return PyLong_FromLong(0L);
280 pendbyte
= bytes
+ n
- 1;
284 pstartbyte
= bytes
+ n
- 1;
290 is_signed
= *pendbyte
>= 0x80;
292 /* Compute numsignificantbytes. This consists of finding the most
293 significant byte. Leading 0 bytes are insignficant if the number
294 is positive, and leading 0xff bytes if negative. */
297 const unsigned char* p
= pendbyte
;
298 const int pincr
= -incr
; /* search MSB to LSB */
299 const unsigned char insignficant
= is_signed
? 0xff : 0x00;
301 for (i
= 0; i
< n
; ++i
, p
+= pincr
) {
302 if (*p
!= insignficant
)
305 numsignificantbytes
= n
- i
;
306 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
307 actually has 2 significant bytes. OTOH, 0xff0001 ==
308 -0x00ffff, so we wouldn't *need* to bump it there; but we
309 do for 0xffff = -0x0001. To be safe without bothering to
310 check every case, bump it regardless. */
311 if (is_signed
&& numsignificantbytes
< n
)
312 ++numsignificantbytes
;
315 /* How many Python long digits do we need? We have
316 8*numsignificantbytes bits, and each Python long digit has SHIFT
317 bits, so it's the ceiling of the quotient. */
318 ndigits
= (numsignificantbytes
* 8 + SHIFT
- 1) / SHIFT
;
319 if (ndigits
> (size_t)INT_MAX
)
320 return PyErr_NoMemory();
321 v
= _PyLong_New((int)ndigits
);
325 /* Copy the bits over. The tricky parts are computing 2's-comp on
326 the fly for signed numbers, and dealing with the mismatch between
327 8-bit bytes and (probably) 15-bit Python digits.*/
330 twodigits carry
= 1; /* for 2's-comp calculation */
331 twodigits accum
= 0; /* sliding register */
332 unsigned int accumbits
= 0; /* number of bits in accum */
333 const unsigned char* p
= pstartbyte
;
335 for (i
= 0; i
< numsignificantbytes
; ++i
, p
+= incr
) {
336 twodigits thisbyte
= *p
;
337 /* Compute correction for 2's comp, if needed. */
339 thisbyte
= (0xff ^ thisbyte
) + carry
;
340 carry
= thisbyte
>> 8;
343 /* Because we're going LSB to MSB, thisbyte is
344 more significant than what's already in accum,
345 so needs to be prepended to accum. */
346 accum
|= thisbyte
<< accumbits
;
348 if (accumbits
>= SHIFT
) {
349 /* There's enough to fill a Python digit. */
350 assert(idigit
< (int)ndigits
);
351 v
->ob_digit
[idigit
] = (digit
)(accum
& MASK
);
355 assert(accumbits
< SHIFT
);
358 assert(accumbits
< SHIFT
);
360 assert(idigit
< (int)ndigits
);
361 v
->ob_digit
[idigit
] = (digit
)accum
;
366 v
->ob_size
= is_signed
? -idigit
: idigit
;
367 return (PyObject
*)long_normalize(v
);
371 _PyLong_AsByteArray(PyLongObject
* v
,
372 unsigned char* bytes
, size_t n
,
373 int little_endian
, int is_signed
)
375 int i
; /* index into v->ob_digit */
376 int ndigits
; /* |v->ob_size| */
377 twodigits accum
; /* sliding register */
378 unsigned int accumbits
; /* # bits in accum */
379 int do_twos_comp
; /* store 2's-comp? is_signed and v < 0 */
380 twodigits carry
; /* for computing 2's-comp */
381 size_t j
; /* # bytes filled */
382 unsigned char* p
; /* pointer to next byte in bytes */
383 int pincr
; /* direction to move p */
385 assert(v
!= NULL
&& PyLong_Check(v
));
387 if (v
->ob_size
< 0) {
388 ndigits
= -(v
->ob_size
);
390 PyErr_SetString(PyExc_TypeError
,
391 "can't convert negative long to unsigned");
397 ndigits
= v
->ob_size
;
410 /* Copy over all the Python digits.
411 It's crucial that every Python digit except for the MSD contribute
412 exactly SHIFT bits to the total, so first assert that the long is
414 assert(ndigits
== 0 || v
->ob_digit
[ndigits
- 1] != 0);
418 carry
= do_twos_comp
? 1 : 0;
419 for (i
= 0; i
< ndigits
; ++i
) {
420 twodigits thisdigit
= v
->ob_digit
[i
];
422 thisdigit
= (thisdigit
^ MASK
) + carry
;
423 carry
= thisdigit
>> SHIFT
;
426 /* Because we're going LSB to MSB, thisdigit is more
427 significant than what's already in accum, so needs to be
428 prepended to accum. */
429 accum
|= thisdigit
<< accumbits
;
432 /* The most-significant digit may be (probably is) at least
434 if (i
== ndigits
- 1) {
435 /* Count # of sign bits -- they needn't be stored,
436 * although for signed conversion we need later to
437 * make sure at least one sign bit gets stored.
438 * First shift conceptual sign bit to real sign bit.
440 stwodigits s
= (stwodigits
)(thisdigit
<<
441 (8*sizeof(stwodigits
) - SHIFT
));
442 unsigned int nsignbits
= 0;
443 while ((s
< 0) == do_twos_comp
&& nsignbits
< SHIFT
) {
447 accumbits
-= nsignbits
;
450 /* Store as many bytes as possible. */
451 while (accumbits
>= 8) {
455 *p
= (unsigned char)(accum
& 0xff);
462 /* Store the straggler (if any). */
463 assert(accumbits
< 8);
464 assert(carry
== 0); /* else do_twos_comp and *every* digit was 0 */
470 /* Fill leading bits of the byte with sign bits
471 (appropriately pretending that the long had an
472 infinite supply of sign bits). */
473 accum
|= (~(twodigits
)0) << accumbits
;
475 *p
= (unsigned char)(accum
& 0xff);
478 else if (j
== n
&& n
> 0 && is_signed
) {
479 /* The main loop filled the byte array exactly, so the code
480 just above didn't get to ensure there's a sign bit, and the
481 loop below wouldn't add one either. Make sure a sign bit
483 unsigned char msb
= *(p
- pincr
);
484 int sign_bit_set
= msb
>= 0x80;
485 assert(accumbits
== 0);
486 if (sign_bit_set
== do_twos_comp
)
492 /* Fill remaining bytes with copies of the sign bit. */
494 unsigned char signbyte
= do_twos_comp
? 0xffU
: 0U;
495 for ( ; j
< n
; ++j
, p
+= pincr
)
502 PyErr_SetString(PyExc_OverflowError
, "long too big to convert");
508 _PyLong_AsScaledDouble(PyObject
*vv
, int *exponent
)
510 /* NBITS_WANTED should be > the number of bits in a double's precision,
511 but small enough so that 2**NBITS_WANTED is within the normal double
512 range. nbitsneeded is set to 1 less than that because the most-significant
513 Python digit contains at least 1 significant bit, but we don't want to
514 bother counting them (catering to the worst case cheaply).
516 57 is one more than VAX-D double precision; I (Tim) don't know of a double
517 format with more precision than that; it's 1 larger so that we add in at
518 least one round bit to stand in for the ignored least-significant bits.
520 #define NBITS_WANTED 57
523 const double multiplier
= (double)(1L << SHIFT
);
527 if (vv
== NULL
|| !PyLong_Check(vv
)) {
528 PyErr_BadInternalCall();
531 v
= (PyLongObject
*)vv
;
543 x
= (double)v
->ob_digit
[i
];
544 nbitsneeded
= NBITS_WANTED
- 1;
545 /* Invariant: i Python digits remain unaccounted for. */
546 while (i
> 0 && nbitsneeded
> 0) {
548 x
= x
* multiplier
+ (double)v
->ob_digit
[i
];
549 nbitsneeded
-= SHIFT
;
551 /* There are i digits we didn't shift in. Pretending they're all
552 zeroes, the true value is x * 2**(i*SHIFT). */
559 /* Get a C double from a long int object. */
562 PyLong_AsDouble(PyObject
*vv
)
567 if (vv
== NULL
|| !PyLong_Check(vv
)) {
568 PyErr_BadInternalCall();
571 x
= _PyLong_AsScaledDouble(vv
, &e
);
572 if (x
== -1.0 && PyErr_Occurred())
574 if (e
> INT_MAX
/ SHIFT
)
577 x
= ldexp(x
, e
* SHIFT
);
578 if (Py_OVERFLOWED(x
))
583 PyErr_SetString(PyExc_OverflowError
,
584 "long int too large to convert to float");
588 /* Create a new long (or int) object from a C pointer */
591 PyLong_FromVoidPtr(void *p
)
593 #if SIZEOF_VOID_P <= SIZEOF_LONG
594 return PyInt_FromLong((long)p
);
597 #ifndef HAVE_LONG_LONG
598 # error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
600 #if SIZEOF_LONG_LONG < SIZEOF_VOID_P
601 # error "PyLong_FromVoidPtr: sizeof(LONG_LONG) < sizeof(void*)"
603 /* optimize null pointers */
605 return PyInt_FromLong(0);
606 return PyLong_FromLongLong((LONG_LONG
)p
);
608 #endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
611 /* Get a C pointer from a long object (or an int object in some cases) */
614 PyLong_AsVoidPtr(PyObject
*vv
)
616 /* This function will allow int or long objects. If vv is neither,
617 then the PyLong_AsLong*() functions will raise the exception:
618 PyExc_SystemError, "bad argument to internal function"
620 #if SIZEOF_VOID_P <= SIZEOF_LONG
624 x
= PyInt_AS_LONG(vv
);
626 x
= PyLong_AsLong(vv
);
629 #ifndef HAVE_LONG_LONG
630 # error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
632 #if SIZEOF_LONG_LONG < SIZEOF_VOID_P
633 # error "PyLong_AsVoidPtr: sizeof(LONG_LONG) < sizeof(void*)"
638 x
= PyInt_AS_LONG(vv
);
640 x
= PyLong_AsLongLong(vv
);
642 #endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
644 if (x
== -1 && PyErr_Occurred())
649 #ifdef HAVE_LONG_LONG
651 /* Initial LONG_LONG support by Chris Herborth (chrish@qnx.com), later
652 * rewritten to use the newer PyLong_{As,From}ByteArray API.
655 #define IS_LITTLE_ENDIAN (int)*(unsigned char*)&one
657 /* Create a new long int object from a C LONG_LONG int. */
660 PyLong_FromLongLong(LONG_LONG ival
)
662 LONG_LONG bytes
= ival
;
664 return _PyLong_FromByteArray(
665 (unsigned char *)&bytes
,
666 SIZEOF_LONG_LONG
, IS_LITTLE_ENDIAN
, 1);
669 /* Create a new long int object from a C unsigned LONG_LONG int. */
672 PyLong_FromUnsignedLongLong(unsigned LONG_LONG ival
)
674 unsigned LONG_LONG bytes
= ival
;
676 return _PyLong_FromByteArray(
677 (unsigned char *)&bytes
,
678 SIZEOF_LONG_LONG
, IS_LITTLE_ENDIAN
, 0);
681 /* Get a C LONG_LONG int from a long int object.
682 Return -1 and set an error if overflow occurs. */
685 PyLong_AsLongLong(PyObject
*vv
)
692 PyErr_BadInternalCall();
695 if (!PyLong_Check(vv
)) {
697 return (LONG_LONG
)PyInt_AsLong(vv
);
698 PyErr_BadInternalCall();
702 res
= _PyLong_AsByteArray(
703 (PyLongObject
*)vv
, (unsigned char *)&bytes
,
704 SIZEOF_LONG_LONG
, IS_LITTLE_ENDIAN
, 1);
706 /* Plan 9 can't handle LONG_LONG in ? : expressions */
708 return (LONG_LONG
)-1;
713 /* Get a C unsigned LONG_LONG int from a long int object.
714 Return -1 and set an error if overflow occurs. */
717 PyLong_AsUnsignedLongLong(PyObject
*vv
)
719 unsigned LONG_LONG bytes
;
723 if (vv
== NULL
|| !PyLong_Check(vv
)) {
724 PyErr_BadInternalCall();
728 res
= _PyLong_AsByteArray(
729 (PyLongObject
*)vv
, (unsigned char *)&bytes
,
730 SIZEOF_LONG_LONG
, IS_LITTLE_ENDIAN
, 0);
732 /* Plan 9 can't handle LONG_LONG in ? : expressions */
734 return (unsigned LONG_LONG
)res
;
739 #undef IS_LITTLE_ENDIAN
741 #endif /* HAVE_LONG_LONG */
745 convert_binop(PyObject
*v
, PyObject
*w
, PyLongObject
**a
, PyLongObject
**b
) {
746 if (PyLong_Check(v
)) {
747 *a
= (PyLongObject
*) v
;
750 else if (PyInt_Check(v
)) {
751 *a
= (PyLongObject
*) PyLong_FromLong(PyInt_AS_LONG(v
));
756 if (PyLong_Check(w
)) {
757 *b
= (PyLongObject
*) w
;
760 else if (PyInt_Check(w
)) {
761 *b
= (PyLongObject
*) PyLong_FromLong(PyInt_AS_LONG(w
));
770 #define CONVERT_BINOP(v, w, a, b) \
771 if (!convert_binop(v, w, a, b)) { \
772 Py_INCREF(Py_NotImplemented); \
773 return Py_NotImplemented; \
776 /* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
777 * is modified in place, by adding y to it. Carries are propagated as far as
778 * x[m-1], and the remaining carry (0 or 1) is returned.
781 v_iadd(digit
*x
, int m
, digit
*y
, int n
)
787 for (i
= 0; i
< n
; ++i
) {
788 carry
+= x
[i
] + y
[i
];
791 assert((carry
& 1) == carry
);
793 for (; carry
&& i
< m
; ++i
) {
797 assert((carry
& 1) == carry
);
802 /* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
803 * is modified in place, by subtracting y from it. Borrows are propagated as
804 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
807 v_isub(digit
*x
, int m
, digit
*y
, int n
)
813 for (i
= 0; i
< n
; ++i
) {
814 borrow
= x
[i
] - y
[i
] - borrow
;
815 x
[i
] = borrow
& MASK
;
817 borrow
&= 1; /* keep only 1 sign bit */
819 for (; borrow
&& i
< m
; ++i
) {
820 borrow
= x
[i
] - borrow
;
821 x
[i
] = borrow
& MASK
;
828 /* Multiply by a single digit, ignoring the sign. */
830 static PyLongObject
*
831 mul1(PyLongObject
*a
, wdigit n
)
833 return muladd1(a
, n
, (digit
)0);
836 /* Multiply by a single digit and add a single digit, ignoring the sign. */
838 static PyLongObject
*
839 muladd1(PyLongObject
*a
, wdigit n
, wdigit extra
)
841 int size_a
= ABS(a
->ob_size
);
842 PyLongObject
*z
= _PyLong_New(size_a
+1);
843 twodigits carry
= extra
;
848 for (i
= 0; i
< size_a
; ++i
) {
849 carry
+= (twodigits
)a
->ob_digit
[i
] * n
;
850 z
->ob_digit
[i
] = (digit
) (carry
& MASK
);
853 z
->ob_digit
[i
] = (digit
) carry
;
854 return long_normalize(z
);
857 /* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
858 in pout, and returning the remainder. pin and pout point at the LSD.
859 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
860 long_format, but that should be done with great care since longs are
864 inplace_divrem1(digit
*pout
, digit
*pin
, int size
, digit n
)
868 assert(n
> 0 && n
<= MASK
);
871 while (--size
>= 0) {
873 rem
= (rem
<< SHIFT
) + *--pin
;
874 *--pout
= hi
= (digit
)(rem
/ n
);
880 /* Divide a long integer by a digit, returning both the quotient
881 (as function result) and the remainder (through *prem).
882 The sign of a is ignored; n should not be zero. */
884 static PyLongObject
*
885 divrem1(PyLongObject
*a
, digit n
, digit
*prem
)
887 const int size
= ABS(a
->ob_size
);
890 assert(n
> 0 && n
<= MASK
);
891 z
= _PyLong_New(size
);
894 *prem
= inplace_divrem1(z
->ob_digit
, a
->ob_digit
, size
, n
);
895 return long_normalize(z
);
898 /* Convert a long int object to a string, using a given conversion base.
899 Return a string object.
900 If base is 8 or 16, add the proper prefix '0' or '0x'. */
903 long_format(PyObject
*aa
, int base
, int addL
)
905 register PyLongObject
*a
= (PyLongObject
*)aa
;
908 const int size_a
= ABS(a
->ob_size
);
913 if (a
== NULL
|| !PyLong_Check(a
)) {
914 PyErr_BadInternalCall();
917 assert(base
>= 2 && base
<= 36);
919 /* Compute a rough upper bound for the length of the string */
926 i
= 5 + (addL
? 1 : 0) + (size_a
*SHIFT
+ bits
-1) / bits
;
927 str
= (PyStringObject
*) PyString_FromStringAndSize((char *)0, i
);
930 p
= PyString_AS_STRING(str
) + i
;
937 if (a
->ob_size
== 0) {
940 else if ((base
& (base
- 1)) == 0) {
941 /* JRH: special case for power-of-2 bases */
943 int accumbits
= 0; /* # of bits in accum */
944 int basebits
= 1; /* # of bits in base-1 */
946 while ((i
>>= 1) > 1)
949 for (i
= 0; i
< size_a
; ++i
) {
950 accum
|= (twodigits
)a
->ob_digit
[i
] << accumbits
;
952 assert(accumbits
>= basebits
);
954 char cdigit
= (char)(accum
& (base
- 1));
955 cdigit
+= (cdigit
< 10) ? '0' : 'A'-10;
956 assert(p
> PyString_AS_STRING(str
));
958 accumbits
-= basebits
;
960 } while (i
< size_a
-1 ? accumbits
>= basebits
:
965 /* Not 0, and base not a power of 2. Divide repeatedly by
966 base, but for speed use the highest power of base that
969 digit
*pin
= a
->ob_digit
;
970 PyLongObject
*scratch
;
971 /* powbasw <- largest power of base that fits in a digit. */
972 digit powbase
= base
; /* powbase == base ** power */
975 unsigned long newpow
= powbase
* (unsigned long)base
;
976 if (newpow
>> SHIFT
) /* doesn't fit in a digit */
978 powbase
= (digit
)newpow
;
982 /* Get a scratch area for repeated division. */
983 scratch
= _PyLong_New(size
);
984 if (scratch
== NULL
) {
989 /* Repeatedly divide by powbase. */
991 int ntostore
= power
;
992 digit rem
= inplace_divrem1(scratch
->ob_digit
,
994 pin
= scratch
->ob_digit
; /* no need to use a again */
995 if (pin
[size
- 1] == 0)
1003 /* Break rem into digits. */
1004 assert(ntostore
> 0);
1006 digit nextrem
= (digit
)(rem
/ base
);
1007 char c
= (char)(rem
- nextrem
* base
);
1008 assert(p
> PyString_AS_STRING(str
));
1009 c
+= (c
< 10) ? '0' : 'A'-10;
1013 /* Termination is a bit delicate: must not
1014 store leading zeroes, so must get out if
1015 remaining quotient and rem are both 0. */
1016 } while (ntostore
&& (size
|| rem
));
1017 } while (size
!= 0);
1025 else if (base
== 16) {
1029 else if (base
!= 10) {
1031 *--p
= '0' + base
%10;
1033 *--p
= '0' + base
/10;
1037 if (p
!= PyString_AS_STRING(str
)) {
1038 char *q
= PyString_AS_STRING(str
);
1041 } while ((*q
++ = *p
++) != '\0');
1043 _PyString_Resize((PyObject
**)&str
,
1044 (int) (q
- PyString_AS_STRING(str
)));
1046 return (PyObject
*)str
;
1050 PyLong_FromString(char *str
, char **pend
, int base
)
1053 char *start
, *orig_str
= str
;
1056 if ((base
!= 0 && base
< 2) || base
> 36) {
1057 PyErr_SetString(PyExc_ValueError
,
1058 "long() arg 2 must be >= 2 and <= 36");
1061 while (*str
!= '\0' && isspace(Py_CHARMASK(*str
)))
1065 else if (*str
== '-') {
1069 while (*str
!= '\0' && isspace(Py_CHARMASK(*str
)))
1074 else if (str
[1] == 'x' || str
[1] == 'X')
1079 if (base
== 16 && str
[0] == '0' && (str
[1] == 'x' || str
[1] == 'X'))
1083 for ( ; z
!= NULL
; ++str
) {
1089 else if (*str
>= 'a')
1090 k
= *str
- 'a' + 10;
1091 else if (*str
>= 'A')
1092 k
= *str
- 'A' + 10;
1093 if (k
< 0 || k
>= base
)
1095 temp
= muladd1(z
, (digit
)base
, (digit
)k
);
1103 if (sign
< 0 && z
!= NULL
&& z
->ob_size
!= 0)
1104 z
->ob_size
= -(z
->ob_size
);
1105 if (*str
== 'L' || *str
== 'l')
1107 while (*str
&& isspace(Py_CHARMASK(*str
)))
1113 return (PyObject
*) z
;
1116 PyErr_Format(PyExc_ValueError
,
1117 "invalid literal for long(): %.200s", orig_str
);
1122 #ifdef Py_USING_UNICODE
1124 PyLong_FromUnicode(Py_UNICODE
*u
, int length
, int base
)
1127 char *buffer
= PyMem_MALLOC(length
+1);
1132 if (PyUnicode_EncodeDecimal(u
, length
, buffer
, NULL
)) {
1136 result
= PyLong_FromString(buffer
, NULL
, base
);
1143 static PyLongObject
*x_divrem
1144 (PyLongObject
*, PyLongObject
*, PyLongObject
**);
1145 static PyObject
*long_pos(PyLongObject
*);
1146 static int long_divrem(PyLongObject
*, PyLongObject
*,
1147 PyLongObject
**, PyLongObject
**);
1149 /* Long division with remainder, top-level routine */
1152 long_divrem(PyLongObject
*a
, PyLongObject
*b
,
1153 PyLongObject
**pdiv
, PyLongObject
**prem
)
1155 int size_a
= ABS(a
->ob_size
), size_b
= ABS(b
->ob_size
);
1159 PyErr_SetString(PyExc_ZeroDivisionError
,
1160 "long division or modulo by zero");
1163 if (size_a
< size_b
||
1164 (size_a
== size_b
&&
1165 a
->ob_digit
[size_a
-1] < b
->ob_digit
[size_b
-1])) {
1167 *pdiv
= _PyLong_New(0);
1169 *prem
= (PyLongObject
*) a
;
1174 z
= divrem1(a
, b
->ob_digit
[0], &rem
);
1177 *prem
= (PyLongObject
*) PyLong_FromLong((long)rem
);
1180 z
= x_divrem(a
, b
, prem
);
1185 The quotient z has the sign of a*b;
1186 the remainder r has the sign of a,
1188 if ((a
->ob_size
< 0) != (b
->ob_size
< 0))
1189 z
->ob_size
= -(z
->ob_size
);
1190 if (a
->ob_size
< 0 && (*prem
)->ob_size
!= 0)
1191 (*prem
)->ob_size
= -((*prem
)->ob_size
);
1196 /* Unsigned long division with remainder -- the algorithm */
1198 static PyLongObject
*
1199 x_divrem(PyLongObject
*v1
, PyLongObject
*w1
, PyLongObject
**prem
)
1201 int size_v
= ABS(v1
->ob_size
), size_w
= ABS(w1
->ob_size
);
1202 digit d
= (digit
) ((twodigits
)BASE
/ (w1
->ob_digit
[size_w
-1] + 1));
1203 PyLongObject
*v
= mul1(v1
, d
);
1204 PyLongObject
*w
= mul1(w1
, d
);
1208 if (v
== NULL
|| w
== NULL
) {
1214 assert(size_v
>= size_w
&& size_w
> 1); /* Assert checks by div() */
1215 assert(v
->ob_refcnt
== 1); /* Since v will be used as accumulator! */
1216 assert(size_w
== ABS(w
->ob_size
)); /* That's how d was calculated */
1218 size_v
= ABS(v
->ob_size
);
1219 a
= _PyLong_New(size_v
- size_w
+ 1);
1221 for (j
= size_v
, k
= a
->ob_size
-1; a
!= NULL
&& k
>= 0; --j
, --k
) {
1222 digit vj
= (j
>= size_v
) ? 0 : v
->ob_digit
[j
];
1224 stwodigits carry
= 0;
1232 if (vj
== w
->ob_digit
[size_w
-1])
1235 q
= (((twodigits
)vj
<< SHIFT
) + v
->ob_digit
[j
-1]) /
1236 w
->ob_digit
[size_w
-1];
1238 while (w
->ob_digit
[size_w
-2]*q
>
1240 ((twodigits
)vj
<< SHIFT
)
1242 - q
*w
->ob_digit
[size_w
-1]
1247 for (i
= 0; i
< size_w
&& i
+k
< size_v
; ++i
) {
1248 twodigits z
= w
->ob_digit
[i
] * q
;
1249 digit zz
= (digit
) (z
>> SHIFT
);
1250 carry
+= v
->ob_digit
[i
+k
] - z
1251 + ((twodigits
)zz
<< SHIFT
);
1252 v
->ob_digit
[i
+k
] = carry
& MASK
;
1253 carry
= Py_ARITHMETIC_RIGHT_SHIFT(BASE_TWODIGITS_TYPE
,
1259 carry
+= v
->ob_digit
[i
+k
];
1260 v
->ob_digit
[i
+k
] = 0;
1264 a
->ob_digit
[k
] = (digit
) q
;
1266 assert(carry
== -1);
1267 a
->ob_digit
[k
] = (digit
) q
-1;
1269 for (i
= 0; i
< size_w
&& i
+k
< size_v
; ++i
) {
1270 carry
+= v
->ob_digit
[i
+k
] + w
->ob_digit
[i
];
1271 v
->ob_digit
[i
+k
] = carry
& MASK
;
1272 carry
= Py_ARITHMETIC_RIGHT_SHIFT(
1273 BASE_TWODIGITS_TYPE
,
1282 a
= long_normalize(a
);
1283 *prem
= divrem1(v
, d
, &d
);
1284 /* d receives the (unused) remainder */
1285 if (*prem
== NULL
) {
1298 long_dealloc(PyObject
*v
)
1300 v
->ob_type
->tp_free(v
);
1304 long_repr(PyObject
*v
)
1306 return long_format(v
, 10, 1);
1310 long_str(PyObject
*v
)
1312 return long_format(v
, 10, 0);
1316 long_compare(PyLongObject
*a
, PyLongObject
*b
)
1320 if (a
->ob_size
!= b
->ob_size
) {
1321 if (ABS(a
->ob_size
) == 0 && ABS(b
->ob_size
) == 0)
1324 sign
= a
->ob_size
- b
->ob_size
;
1327 int i
= ABS(a
->ob_size
);
1328 while (--i
>= 0 && a
->ob_digit
[i
] == b
->ob_digit
[i
])
1333 sign
= (int)a
->ob_digit
[i
] - (int)b
->ob_digit
[i
];
1338 return sign
< 0 ? -1 : sign
> 0 ? 1 : 0;
1342 long_hash(PyLongObject
*v
)
1347 /* This is designed so that Python ints and longs with the
1348 same value hash to the same value, otherwise comparisons
1349 of mapping keys will turn out weird */
1358 /* Force a 32-bit circular shift */
1359 x
= ((x
<< SHIFT
) & ~MASK
) | ((x
>> (32-SHIFT
)) & MASK
);
1360 x
+= v
->ob_digit
[i
];
1369 /* Add the absolute values of two long integers. */
1371 static PyLongObject
*
1372 x_add(PyLongObject
*a
, PyLongObject
*b
)
1374 int size_a
= ABS(a
->ob_size
), size_b
= ABS(b
->ob_size
);
1379 /* Ensure a is the larger of the two: */
1380 if (size_a
< size_b
) {
1381 { PyLongObject
*temp
= a
; a
= b
; b
= temp
; }
1382 { int size_temp
= size_a
;
1384 size_b
= size_temp
; }
1386 z
= _PyLong_New(size_a
+1);
1389 for (i
= 0; i
< size_b
; ++i
) {
1390 carry
+= a
->ob_digit
[i
] + b
->ob_digit
[i
];
1391 z
->ob_digit
[i
] = carry
& MASK
;
1394 for (; i
< size_a
; ++i
) {
1395 carry
+= a
->ob_digit
[i
];
1396 z
->ob_digit
[i
] = carry
& MASK
;
1399 z
->ob_digit
[i
] = carry
;
1400 return long_normalize(z
);
1403 /* Subtract the absolute values of two integers. */
1405 static PyLongObject
*
1406 x_sub(PyLongObject
*a
, PyLongObject
*b
)
1408 int size_a
= ABS(a
->ob_size
), size_b
= ABS(b
->ob_size
);
1414 /* Ensure a is the larger of the two: */
1415 if (size_a
< size_b
) {
1417 { PyLongObject
*temp
= a
; a
= b
; b
= temp
; }
1418 { int size_temp
= size_a
;
1420 size_b
= size_temp
; }
1422 else if (size_a
== size_b
) {
1423 /* Find highest digit where a and b differ: */
1425 while (--i
>= 0 && a
->ob_digit
[i
] == b
->ob_digit
[i
])
1428 return _PyLong_New(0);
1429 if (a
->ob_digit
[i
] < b
->ob_digit
[i
]) {
1431 { PyLongObject
*temp
= a
; a
= b
; b
= temp
; }
1433 size_a
= size_b
= i
+1;
1435 z
= _PyLong_New(size_a
);
1438 for (i
= 0; i
< size_b
; ++i
) {
1439 /* The following assumes unsigned arithmetic
1440 works module 2**N for some N>SHIFT. */
1441 borrow
= a
->ob_digit
[i
] - b
->ob_digit
[i
] - borrow
;
1442 z
->ob_digit
[i
] = borrow
& MASK
;
1444 borrow
&= 1; /* Keep only one sign bit */
1446 for (; i
< size_a
; ++i
) {
1447 borrow
= a
->ob_digit
[i
] - borrow
;
1448 z
->ob_digit
[i
] = borrow
& MASK
;
1450 borrow
&= 1; /* Keep only one sign bit */
1452 assert(borrow
== 0);
1454 z
->ob_size
= -(z
->ob_size
);
1455 return long_normalize(z
);
1459 long_add(PyLongObject
*v
, PyLongObject
*w
)
1461 PyLongObject
*a
, *b
, *z
;
1463 CONVERT_BINOP((PyObject
*)v
, (PyObject
*)w
, &a
, &b
);
1465 if (a
->ob_size
< 0) {
1466 if (b
->ob_size
< 0) {
1468 if (z
!= NULL
&& z
->ob_size
!= 0)
1469 z
->ob_size
= -(z
->ob_size
);
1482 return (PyObject
*)z
;
1486 long_sub(PyLongObject
*v
, PyLongObject
*w
)
1488 PyLongObject
*a
, *b
, *z
;
1490 CONVERT_BINOP((PyObject
*)v
, (PyObject
*)w
, &a
, &b
);
1492 if (a
->ob_size
< 0) {
1497 if (z
!= NULL
&& z
->ob_size
!= 0)
1498 z
->ob_size
= -(z
->ob_size
);
1508 return (PyObject
*)z
;
1511 /* Grade school multiplication, ignoring the signs.
1512 * Returns the absolute value of the product, or NULL if error.
1514 static PyLongObject
*
1515 x_mul(PyLongObject
*a
, PyLongObject
*b
)
1518 int size_a
= ABS(a
->ob_size
);
1519 int size_b
= ABS(b
->ob_size
);
1522 z
= _PyLong_New(size_a
+ size_b
);
1526 memset(z
->ob_digit
, 0, z
->ob_size
* sizeof(digit
));
1527 for (i
= 0; i
< size_a
; ++i
) {
1528 twodigits carry
= 0;
1529 twodigits f
= a
->ob_digit
[i
];
1531 digit
*pz
= z
->ob_digit
+ i
;
1537 for (j
= 0; j
< size_b
; ++j
) {
1538 carry
+= *pz
+ b
->ob_digit
[j
] * f
;
1539 *pz
++ = (digit
) (carry
& MASK
);
1542 for (; carry
!= 0; ++j
) {
1543 assert(i
+j
< z
->ob_size
);
1545 *pz
++ = (digit
) (carry
& MASK
);
1549 return long_normalize(z
);
1552 /* A helper for Karatsuba multiplication (k_mul).
1553 Takes a long "n" and an integer "size" representing the place to
1554 split, and sets low and high such that abs(n) == (high << size) + low,
1555 viewing the shift as being by digits. The sign bit is ignored, and
1556 the return values are >= 0.
1557 Returns 0 on success, -1 on failure.
1560 kmul_split(PyLongObject
*n
, int size
, PyLongObject
**high
, PyLongObject
**low
)
1562 PyLongObject
*hi
, *lo
;
1563 int size_lo
, size_hi
;
1564 const int size_n
= ABS(n
->ob_size
);
1566 size_lo
= MIN(size_n
, size
);
1567 size_hi
= size_n
- size_lo
;
1569 if ((hi
= _PyLong_New(size_hi
)) == NULL
)
1571 if ((lo
= _PyLong_New(size_lo
)) == NULL
) {
1576 memcpy(lo
->ob_digit
, n
->ob_digit
, size_lo
* sizeof(digit
));
1577 memcpy(hi
->ob_digit
, n
->ob_digit
+ size_lo
, size_hi
* sizeof(digit
));
1579 *high
= long_normalize(hi
);
1580 *low
= long_normalize(lo
);
1584 static PyLongObject
*k_lopsided_mul(PyLongObject
*a
, PyLongObject
*b
);
1586 /* Karatsuba multiplication. Ignores the input signs, and returns the
1587 * absolute value of the product (or NULL if error).
1588 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
1590 static PyLongObject
*
1591 k_mul(PyLongObject
*a
, PyLongObject
*b
)
1593 int asize
= ABS(a
->ob_size
);
1594 int bsize
= ABS(b
->ob_size
);
1595 PyLongObject
*ah
= NULL
;
1596 PyLongObject
*al
= NULL
;
1597 PyLongObject
*bh
= NULL
;
1598 PyLongObject
*bl
= NULL
;
1599 PyLongObject
*ret
= NULL
;
1600 PyLongObject
*t1
, *t2
, *t3
;
1601 int shift
; /* the number of digits we split off */
1604 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
1605 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
1606 * Then the original product is
1607 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
1608 * By picking X to be a power of 2, "*X" is just shifting, and it's
1609 * been reduced to 3 multiplies on numbers half the size.
1612 /* We want to split based on the larger number; fiddle so that b
1615 if (asize
> bsize
) {
1625 /* Use gradeschool math when either number is too small. */
1626 if (asize
<= KARATSUBA_CUTOFF
) {
1628 return _PyLong_New(0);
1633 /* If a is small compared to b, splitting on b gives a degenerate
1634 * case with ah==0, and Karatsuba may be (even much) less efficient
1635 * than "grade school" then. However, we can still win, by viewing
1636 * b as a string of "big digits", each of width a->ob_size. That
1637 * leads to a sequence of balanced calls to k_mul.
1639 if (2 * asize
<= bsize
)
1640 return k_lopsided_mul(a
, b
);
1642 /* Split a & b into hi & lo pieces. */
1644 if (kmul_split(a
, shift
, &ah
, &al
) < 0) goto fail
;
1645 assert(ah
->ob_size
> 0); /* the split isn't degenerate */
1647 if (kmul_split(b
, shift
, &bh
, &bl
) < 0) goto fail
;
1650 * 1. Allocate result space (asize + bsize digits: that's always
1652 * 2. Compute ah*bh, and copy into result at 2*shift.
1653 * 3. Compute al*bl, and copy into result at 0. Note that this
1654 * can't overlap with #2.
1655 * 4. Subtract al*bl from the result, starting at shift. This may
1656 * underflow (borrow out of the high digit), but we don't care:
1657 * we're effectively doing unsigned arithmetic mod
1658 * BASE**(sizea + sizeb), and so long as the *final* result fits,
1659 * borrows and carries out of the high digit can be ignored.
1660 * 5. Subtract ah*bh from the result, starting at shift.
1661 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
1665 /* 1. Allocate result space. */
1666 ret
= _PyLong_New(asize
+ bsize
);
1667 if (ret
== NULL
) goto fail
;
1669 /* Fill with trash, to catch reference to uninitialized digits. */
1670 memset(ret
->ob_digit
, 0xDF, ret
->ob_size
* sizeof(digit
));
1673 /* 2. t1 <- ah*bh, and copy into high digits of result. */
1674 if ((t1
= k_mul(ah
, bh
)) == NULL
) goto fail
;
1675 assert(t1
->ob_size
>= 0);
1676 assert(2*shift
+ t1
->ob_size
<= ret
->ob_size
);
1677 memcpy(ret
->ob_digit
+ 2*shift
, t1
->ob_digit
,
1678 t1
->ob_size
* sizeof(digit
));
1680 /* Zero-out the digits higher than the ah*bh copy. */
1681 i
= ret
->ob_size
- 2*shift
- t1
->ob_size
;
1683 memset(ret
->ob_digit
+ 2*shift
+ t1
->ob_size
, 0,
1686 /* 3. t2 <- al*bl, and copy into the low digits. */
1687 if ((t2
= k_mul(al
, bl
)) == NULL
) {
1691 assert(t2
->ob_size
>= 0);
1692 assert(t2
->ob_size
<= 2*shift
); /* no overlap with high digits */
1693 memcpy(ret
->ob_digit
, t2
->ob_digit
, t2
->ob_size
* sizeof(digit
));
1695 /* Zero out remaining digits. */
1696 i
= 2*shift
- t2
->ob_size
; /* number of uninitialized digits */
1698 memset(ret
->ob_digit
+ t2
->ob_size
, 0, i
* sizeof(digit
));
1700 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
1701 * because it's fresher in cache.
1703 i
= ret
->ob_size
- shift
; /* # digits after shift */
1704 (void)v_isub(ret
->ob_digit
+ shift
, i
, t2
->ob_digit
, t2
->ob_size
);
1707 (void)v_isub(ret
->ob_digit
+ shift
, i
, t1
->ob_digit
, t1
->ob_size
);
1710 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
1711 if ((t1
= x_add(ah
, al
)) == NULL
) goto fail
;
1716 if ((t2
= x_add(bh
, bl
)) == NULL
) {
1727 if (t3
== NULL
) goto fail
;
1728 assert(t3
->ob_size
>= 0);
1730 /* Add t3. It's not obvious why we can't run out of room here.
1731 * See the (*) comment after this function.
1733 (void)v_iadd(ret
->ob_digit
+ shift
, i
, t3
->ob_digit
, t3
->ob_size
);
1736 return long_normalize(ret
);
1747 /* (*) Why adding t3 can't "run out of room" above.
1749 Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
1752 1. For any integer i, i = c(i/2) + f(i/2). In particular,
1753 bsize = c(bsize/2) + f(bsize/2).
1754 2. shift = f(bsize/2)
1756 4. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
1757 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
1759 We allocated asize + bsize result digits, and add t3 into them at an offset
1760 of shift. This leaves asize+bsize-shift allocated digit positions for t3
1761 to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
1762 asize + c(bsize/2) available digit positions.
1764 bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
1765 at most c(bsize/2) digits + 1 bit.
1767 If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
1768 digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
1769 most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
1771 The product (ah+al)*(bh+bl) therefore has at most
1773 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
1775 and we have asize + c(bsize/2) available digit positions. We need to show
1776 this is always enough. An instance of c(bsize/2) cancels out in both, so
1777 the question reduces to whether asize digits is enough to hold
1778 (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
1779 then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
1780 asize is at least f(bsize/2)+1 digits, so this in turn reduces to whether 1
1781 digit is enough to hold 2 bits. This is so since SHIFT=15 >= 2. If
1782 asize == bsize, then we're asking whether bsize digits is enough to hold
1783 c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
1784 is enough to hold 2 bits. This is so if bsize >= 2, which holds because
1785 bsize >= KARATSUBA_CUTOFF >= 2.
1787 Note that since there's always enough room for (ah+al)*(bh+bl), and that's
1788 clearly >= each of ah*bh and al*bl, there's always enough room to subtract
1789 ah*bh and al*bl too.
1792 /* b has at least twice the digits of a, and a is big enough that Karatsuba
1793 * would pay off *if* the inputs had balanced sizes. View b as a sequence
1794 * of slices, each with a->ob_size digits, and multiply the slices by a,
1795 * one at a time. This gives k_mul balanced inputs to work with, and is
1796 * also cache-friendly (we compute one double-width slice of the result
1797 * at a time, then move on, never bactracking except for the helpful
1798 * single-width slice overlap between successive partial sums).
1800 static PyLongObject
*
1801 k_lopsided_mul(PyLongObject
*a
, PyLongObject
*b
)
1803 const int asize
= ABS(a
->ob_size
);
1804 int bsize
= ABS(b
->ob_size
);
1805 int nbdone
; /* # of b digits already multiplied */
1807 PyLongObject
*bslice
= NULL
;
1809 assert(asize
> KARATSUBA_CUTOFF
);
1810 assert(2 * asize
<= bsize
);
1812 /* Allocate result space, and zero it out. */
1813 ret
= _PyLong_New(asize
+ bsize
);
1816 memset(ret
->ob_digit
, 0, ret
->ob_size
* sizeof(digit
));
1818 /* Successive slices of b are copied into bslice. */
1819 bslice
= _PyLong_New(asize
);
1825 PyLongObject
*product
;
1826 const int nbtouse
= MIN(bsize
, asize
);
1828 /* Multiply the next slice of b by a. */
1829 memcpy(bslice
->ob_digit
, b
->ob_digit
+ nbdone
,
1830 nbtouse
* sizeof(digit
));
1831 bslice
->ob_size
= nbtouse
;
1832 product
= k_mul(a
, bslice
);
1833 if (product
== NULL
)
1836 /* Add into result. */
1837 (void)v_iadd(ret
->ob_digit
+ nbdone
, ret
->ob_size
- nbdone
,
1838 product
->ob_digit
, product
->ob_size
);
1846 return long_normalize(ret
);
1855 long_mul(PyLongObject
*v
, PyLongObject
*w
)
1857 PyLongObject
*a
, *b
, *z
;
1859 if (!convert_binop((PyObject
*)v
, (PyObject
*)w
, &a
, &b
)) {
1860 Py_INCREF(Py_NotImplemented
);
1861 return Py_NotImplemented
;
1865 /* Negate if exactly one of the inputs is negative. */
1866 if (((a
->ob_size
^ b
->ob_size
) < 0) && z
)
1867 z
->ob_size
= -(z
->ob_size
);
1870 return (PyObject
*)z
;
1873 /* The / and % operators are now defined in terms of divmod().
1874 The expression a mod b has the value a - b*floor(a/b).
1875 The long_divrem function gives the remainder after division of
1876 |a| by |b|, with the sign of a. This is also expressed
1877 as a - b*trunc(a/b), if trunc truncates towards zero.
1884 So, to get from rem to mod, we have to add b if a and b
1885 have different signs. We then subtract one from the 'div'
1886 part of the outcome to keep the invariant intact. */
1889 l_divmod(PyLongObject
*v
, PyLongObject
*w
,
1890 PyLongObject
**pdiv
, PyLongObject
**pmod
)
1892 PyLongObject
*div
, *mod
;
1894 if (long_divrem(v
, w
, &div
, &mod
) < 0)
1896 if ((mod
->ob_size
< 0 && w
->ob_size
> 0) ||
1897 (mod
->ob_size
> 0 && w
->ob_size
< 0)) {
1900 temp
= (PyLongObject
*) long_add(mod
, w
);
1907 one
= (PyLongObject
*) PyLong_FromLong(1L);
1909 (temp
= (PyLongObject
*) long_sub(div
, one
)) == NULL
) {
1925 long_div(PyObject
*v
, PyObject
*w
)
1927 PyLongObject
*a
, *b
, *div
, *mod
;
1929 CONVERT_BINOP(v
, w
, &a
, &b
);
1931 if (l_divmod(a
, b
, &div
, &mod
) < 0) {
1939 return (PyObject
*)div
;
1943 long_classic_div(PyObject
*v
, PyObject
*w
)
1945 PyLongObject
*a
, *b
, *div
, *mod
;
1947 CONVERT_BINOP(v
, w
, &a
, &b
);
1949 if (Py_DivisionWarningFlag
&&
1950 PyErr_Warn(PyExc_DeprecationWarning
, "classic long division") < 0)
1952 else if (l_divmod(a
, b
, &div
, &mod
) < 0)
1959 return (PyObject
*)div
;
1963 long_true_divide(PyObject
*v
, PyObject
*w
)
1965 PyLongObject
*a
, *b
;
1967 int aexp
, bexp
, failed
;
1969 CONVERT_BINOP(v
, w
, &a
, &b
);
1970 ad
= _PyLong_AsScaledDouble((PyObject
*)a
, &aexp
);
1971 bd
= _PyLong_AsScaledDouble((PyObject
*)b
, &bexp
);
1972 failed
= (ad
== -1.0 || bd
== -1.0) && PyErr_Occurred();
1979 PyErr_SetString(PyExc_ZeroDivisionError
,
1980 "long division or modulo by zero");
1984 /* True value is very close to ad/bd * 2**(SHIFT*(aexp-bexp)) */
1985 ad
/= bd
; /* overflow/underflow impossible here */
1987 if (aexp
> INT_MAX
/ SHIFT
)
1989 else if (aexp
< -(INT_MAX
/ SHIFT
))
1990 return PyFloat_FromDouble(0.0); /* underflow to 0 */
1992 ad
= ldexp(ad
, aexp
* SHIFT
);
1993 if (Py_OVERFLOWED(ad
)) /* ignore underflow to 0.0 */
1995 return PyFloat_FromDouble(ad
);
1998 PyErr_SetString(PyExc_OverflowError
,
1999 "long/long too large for a float");
2005 long_mod(PyObject
*v
, PyObject
*w
)
2007 PyLongObject
*a
, *b
, *div
, *mod
;
2009 CONVERT_BINOP(v
, w
, &a
, &b
);
2011 if (l_divmod(a
, b
, &div
, &mod
) < 0) {
2019 return (PyObject
*)mod
;
2023 long_divmod(PyObject
*v
, PyObject
*w
)
2025 PyLongObject
*a
, *b
, *div
, *mod
;
2028 CONVERT_BINOP(v
, w
, &a
, &b
);
2030 if (l_divmod(a
, b
, &div
, &mod
) < 0) {
2037 PyTuple_SetItem(z
, 0, (PyObject
*) div
);
2038 PyTuple_SetItem(z
, 1, (PyObject
*) mod
);
2050 long_pow(PyObject
*v
, PyObject
*w
, PyObject
*x
)
2052 PyLongObject
*a
, *b
;
2054 PyLongObject
*z
, *div
, *mod
;
2057 CONVERT_BINOP(v
, w
, &a
, &b
);
2058 if (PyLong_Check(x
) || Py_None
== x
) {
2062 else if (PyInt_Check(x
)) {
2063 c
= PyLong_FromLong(PyInt_AS_LONG(x
));
2068 Py_INCREF(Py_NotImplemented
);
2069 return Py_NotImplemented
;
2072 if (c
!= Py_None
&& ((PyLongObject
*)c
)->ob_size
== 0) {
2073 PyErr_SetString(PyExc_ValueError
,
2074 "pow() 3rd argument cannot be 0");
2079 size_b
= b
->ob_size
;
2085 PyErr_SetString(PyExc_TypeError
, "pow() 2nd argument "
2086 "cannot be negative when 3rd argument specified");
2089 /* Return a float. This works because we know that
2090 this calls float_pow() which converts its
2091 arguments to double. */
2092 return PyFloat_Type
.tp_as_number
->nb_power(v
, w
, x
);
2094 z
= (PyLongObject
*)PyLong_FromLong(1L);
2095 for (i
= 0; i
< size_b
; ++i
) {
2096 digit bi
= b
->ob_digit
[i
];
2099 for (j
= 0; j
< SHIFT
; ++j
) {
2103 temp
= (PyLongObject
*)long_mul(z
, a
);
2105 if (c
!=Py_None
&& temp
!=NULL
) {
2106 if (l_divmod(temp
,(PyLongObject
*)c
,
2121 if (bi
== 0 && i
+1 == size_b
)
2123 temp
= (PyLongObject
*)long_mul(a
, a
);
2125 if (c
!=Py_None
&& temp
!=NULL
) {
2126 if (l_divmod(temp
, (PyLongObject
*)c
, &div
,
2143 if (a
== NULL
|| z
== NULL
)
2146 if (c
!=Py_None
&& z
!=NULL
) {
2147 if (l_divmod(z
, (PyLongObject
*)c
, &div
, &mod
) < 0) {
2161 return (PyObject
*)z
;
2165 long_invert(PyLongObject
*v
)
2167 /* Implement ~x as -(x+1) */
2170 w
= (PyLongObject
*)PyLong_FromLong(1L);
2173 x
= (PyLongObject
*) long_add(v
, w
);
2177 x
->ob_size
= -(x
->ob_size
);
2178 return (PyObject
*)x
;
2182 long_pos(PyLongObject
*v
)
2184 if (PyLong_CheckExact(v
)) {
2186 return (PyObject
*)v
;
2189 return _PyLong_Copy(v
);
2193 long_neg(PyLongObject
*v
)
2196 if (v
->ob_size
== 0 && PyLong_CheckExact(v
)) {
2199 return (PyObject
*) v
;
2201 z
= (PyLongObject
*)_PyLong_Copy(v
);
2203 z
->ob_size
= -(v
->ob_size
);
2204 return (PyObject
*)z
;
2208 long_abs(PyLongObject
*v
)
2217 long_nonzero(PyLongObject
*v
)
2219 return ABS(v
->ob_size
) != 0;
2223 long_rshift(PyLongObject
*v
, PyLongObject
*w
)
2225 PyLongObject
*a
, *b
;
2226 PyLongObject
*z
= NULL
;
2228 int newsize
, wordshift
, loshift
, hishift
, i
, j
;
2229 digit lomask
, himask
;
2231 CONVERT_BINOP((PyObject
*)v
, (PyObject
*)w
, &a
, &b
);
2233 if (a
->ob_size
< 0) {
2234 /* Right shifting negative numbers is harder */
2235 PyLongObject
*a1
, *a2
;
2236 a1
= (PyLongObject
*) long_invert(a
);
2239 a2
= (PyLongObject
*) long_rshift(a1
, b
);
2243 z
= (PyLongObject
*) long_invert(a2
);
2248 shiftby
= PyLong_AsLong((PyObject
*)b
);
2249 if (shiftby
== -1L && PyErr_Occurred())
2252 PyErr_SetString(PyExc_ValueError
,
2253 "negative shift count");
2256 wordshift
= shiftby
/ SHIFT
;
2257 newsize
= ABS(a
->ob_size
) - wordshift
;
2262 return (PyObject
*)z
;
2264 loshift
= shiftby
% SHIFT
;
2265 hishift
= SHIFT
- loshift
;
2266 lomask
= ((digit
)1 << hishift
) - 1;
2267 himask
= MASK
^ lomask
;
2268 z
= _PyLong_New(newsize
);
2272 z
->ob_size
= -(z
->ob_size
);
2273 for (i
= 0, j
= wordshift
; i
< newsize
; i
++, j
++) {
2274 z
->ob_digit
[i
] = (a
->ob_digit
[j
] >> loshift
) & lomask
;
2277 (a
->ob_digit
[j
+1] << hishift
) & himask
;
2279 z
= long_normalize(z
);
2284 return (PyObject
*) z
;
2289 long_lshift(PyObject
*v
, PyObject
*w
)
2291 /* This version due to Tim Peters */
2292 PyLongObject
*a
, *b
;
2293 PyLongObject
*z
= NULL
;
2295 int oldsize
, newsize
, wordshift
, remshift
, i
, j
;
2298 CONVERT_BINOP(v
, w
, &a
, &b
);
2300 shiftby
= PyLong_AsLong((PyObject
*)b
);
2301 if (shiftby
== -1L && PyErr_Occurred())
2304 PyErr_SetString(PyExc_ValueError
, "negative shift count");
2307 if ((long)(int)shiftby
!= shiftby
) {
2308 PyErr_SetString(PyExc_ValueError
,
2309 "outrageous left shift count");
2312 /* wordshift, remshift = divmod(shiftby, SHIFT) */
2313 wordshift
= (int)shiftby
/ SHIFT
;
2314 remshift
= (int)shiftby
- wordshift
* SHIFT
;
2316 oldsize
= ABS(a
->ob_size
);
2317 newsize
= oldsize
+ wordshift
;
2320 z
= _PyLong_New(newsize
);
2324 z
->ob_size
= -(z
->ob_size
);
2325 for (i
= 0; i
< wordshift
; i
++)
2328 for (i
= wordshift
, j
= 0; j
< oldsize
; i
++, j
++) {
2329 accum
|= (twodigits
)a
->ob_digit
[j
] << remshift
;
2330 z
->ob_digit
[i
] = (digit
)(accum
& MASK
);
2334 z
->ob_digit
[newsize
-1] = (digit
)accum
;
2337 z
= long_normalize(z
);
2341 return (PyObject
*) z
;
2345 /* Bitwise and/xor/or operations */
2348 long_bitwise(PyLongObject
*a
,
2349 int op
, /* '&', '|', '^' */
2352 digit maska
, maskb
; /* 0 or MASK */
2354 int size_a
, size_b
, size_z
;
2360 if (a
->ob_size
< 0) {
2361 a
= (PyLongObject
*) long_invert(a
);
2368 if (b
->ob_size
< 0) {
2369 b
= (PyLongObject
*) long_invert(b
);
2380 if (maska
!= maskb
) {
2386 if (maska
&& maskb
) {
2394 if (maska
|| maskb
) {
2403 /* JRH: The original logic here was to allocate the result value (z)
2404 as the longer of the two operands. However, there are some cases
2405 where the result is guaranteed to be shorter than that: AND of two
2406 positives, OR of two negatives: use the shorter number. AND with
2407 mixed signs: use the positive number. OR with mixed signs: use the
2408 negative number. After the transformations above, op will be '&'
2409 iff one of these cases applies, and mask will be non-0 for operands
2410 whose length should be ignored.
2413 size_a
= a
->ob_size
;
2414 size_b
= b
->ob_size
;
2418 : (maskb
? size_a
: MIN(size_a
, size_b
)))
2419 : MAX(size_a
, size_b
);
2420 z
= _PyLong_New(size_z
);
2421 if (a
== NULL
|| b
== NULL
|| z
== NULL
) {
2428 for (i
= 0; i
< size_z
; ++i
) {
2429 diga
= (i
< size_a
? a
->ob_digit
[i
] : 0) ^ maska
;
2430 digb
= (i
< size_b
? b
->ob_digit
[i
] : 0) ^ maskb
;
2432 case '&': z
->ob_digit
[i
] = diga
& digb
; break;
2433 case '|': z
->ob_digit
[i
] = diga
| digb
; break;
2434 case '^': z
->ob_digit
[i
] = diga
^ digb
; break;
2440 z
= long_normalize(z
);
2442 return (PyObject
*) z
;
2449 long_and(PyObject
*v
, PyObject
*w
)
2451 PyLongObject
*a
, *b
;
2453 CONVERT_BINOP(v
, w
, &a
, &b
);
2454 c
= long_bitwise(a
, '&', b
);
2461 long_xor(PyObject
*v
, PyObject
*w
)
2463 PyLongObject
*a
, *b
;
2465 CONVERT_BINOP(v
, w
, &a
, &b
);
2466 c
= long_bitwise(a
, '^', b
);
2473 long_or(PyObject
*v
, PyObject
*w
)
2475 PyLongObject
*a
, *b
;
2477 CONVERT_BINOP(v
, w
, &a
, &b
);
2478 c
= long_bitwise(a
, '|', b
);
2485 long_coerce(PyObject
**pv
, PyObject
**pw
)
2487 if (PyInt_Check(*pw
)) {
2488 *pw
= PyLong_FromLong(PyInt_AS_LONG(*pw
));
2492 else if (PyLong_Check(*pw
)) {
2497 return 1; /* Can't do it */
2501 long_long(PyObject
*v
)
2508 long_int(PyObject
*v
)
2511 x
= PyLong_AsLong(v
);
2512 if (PyErr_Occurred()) {
2513 if (PyErr_ExceptionMatches(PyExc_OverflowError
)) {
2515 if (PyLong_CheckExact(v
)) {
2520 return _PyLong_Copy((PyLongObject
*)v
);
2525 return PyInt_FromLong(x
);
2529 long_float(PyObject
*v
)
2532 result
= PyLong_AsDouble(v
);
2533 if (result
== -1.0 && PyErr_Occurred())
2535 return PyFloat_FromDouble(result
);
2539 long_oct(PyObject
*v
)
2541 return long_format(v
, 8, 1);
2545 long_hex(PyObject
*v
)
2547 return long_format(v
, 16, 1);
2551 long_subtype_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
);
2554 long_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
2557 int base
= -909; /* unlikely! */
2558 static char *kwlist
[] = {"x", "base", 0};
2560 if (type
!= &PyLong_Type
)
2561 return long_subtype_new(type
, args
, kwds
); /* Wimp out */
2562 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "|Oi:long", kwlist
,
2566 return PyLong_FromLong(0L);
2568 return PyNumber_Long(x
);
2569 else if (PyString_Check(x
))
2570 return PyLong_FromString(PyString_AS_STRING(x
), NULL
, base
);
2571 #ifdef Py_USING_UNICODE
2572 else if (PyUnicode_Check(x
))
2573 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x
),
2574 PyUnicode_GET_SIZE(x
),
2578 PyErr_SetString(PyExc_TypeError
,
2579 "long() can't convert non-string with explicit base");
2584 /* Wimpy, slow approach to tp_new calls for subtypes of long:
2585 first create a regular long from whatever arguments we got,
2586 then allocate a subtype instance and initialize it from
2587 the regular long. The regular long is then thrown away.
2590 long_subtype_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
2592 PyLongObject
*tmp
, *new;
2595 assert(PyType_IsSubtype(type
, &PyLong_Type
));
2596 tmp
= (PyLongObject
*)long_new(&PyLong_Type
, args
, kwds
);
2599 assert(PyLong_CheckExact(tmp
));
2603 new = (PyLongObject
*)type
->tp_alloc(type
, n
);
2606 assert(PyLong_Check(new));
2607 new->ob_size
= tmp
->ob_size
;
2608 for (i
= 0; i
< n
; i
++)
2609 new->ob_digit
[i
] = tmp
->ob_digit
[i
];
2611 return (PyObject
*)new;
2614 PyDoc_STRVAR(long_doc
,
2615 "long(x[, base]) -> integer\n\
2617 Convert a string or number to a long integer, if possible. A floating\n\
2618 point argument will be truncated towards zero (this does not include a\n\
2619 string representation of a floating point number!) When converting a\n\
2620 string, use the optional base. It is an error to supply a base when\n\
2621 converting a non-string.");
2623 static PyNumberMethods long_as_number
= {
2624 (binaryfunc
) long_add
, /*nb_add*/
2625 (binaryfunc
) long_sub
, /*nb_subtract*/
2626 (binaryfunc
) long_mul
, /*nb_multiply*/
2627 (binaryfunc
) long_classic_div
, /*nb_divide*/
2628 (binaryfunc
) long_mod
, /*nb_remainder*/
2629 (binaryfunc
) long_divmod
, /*nb_divmod*/
2630 (ternaryfunc
) long_pow
, /*nb_power*/
2631 (unaryfunc
) long_neg
, /*nb_negative*/
2632 (unaryfunc
) long_pos
, /*tp_positive*/
2633 (unaryfunc
) long_abs
, /*tp_absolute*/
2634 (inquiry
) long_nonzero
, /*tp_nonzero*/
2635 (unaryfunc
) long_invert
, /*nb_invert*/
2636 (binaryfunc
) long_lshift
, /*nb_lshift*/
2637 (binaryfunc
) long_rshift
, /*nb_rshift*/
2638 (binaryfunc
) long_and
, /*nb_and*/
2639 (binaryfunc
) long_xor
, /*nb_xor*/
2640 (binaryfunc
) long_or
, /*nb_or*/
2641 (coercion
) long_coerce
, /*nb_coerce*/
2642 (unaryfunc
) long_int
, /*nb_int*/
2643 (unaryfunc
) long_long
, /*nb_long*/
2644 (unaryfunc
) long_float
, /*nb_float*/
2645 (unaryfunc
) long_oct
, /*nb_oct*/
2646 (unaryfunc
) long_hex
, /*nb_hex*/
2647 0, /* nb_inplace_add */
2648 0, /* nb_inplace_subtract */
2649 0, /* nb_inplace_multiply */
2650 0, /* nb_inplace_divide */
2651 0, /* nb_inplace_remainder */
2652 0, /* nb_inplace_power */
2653 0, /* nb_inplace_lshift */
2654 0, /* nb_inplace_rshift */
2655 0, /* nb_inplace_and */
2656 0, /* nb_inplace_xor */
2657 0, /* nb_inplace_or */
2658 (binaryfunc
)long_div
, /* nb_floor_divide */
2659 long_true_divide
, /* nb_true_divide */
2660 0, /* nb_inplace_floor_divide */
2661 0, /* nb_inplace_true_divide */
2664 PyTypeObject PyLong_Type
= {
2665 PyObject_HEAD_INIT(&PyType_Type
)
2667 "long", /* tp_name */
2668 sizeof(PyLongObject
) - sizeof(digit
), /* tp_basicsize */
2669 sizeof(digit
), /* tp_itemsize */
2670 (destructor
)long_dealloc
, /* tp_dealloc */
2674 (cmpfunc
)long_compare
, /* tp_compare */
2675 (reprfunc
)long_repr
, /* tp_repr */
2676 &long_as_number
, /* tp_as_number */
2677 0, /* tp_as_sequence */
2678 0, /* tp_as_mapping */
2679 (hashfunc
)long_hash
, /* tp_hash */
2681 (reprfunc
)long_str
, /* tp_str */
2682 PyObject_GenericGetAttr
, /* tp_getattro */
2683 0, /* tp_setattro */
2684 0, /* tp_as_buffer */
2685 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_CHECKTYPES
|
2686 Py_TPFLAGS_BASETYPE
, /* tp_flags */
2687 long_doc
, /* tp_doc */
2688 0, /* tp_traverse */
2690 0, /* tp_richcompare */
2691 0, /* tp_weaklistoffset */
2693 0, /* tp_iternext */
2699 0, /* tp_descr_get */
2700 0, /* tp_descr_set */
2701 0, /* tp_dictoffset */
2704 long_new
, /* tp_new */
2705 PyObject_Del
, /* tp_free */