Template_Fast Power + Montgomery Fast Power Modulo_Dichotomy_logn

1. Integral modular decomposition formula

For positive integers X, Y, M, (X*Y)%M=((X%M)*(Y%M))%M

Second, the fast power algorithm

For example, to find 2^7, in general, 7 multiplication operations are required, that is, 1*2*2*2*2*2*2*2

You can keep the 2*2 result: (2*2)*(2*2)*(2*2)*2=4*4*4*2

Keep 4*4 (4*4)*(4*2)

*************************************************************************************

typedef long long LL;

LL power(LL n, LL p)//n^p
{
    LL ret = 1;//The remaining product for odd times
    if(!p) return 1;//special case
    while(p)
    {
        if(p&1) ret *= n;//If the current index is an odd number of times, keep the product of the orders
        n *= n;//Main power
        p >>= 1; // index divided by 2
    }
    return ret;
}

3. Montgomery's Fast Power Modular Algorithm

求(n^p)%M = (n*n*n*n...)%M=((n*n)%M*(n*n)%M...)%M

LL pow_mod(LL n, LL p, LL m)
{
    LL ret = 1;
    n %= m;
    if(!p) return 1;
    while(p)
    {
        if(p&1) ret = (ret*n) % m;
        n = (n*n) % m;
        p >>= 1;
    }
    return ret;
}

4. Since data overflow may be caused when doing multiplication, when doing multiplication and modulo operation, you can add and modulo to prevent overflow.

LL mul_mod(LL a, LL b, LL c)//(a*b) % c
{
    LL ret = 0;
    while(b)
    {
        if(b&1) ret = (ret+a) % c;
        a = (a << 1) % c;
        b >>= 1;
    }
    return ret;
}

LL Pow_mod(LL a, LL b, LL c)//(a^b) % c
{
    LL ret = 1;
    while(b)
    {
        if(b&1) ret = mul_mod(ret, a, c);
        a = mul_mod(a, a, c);
        b >>= 1;
    }
    return ret;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325846484&siteId=291194637