8000 gh-111139: Optimize math.gcd(int, int) by vstinner · Pull Request #113887 · python/cpython · GitHub
[go: up one dir, main page]

Skip to content

gh-111139: Optimize math.gcd(int, int) #113887

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jan 10, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 12 additions & 5 deletions Modules/mathmodule.c
Original file line number Diff line number Diff line change
Expand Up @@ -759,13 +759,20 @@ m_log10(double x)
static PyObject *
math_gcd(PyObject *module, PyObject * const *args, Py_ssize_t nargs)
{
PyObject *res, *x;
Py_ssize_t i;
// Fast-path for the common case: avoid calling _PyNumber_Index()
// and the loop.
if (nargs == 2
&& PyLong_CheckExact(args[0])
&& PyLong_CheckExact(args[1]))
{
return _PyLong_GCD(args[0], args[1]);
}

if (nargs == 0) {
return PyLong_FromLong(0);
}
res = PyNumber_Index(args[0]);

PyObject *res = PyNumber_Index(args[0]);
if (res == NULL) {
return NULL;
}
Expand All @@ -775,8 +782,8 @@ math_gcd(PyObject *module, PyObject * const *args, Py_ssize_t nargs)
}

PyObject *one = _PyLong_GetOne(); // borrowed ref
for (i = 1; i < nargs; i++) {
x = _PyNumber_Index(args[i]);
for (Py_ssize_t i = 1; i < nargs; i++) {
PyObject *x = _PyNumber_Index(args[i]);
if (x == NULL) {
Py_DECREF(res);
return NULL;
Expand Down
0