Quick & fast power modulo multiplication modulo

Fast power modulo

I.e., obtain fast (a ^ b) of the value of mod c. Because when the values ​​of a, b very large directly find a ^ b may cause overflow and inefficient.

Thinking

The principle is based on \ (A * B \% C = ((A \% C) * (B \% C)) \% C \) , \ (A ^ B \% C = (A \% C) ^ B \% c \) formula.

Solving fast power:

Provided index represented in binary as b \ (b = (. 1-n-B_n B_ {...} b_2b_1b_0) _2 \) ,

\(b = b_0 + b_1*2^1 + b_2*2^2+...+b_{n-1}*2^{n-1} + b_n*2^n\)

\ (a ^ b = a ^ {b_0 b_1 * 2 ^ 1 + b_2 * 2 ^ 2 + ... + b_ {n-1} * 2 ^ {n-1} + b_n * 2 ^ n} = a ^ {b0} * a ^ {b_1 * 2 ^ 1} * a ^ {b_2 * 2 ^ 2} * ... * a ^ {b_ {n-1} * 2 ^ {n-1}} * a ^ {b_n * 2 ^ n} \) ,

\(a^b \% c = a^{b0}*a^{b_1*2^1}*a^{b_2*2^2} *...*a^{b_{n-1}*2^{n-1}} * a^{b_n*2^n} \% c\)

Set \ (K_n = (A ^ {B_n * 2 ^ n-}) \% C \) , seeking Kn words, when bn = 0 when Kn =. 1, BN =. 1 \ (Kn = (A ^ {2 ^ n- }) \% C \) , thus calculated and then consider \ ((A ^ ^ {n-2}) \% C \) .

\ ((a ^ {2 ^ n}) \% c = [(a ^ {2 ^ {n-1}} \% c) * (a ^ {2 ^ {n-1}} \% c)] \% c \) thus recursive.

Code

python

def quick_powmod(a, b, c):
    a = a % c
    ans = 1 # 存放结果
    while b != 0:
        if b & 1: # 二进制与
            ans = (ans * a) % c
        a = (a * a) % c # 取模是防止溢出
        b >>= 1 # 二进制向右移动一位
    return ans

For example, a = 2 b = 10 c = 3, b is the binary representation of 1010.

\ (^ 2 ^ {10} = {2 * 0+. 1. 1 + 0 * 2 ^ 2 ^ 2 + 2 ^ *. 3. 1} \) , the bits B taken from right to left, is 0, that multiplies a, is 1, the result is multiplied to take the tired ans years.

Rapid multiplication modulo

To transform the multiplication using binary adder.

Thinking

Fast modulo exponentiation and the like, converted to a binary multiplier calculation.

For example, \ (20 * 20 * 14 = (1110) 2 * 2 ^ 20 = 0 * 0 * 2 ^ 20 + 1 + 20 * 1 * 1 * 2 ^ 2 + 2 ^ 20 * 3 * 1 \)

Code

Python

def quick_mulmod(a, b, c):
    ans = 0
    a = a % c
    while b != 0:
        if b & 1 :
            ans = (ans + a) % c
        a = (2*a) % c
        b >>= 1
    return ans

At first glance the still very difficult to understand, for example derive again to understand.

Guess you like

Origin www.cnblogs.com/KRDecad3/p/11603873.html