Skip to content

Commit 350b32f

Browse files
committed
gh-102221: speed up math.lcm by swapping numbers
1 parent 3ac9851 commit 350b32f

File tree

2 files changed

+10
-1
lines changed

2 files changed

+10
-1
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Speed up math lcm

Modules/mathmodule.c

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -811,7 +811,15 @@ long_lcm(PyObject *a, PyObject *b)
811811
if (_PyLong_IsZero((PyLongObject *)a) || _PyLong_IsZero((PyLongObject *)b)) {
812812
return PyLong_FromLong(0);
813813
}
814-
g = _PyLong_GCD(a, b);
814+
815+
/* Make sure a <= b to speed up (a // g) * b. */
816+
if (PyObject_RichCompareBool(b, a, Py_LT)) {
817+
g = a;
818+
a = b;
819+
b = g;
820+
}
821+
822+
g = _PyLong_GCD(b, a);
815823
if (g == NULL) {
816824
return NULL;
817825
}

0 commit comments

Comments
 (0)