8000 gh-102221: speed up math.lcm by swapping numbers · python/cpython@2e0bcbb · GitHub
[go: up one dir, main page]

Skip to content

Commit 2e0bcbb

Browse files
committed
gh-102221: speed up math.lcm by swapping numbers
1 parent 028309f commit 2e0bcbb

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
@@ -769,7 +769,15 @@ long_lcm(PyObject *a, PyObject *b)
769769
if (_PyLong_IsZero((PyLongObject *)a) || _PyLong_IsZero((PyLongObject *)b)) {
770770
return PyLong_FromLong(0);
771771
}
772-
g = _PyLong_GCD(a, b);
772+
773+
/* Make sure a <= b to speed up (a // g) * b. */
774+
if (PyObject_RichCompareBool(b, a, Py_LT)) {
775+
g = a;
776+
a = b;
777+
b = g;
778+
}
779+
780+
g = _PyLong_GCD(b, a);
773781
if (g == NULL) {
774782
return NULL;
775783
}

0 commit comments

Comments
 (0)
0