Modulus power of big numbers

旧时模样 提交于 2019-12-27 12:09:11

问题


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?


回答1:


some pseudo code

function powermod(base, exponent, modulus) {
    if (base < 1 || exponent < 0 || modulus < 1)
        return -1

    result = 1;
    while (exponent > 0) {
       if ((exponent % 2) == 1) {
           result = (result * base) % modulus;
       }
       base = (base * base) % modulus;
       exponent = floor(exponent / 2);
    }
    return result;
}

and call

powermod(45, x, 257)    



回答2:


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:

  1. 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

  2. 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.




回答3:


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.




回答4:


Consider the simple identity:

mod(A^2,p) = mod(A,p)*mod(A,p)

Also note that

A^4 = (A^2)^2

Other powers are trivially computed if you know the binary representation of the final exponent you wish to compute.



来源:https://stackoverflow.com/questions/8287144/modulus-power-of-big-numbers

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