2

If I run, assuming e is a large value like 65537:

x**e

It takes a very long time, however assuming a reasonable n:

(x**e)%n

Runs much faster, so Python is clearly optimising modular exponentiation. My question is how does CPython identify that it can make this optimisation, is it the bytecode or something else?

0x777C
  • 993
  • 7
  • 21
  • independently of cpython, I think in general modular exponentiation is faster than exponentiation so its not necessarily a feature of cpython, but of the c math library being used – chiliNUT May 07 '20 at 22:27
  • I mean yes I understand that modular exponentiation is faster but my question is more to do with how CPython identifies this pattern where in Java's BigInteger for example you'd call .modPow() to take advantage of this optimisation – 0x777C May 07 '20 at 23:32
  • 1
    Could you add your timing results along with the version of CPython you're using? I'm under the impression you're mistakenly interpreting as an optimization the delay it takes for Python to print the result of a very large integer. – Dimitris Fasarakis Hilliard May 08 '20 at 09:01
  • It seems you're right, when timing it the modular exponentiation is actually slower. python -m timeit -c "(256**0x10001)%7351346217512465" gives 1.94 msec per loop while python -m timeit -c "(256**0x10001)" gives 1.56 msec per loop – 0x777C May 08 '20 at 10:15
  • @Faissaloo and that should be expected. CPython purposely does very little to optimize code. – Dimitris Fasarakis Hilliard May 08 '20 at 12:44

0 Answers0