Quick to realize the power of C ++ #

Fast power template title

Obviously, this problem can not simply \ (for \) loop + \ (MOD \) to complete, because the index \ (p \) has reached a long integer, direct cycles to complete, then certainly timeout.
So fast power came into being.
What power is it fast?
Using the binary expansion of the real, to reduce the number of calculations often involve similar to \ (a ^ b \ mod p \) operations, where \ (b \) are often very large, we can not lead to \ (for \) loop calculation .
So how to use the code to achieve it?
First of all,For insuranceWe put all the data types are set long long.
Then the sake of convenience, the fast writing a power function, the parameter is the above-mentioned \ (A, B, P \) ,this is a good habit
Fast power name suggests, is quick count how many times the power of a number. Time complexity of O (logN), as compared with the efficiency of simple O (N) has been greatly improved.
In simple terms, it is a binary modulo process.
As half of the process, nothing more than expand the base-reduction index, to reduce the complexity of the effects of time.
But note that, because there is a general power of fast modulo operation, it will be carried out in the process \ (mod \) Oh.
Code is also very simple, it is a way to customize the function paste it below ...

long long qpow(long long a,long long b,long long p)
{
    long long x=a;
    long long ans=1;
    while(b)
    {
        if(b%2!=0)
            ans*=x;
        ans%=p;
        x*=x;
        x%=p;
        b/=2;
    }
    return ans;
}

ov.

Guess you like

Origin www.cnblogs.com/moyujiang/p/11240084.html