Fast exponential algorithm

Issue Brief

In the RSA, the encryption and decryption process is required after a certain integer powers of integers modulo. Most of the time, these two integers are relatively large, intermediate results obtained by direct meaning to be calculated this time the computer would exceed the allowed range integer (e.g. computing \ (66 ^ {77} \) , which is quite small); on the other hand, we have to consider the efficiency of computing, such as \ (66 ^ {77} \) is directly calculated in accordance with the definition of the words to do 76 multiplications, the overhead is considerable. For these two problems, we need to have a good algorithm to efficiently and accurately computing power of large integer arithmetic.

Preliminary ideas

For the first problem that the value is too large problem, consider using the properties of modular arithmetic:
\ [(A * B) (n-MOD) = [(A (n-MOD)) * (B (n-MOD))] ( mod n) \]
can effectively reduce the intermediate value.
For the second problem, using the properties of the index, the results for each part of the repeated squaring, the minimum number of operations may be as Save \ (log_2n \) , computing \ (x ^ {16} \ ) , it is possible performed as follows:
\ [^ X 2, 4 X ^, X ^. 8, X 16 ^ {} \]
need only count four times, reducing the ratio of 3/4 is calculated according to the definition.

Fast exponential algorithm

Fast exponential algorithm incorporates two ideas above, the algorithm is described as follows:

In general, we compute \ (a ^ mmodn \) when m represents a first binary form \ (b_k, B_. 1-K {}, ..., b_0 \) , i.e.
\ [m = \ sum \ limits_ { b_i = 1} 2 ^ i \
] Thus,
\ [A ^ m = A ^ {\ SUM \ limits_ {B_i =. 1} 2 ^ I} = \ Prod \ limits_ {B_i =. 1} A ^ {2 ^ I} \]
\ [^ mmodn = A [\ Prod \ limits_ B_i = {}. 1 A ^ I ^ {2}] modN = \ Prod \ limits_ B_i = {}. 1 [I ^ A ^ {2} modN] \]

Code simple realization:

d = 1
for i in range(k+1):
    d = d*d%n
    if b[i] == '1':
        d = d*a%n

Suddenly think of it, he said today that the lesson we handouts Lin really a lot of mistakes, but I believe your ability can be rectified, ooo, ooo, I cried hot, an afternoon to remember these words

Guess you like

Origin www.cnblogs.com/chuaner/p/12019791.html