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

前端 未结 4 1457
终归单人心
终归单人心 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:42

    See the Wikipedia article on modular exponentiation. Basically, when you do a**d % n, you actually have to calculate a**d, which could be quite large. But there are ways of computing a**d % n without having to compute a**d itself, and that is what pow does. The ** operator can't do this because it can't "see into the future" to know that you are going to immediately take the modulus.

提交回复
热议问题