diff -r 3b94a4ef244e Lib/test/test_math.py --- a/Lib/test/test_math.py Fri Feb 07 17:53:13 2014 +0100 +++ b/Lib/test/test_math.py Fri Feb 07 19:09:49 2014 +0000 @@ -422,9 +422,17 @@ self.assertEqual(math.factorial(i), py_factorial(i)) self.assertRaises(ValueError, math.factorial, -1) self.assertRaises(ValueError, math.factorial, -1.0) + self.assertRaises(ValueError, math.factorial, -10**100) + self.assertRaises(ValueError, math.factorial, -1e100) self.assertRaises(ValueError, math.factorial, math.pi) - self.assertRaises(OverflowError, math.factorial, sys.maxsize+1) - self.assertRaises(OverflowError, math.factorial, 10e100) + + # Other implementations may place different upper bounds. + @support.cpython_only + def testFactorialHugeInputs(self): + # Currently raises ValueError for inputs that are too large + # to fit into a C long. + self.assertRaises(OverflowError, math.factorial, 10**100) + self.assertRaises(OverflowError, math.factorial, 1e100) def testFloor(self): self.assertRaises(TypeError, math.floor) diff -r 3b94a4ef244e Modules/mathmodule.c --- a/Modules/mathmodule.c Fri Feb 07 17:53:13 2014 +0100 +++ b/Modules/mathmodule.c Fri Feb 07 19:09:49 2014 +0000 @@ -1406,6 +1406,7 @@ math_factorial(PyObject *self, PyObject *arg) { long x; + int overflow; PyObject *result, *odd_part, *two_valuation; if (PyFloat_Check(arg)) { @@ -1419,15 +1420,21 @@ lx = PyLong_FromDouble(dx); if (lx == NULL) return NULL; - x = PyLong_AsLong(lx); + x = PyLong_AsLongAndOverflow(lx, &overflow); Py_DECREF(lx); } else - x = PyLong_AsLong(arg); + x = PyLong_AsLongAndOverflow(arg, &overflow); - if (x == -1 && PyErr_Occurred()) + if (x == -1 && PyErr_Occurred()) { return NULL; - if (x < 0) { + } + else if (overflow == 1) { + PyErr_SetString(PyExc_OverflowError, + "factorial() argument outrageously large"); + return NULL; + } + else if (overflow == -1 || x < 0) { PyErr_SetString(PyExc_ValueError, "factorial() not defined for negative values"); return NULL;