简体   繁体   English

如何实现模幂运算?

[英]How to implement modular exponentiation?

I am trying to calculate something like this: a^b mod c, where all three numbers are large. 我试图计算这样的东西:a ^ b mod c,其中所有三个数字都很大。

Things I've tried: 我试过的事情:

  1. Python's pow() function is taking hours and has yet to produce a result. Python的pow()函数需要花费数小时才能产生结果。 (if someone could tell me how it's implemented that would be very helpful!) (如果有人能告诉我它是如何实施的,那会非常有帮助!)

  2. A right-to-left binary method that I implemented, with O(log e) time, would take about 30~40 hours (don't wanna wait that long). 我用O(log e)时间实现的从右到左的二进制方法大约需要30~40个小时(不想等那么久)。

  3. Various recursion methods are producing segmentation faults (after I changed the recursion limits) 各种递归方法产生分段错误(在我更改递归限制之后)

Any optimizations I could make? 我可以进行任何优化吗?

It sounds like you are trying to evaluate pow(a, b) % c . 听起来你正试图评估pow(a, b) % c You should be using the 3-argument form, pow(a, b, c) , which takes advantage of the fact that a * b mod c == a mod c * b mod c , which means you can reduce subproducts as they are computed while computing a ^ b , rather than having to do all the multiplications first. 你应该使用3参数形式pow(a, b, c) ,它利用a * b mod c == a mod c * b mod c的事实,这意味着你可以减少子产品,因为它们是计算a ^ b时计算,而不是必须先进行所有乘法运算。

Python uses Karatsuba multiplication so the running time of multiplication is O(n^1.585). Python使用Karatsuba乘法,因此乘法的运行时间为O(n ^ 1.585)。 But division is still O(n^2). 但是分裂仍然是O(n ^ 2)。

For exponentiation, Python uses a left-to-right method with a 5-bit window. 对于取幂,Python使用从左到右的方法和5位窗口。 (It consumes 5 bits at once instead of just 1 bit. It does use more memory but will generally be faster.) (它一次消耗5位而不是1位。它确实使用更多内存,但通常会更快。)

To get faster computations, you may want to look at gmpy2 . 要获得更快的计算,您可能需要查看gmpy2 It wraps the GMP multiple-precision library and will be faster. 它包装了GMP多精度库,速度更快。 I ran a quick test and I think it will be ~100x faster. 我跑了一个快速测试,我认为它会快〜100倍。

Disclaimer: I maintain gmpy2. 免责声明:我维持gmpy2。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM