Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 81a9315

Browse files
author
Tim Peters
committed
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.
1 parent 7760b4e commit 81a9315

1 file changed

Lines changed: 10 additions & 4 deletions

File tree

Objects/longobject.c

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3868,10 +3868,16 @@ long_pow(PyObject *v, PyObject *w, PyObject *x)
38683868
goto Done;
38693869
}
38703870

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

0 commit comments

Comments
 (0)