Commit 45e0411e authored by Mark Dickinson's avatar Mark Dickinson Committed by GitHub

Simplify negativity checks in math.comb and math.perm. (GH-13870)

parent 55295156
...@@ -3056,6 +3056,12 @@ math_perm_impl(PyObject *module, PyObject *n, PyObject *k) ...@@ -3056,6 +3056,12 @@ math_perm_impl(PyObject *module, PyObject *n, PyObject *k)
"n must be a non-negative integer"); "n must be a non-negative integer");
goto error; goto error;
} }
if (Py_SIZE(k) < 0) {
PyErr_SetString(PyExc_ValueError,
"k must be a non-negative integer");
goto error;
}
cmp = PyObject_RichCompareBool(n, k, Py_LT); cmp = PyObject_RichCompareBool(n, k, Py_LT);
if (cmp != 0) { if (cmp != 0) {
if (cmp > 0) { if (cmp > 0) {
...@@ -3072,11 +3078,8 @@ math_perm_impl(PyObject *module, PyObject *n, PyObject *k) ...@@ -3072,11 +3078,8 @@ math_perm_impl(PyObject *module, PyObject *n, PyObject *k)
LLONG_MAX); LLONG_MAX);
goto error; goto error;
} }
else if (overflow < 0 || factors < 0) { else if (factors == -1) {
if (!PyErr_Occurred()) { /* k is nonnegative, so a return value of -1 can only indicate error */
PyErr_SetString(PyExc_ValueError,
"k must be a non-negative integer");
}
goto error; goto error;
} }
...@@ -3176,6 +3179,12 @@ math_comb_impl(PyObject *module, PyObject *n, PyObject *k) ...@@ -3176,6 +3179,12 @@ math_comb_impl(PyObject *module, PyObject *n, PyObject *k)
"n must be a non-negative integer"); "n must be a non-negative integer");
goto error; goto error;
} }
if (Py_SIZE(k) < 0) {
PyErr_SetString(PyExc_ValueError,
"k must be a non-negative integer");
goto error;
}
/* k = min(k, n - k) */ /* k = min(k, n - k) */
temp = PyNumber_Subtract(n, k); temp = PyNumber_Subtract(n, k);
if (temp == NULL) { if (temp == NULL) {
...@@ -3204,11 +3213,8 @@ math_comb_impl(PyObject *module, PyObject *n, PyObject *k) ...@@ -3204,11 +3213,8 @@ math_comb_impl(PyObject *module, PyObject *n, PyObject *k)
LLONG_MAX); LLONG_MAX);
goto error; goto error;
} }
else if (overflow < 0 || factors < 0) { if (factors == -1) {
if (!PyErr_Occurred()) { /* k is nonnegative, so a return value of -1 can only indicate error */
PyErr_SetString(PyExc_ValueError,
"k must be a non-negative integer");
}
goto error; goto error;
} }
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment