大数的模幂
我正在尝试实施 SAFER+ 算法。该算法需要找到幂函数的模,如下所示:
pow(45, x) mod 257
变量 x 是一个字节,因此范围可以从 0 到 255。因此,如果使用 32- 实现,幂函数的结果可能非常大,从而导致错误的值或 64 位整数。
我怎样才能进行这个计算?
I am trying to implement the SAFER+ algorithm. The algorithm requires finding the modulus of a power function as follows:
pow(45, x) mod 257
The variable x is a byte, and thus can range from 0 to 255. Accordingly, the result of the power function can be VERY big resulting in incorrect values if implemented using 32- or 64-bit integers.
How can I perform this calculation?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
一些伪代码
和调用
some pseudo code
and call
通过重复平方来执行求幂,每次运算后减少模数。这是一个非常标准的技术。
一个有效的示例:
45^13 mod 257
:首先计算 45^2、45^4、45^8 mod 257:
45^2 模 257 = 2025 模 257 = 226
45^4 模 257 = 226^2 模 257 = 51076 模 257 = 190
45^8 mod 257 = 190^2 mod 257 = 36100 mod 257 = 120
然后使用 13 的二进制展开将它们组合起来得到结果:
45^13 模 257 = 45^1 * 45^4 * 45^8 模 257
45^13 模 257 = 45 * 190 * 120 模 257
45^13 模 257 = 8550 * 120 模 257
45^13 模 257 = 69 * 120 模 257
45^13 模 257 = 8280 模 257
45^13 mod 257 = 56
请注意,计算的中间结果永远不会大于 257*257,所以这个可以轻松地以 32 位整数类型执行。
Perform the exponentiation by repeated squaring, reducing by the modulus after each operation. This is a very standard technique.
A worked example:
45^13 mod 257
:First compute 45^2, 45^4, 45^8 mod 257:
45^2 mod 257 = 2025 mod 257 = 226
45^4 mod 257 = 226^2 mod 257 = 51076 mod 257 = 190
45^8 mod 257 = 190^2 mod 257 = 36100 mod 257 = 120
Then use the binary expansion of 13 to combine these to get the result:
45^13 mod 257 = 45^1 * 45^4 * 45^8 mod 257
45^13 mod 257 = 45 * 190 * 120 mod 257
45^13 mod 257 = 8550 * 120 mod 257
45^13 mod 257 = 69 * 120 mod 257
45^13 mod 257 = 8280 mod 257
45^13 mod 257 = 56
Note that the intermediate results of the computation are never larger than 257*257, so this can easily be performed in a 32-bit integer type.
基本方法是根据指数位进行平方或乘法,并在每一步执行模约简。该算法称为(二进制)模幂。
The basic approach is to square-or-multiply depending on the exponent bit, and perform the modular reduction at each step. The algorithm is called (binary) modular exponentiation.
考虑简单恒等式:
另请注意,
如果您知道要计算的最终指数的二进制表示形式,则可以轻松计算其他幂。
Consider the simple identity:
Also note that
Other powers are trivially computed if you know the binary representation of the final exponent you wish to compute.