Issue #19171: speed some cases of 3-argument long pow().

Reduce the base by the modulus when the base is larger than
the modulus.  This can unboundedly speed the "startup costs"
of doing modular exponentiation, particularly in cases where
the base is much larger than the modulus.  Original patch
by Armin Rigo, inspired by https://github.com/pyca/ed25519.

Merged from 3.3.
This commit is contained in:
Tim Peters 2013-10-05 16:55:38 -05:00
commit 9259c21a63
1 changed files with 10 additions and 4 deletions

View File

@ -3878,10 +3878,16 @@ long_pow(PyObject *v, PyObject *w, PyObject *x)
goto Done; goto Done;
} }
/* if base < 0: /* Reduce base by modulus in some cases:
base = base % modulus 1. If base < 0. Forcing the base non-negative makes things easier.
Having the base positive just makes things easier. */ 2. If base is obviously larger than the modulus. The "small
if (Py_SIZE(a) < 0) { exponent" case later can multiply directly by base repeatedly,
while the "large exponent" case multiplies directly by base 31
times. It can be unboundedly faster to multiply by
base % modulus instead.
We could _always_ do this reduction, but l_divmod() isn't cheap,
so we only do it when it buys something. */
if (Py_SIZE(a) < 0 || Py_SIZE(a) > Py_SIZE(c)) {
if (l_divmod(a, c, NULL, &temp) < 0) if (l_divmod(a, c, NULL, &temp) < 0)
goto Error; goto Error;
Py_DECREF(a); Py_DECREF(a);