Modular Exponentiation

北战南征 提交于 2019-12-29 09:08:37

问题


In C/C++ how can I calculate (a^b)%m where b does not fit into 64 bits? In other words, is there a way of calculating the above value using b%m instead of b?

And is there any algorithm that can compute the above result in O(log(b)) time or O(log(b%m)) time?


回答1:


According to Euler's theorem, if a and m are coprime:

ab mod m = ab mod phi(m) mod m

so if b is large, you can use the value b % phi(m) instead of b. phi(m) is Euler's totient function, which can be easily calculated if you know the prime factorization of m.

Once you've reduced the value of b in this way, use Exponentiation by squaring to compute the modular exponentiation in O(log (b % phi(m))).



来源:https://stackoverflow.com/questions/11448658/modular-exponentiation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!