Skip to content

Commit 5f46ac9

Browse files
gh-160872: Keep PyLong "x_divrem" inner loop carry in 64 bits (#161156)
* gh-160872: Keep PyLong "x_divrem" inner loop carry in 64 bits --------- Co-authored-by: blurb-it[bot] <43283697+blurb-it[bot]@users.noreply.github.com>
1 parent 9ea60a5 commit 5f46ac9

2 files changed

Lines changed: 6 additions & 7 deletions

File tree

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Optimize division and remainder operations on large :class:`int` values.

‎Objects/longobject.c‎

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3325,8 +3325,7 @@ x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
33253325
int d;
33263326
digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;
33273327
twodigits vv;
3328-
sdigit zhi;
3329-
stwodigits z;
3328+
stwodigits z, zhi;
33303329

33313330
/* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
33323331
edn.), section 4.3.1, Algorithm D], except that we don't explicitly
@@ -3416,16 +3415,15 @@ x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
34163415
for (i = 0; i < size_w; ++i) {
34173416
/* invariants: -PyLong_BASE <= -q <= zhi <= 0;
34183417
-PyLong_BASE * q <= z < PyLong_BASE */
3419-
z = (sdigit)vk[i] + zhi -
3418+
z = (stwodigits)vk[i] + zhi -
34203419
(stwodigits)q * (stwodigits)w0[i];
34213420
vk[i] = (digit)z & PyLong_MASK;
3422-
zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
3423-
z, PyLong_SHIFT);
3421+
zhi = Py_ARITHMETIC_RIGHT_SHIFT(stwodigits, z, PyLong_SHIFT);
34243422
}
34253423

34263424
/* add w back if q was too large (this branch taken rarely) */
3427-
assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);
3428-
if ((sdigit)vtop + zhi < 0) {
3425+
assert((stwodigits)vtop + zhi == -1 || (stwodigits)vtop + zhi == 0);
3426+
if ((stwodigits)vtop + zhi < 0) {
34293427
carry = 0;
34303428
for (i = 0; i < size_w; ++i) {
34313429
carry += vk[i] + w0[i];

0 commit comments

Comments
 (0)