Skip to content

Commit 450c83f

Browse files
eendebakptclaude
andcommitted
Fix assertion failure in x_add() for zero operands from k_mul()
k_lopsided_mul() passes unnormalized slices of the larger operand to k_mul(). If such a slice has only zero digits, both halves of the split are zero and x_add() was called with two zero operands. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
1 parent b09a7e9 commit 450c83f

2 files changed

Lines changed: 18 additions & 0 deletions

File tree

‎Lib/test/test_long.py‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1748,6 +1748,18 @@ def test_karatsuba_single_digit_parts(self):
17481748
self.assertEqual(a * b, (1 << (SHIFT * 139)) + (1 << (SHIFT * 209)))
17491749
self.assertEqual(b * a, a * b)
17501750

1751+
def test_karatsuba_zero_parts(self):
1752+
# gh-100687: k_lopsided_mul() passes slices of the larger operand
1753+
# to k_mul(), and such a slice can consist of zero digits only.
1754+
n = KARATSUBA_CUTOFF + 30
1755+
a = (1 << (SHIFT * n)) - 1
1756+
b = 1 << (SHIFT * n * 3)
1757+
self.assertEqual(a * b, a << (SHIFT * n * 3))
1758+
self.assertEqual(b * a, a * b)
1759+
# Only the high half of a slice is zero.
1760+
b += 1 << (SHIFT * (n + 1))
1761+
self.assertEqual(a * b, (a << (SHIFT * n * 3)) + (a << (SHIFT * (n + 1))))
1762+
17511763
def test_hash(self):
17521764
# gh-136599
17531765
self.assertEqual(hash(-1), -2)

‎Objects/longobject.c‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4205,6 +4205,12 @@ k_mul(PyLongObject *a, PyLongObject *b)
42054205
if (a == b) {
42064206
t2 = (PyLongObject*)Py_NewRef(t1);
42074207
}
4208+
else if (_PyLong_IsZero(bh)) {
4209+
/* b can be an unnormalized slice made by k_lopsided_mul(), so bh
4210+
* (and bl too) can be zero, and x_add() needs a nonzero operand.
4211+
*/
4212+
t2 = (PyLongObject*)Py_NewRef(bl);
4213+
}
42084214
else if ((t2 = x_add(bh, bl)) == NULL) {
42094215
Py_DECREF(t1);
42104216
goto fail;

0 commit comments

Comments
 (0)