Why is pow(a, d, n) so much faster than a**d % n?

前端 未结 4 1454
终归单人心
终归单人心 2020-12-02 09:11

I was trying to implement a Miller-Rabin primality test, and was puzzled why it was taking so long (> 20 seconds) for midsize numbers (~7 digits). I eventually found the fol

4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-02 09:28

    The way x = a**d % n is calculated is to raise a to the d power, then modulo that with n. Firstly, if a is large, this creates a huge number which is then truncated. However, x = pow(a, d, n) is most likely optimized so that only the last n digits are tracked, which are all that are required for calculating multiplication modulo a number.

提交回复
热议问题