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

Skip to content

Commit e35ba2a

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

File tree

2 files changed

+11
-2
lines changed

2 files changed

+11
-2
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: 10 additions & 2 deletions
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; see #102221 for details. */
774+
if (_PyLong_DigitCount((PyLongObject *)b) < _PyLong_DigitCount((PyLongObject *)a)) {
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
}
@@ -830,7 +838,7 @@ math_lcm_impl(PyObject *module, PyObject * const *args,
830838
Py_DECREF(x);
831839
continue;
832840
}
833-
Py_SETREF(res, long_lcm(res, x));
841+
Py_SETREF(res, long_lcm(x, res));
834842
Py_DECREF(x);
835843
if (res == NULL) {
836844
return NULL;

0 commit comments

Comments
 (0)
0