Fast modulo exponentiation Explanation of reference

First understand the

Properties of modulo arithmetic

 

                    a%b=r;

                   a=kb+r;

 

When it is found that a modulo r to the fact kb% b = 0

So for modulo exponentiation

    A ^ n is the product of (kb + r) ^ is divided into a plurality kb + r

  Multiplication modulo operation look here -------- ((kb + r1) (kb + r2)) == (kb ^ 2 + kb * (r1 + r2) + r1 * r2)% b;

There was again kb eliminate the last remaining friends ~ ~ (r1 * r2)% b;

   Using the binomial theorem we just did not take Kb part so we can get

              a^n % b =(  (r)^n % b )%b;

and so! !

 

a ^ b% c
to b, we can split into binary form
b = b0 + b1 * 2 + b2 * 2 ^ 2 + ... + bn * 2 ^ n
where our b0 corresponds to a first binary b
then we can computing a ^ b disassembled into
a ^ b0 * a ^ b1 * 2 * 1 ... * a (bn * 2 ^ n) ^
for b, the bit 1 is not 0, then for bx set to 0 are the result of our calculation is 1 would not have considered, we really want is non-zero bit of b
expression after it is assumed that removing bits of b 0 we get is
a ^ (bx * 2 ^ x) * ... * a (bn * 2 ^ n)
here we then apply our formula mentioned at the outset, then our operator a ^ b% c can be converted to
(a ^ (bx * 2 ^ x)% c) * ... * (a (bn * 2 ^ n) ^% c)
this is the case, we would be very close to the essence of the fast power
(a ^ (bx * 2 ^ x)% c) * ... * (a ^ (bn * 2 ^ n)% c)
we find that make
A1 = (A ^ (the X-BX * ^ 2)% c)
 An = (A ^ (* 2 ^ the n-BN)% c )
in this case, an is always square a (n-1) of the fold (of course, added to the list that uniform modulo), recursive sequence

 

1. If b is even, we can write
k = a2 mod c, then the request (k) b / 2 mod c it. 
2. If b is odd, we can remember ((k) b / 2 mod c × a) mod c it.

 

Now let's consider implementing it:

This is a reference --------

 

int fast_pow(int a,int b,int c)
{
    int ANS = . 1 ;    /// registration result 
    a = a% c;    /// pretreatment, so that a range of data is under c 
    the while (B =! 0 )
    {
        IF (& B . 1 ) /// odd 
        {
            ANS = (A * ANS)% C; /// eliminate the impact index is an odd number 
        }
        b >> = . 1 ;     /// binary shift operation, the constant b is traversing bit 
        A = (A * A)% C;    /// constant doubling 
    }
     return ANS;
}

Guess you like

Origin www.cnblogs.com/ballcoming/p/12150265.html