diff --git a/Lib/test/test_long.py b/Lib/test/test_long.py index ce72c256774d77..c33a9a5e6f2609 100644 --- a/Lib/test/test_long.py +++ b/Lib/test/test_long.py @@ -1748,6 +1748,18 @@ def test_karatsuba_single_digit_parts(self): self.assertEqual(a * b, (1 << (SHIFT * 139)) + (1 << (SHIFT * 209))) self.assertEqual(b * a, a * b) + def test_karatsuba_zero_parts(self): + # gh-100687: k_lopsided_mul() passes slices of the larger operand + # to k_mul(), and such a slice can consist of zero digits only. + n = KARATSUBA_CUTOFF + 30 + a = (1 << (SHIFT * n)) - 1 + b = 1 << (SHIFT * n * 3) + self.assertEqual(a * b, a << (SHIFT * n * 3)) + self.assertEqual(b * a, a * b) + # Only the high half of a slice is zero. + b += 1 << (SHIFT * (n + 1)) + self.assertEqual(a * b, (a << (SHIFT * n * 3)) + (a << (SHIFT * (n + 1)))) + def test_hash(self): # gh-136599 self.assertEqual(hash(-1), -2) diff --git a/Objects/longobject.c b/Objects/longobject.c index 4a3117c43de5e1..b48328efa2f1b7 100644 --- a/Objects/longobject.c +++ b/Objects/longobject.c @@ -4205,6 +4205,12 @@ k_mul(PyLongObject *a, PyLongObject *b) if (a == b) { t2 = (PyLongObject*)Py_NewRef(t1); } + else if (_PyLong_IsZero(bh)) { + /* b can be an unnormalized slice made by k_lopsided_mul(), so bh + * (and bl too) can be zero, and x_add() needs a nonzero operand. + */ + t2 = (PyLongObject*)Py_NewRef(bl); + } else if ((t2 = x_add(bh, bl)) == NULL) { Py_DECREF(t1); goto fail;