[Algorithm / template] fast power

[Algorithm / template] fast power

First, the definition

A power capable rapid (O (logN) \) \ calculate the time complexity \ (a ^ b \) an algorithm.
Quick power is commonly used algorithms.

Second, the realization principle

In fact, \ (a ^ b \) is a b a a multiplicative type, we can use a simple algorithm processed in O (N) time. Face smaller data, we can also use \ (pow (a, b) \) is calculated. Once when the data range is too large or calculated data beyond our known data types, this time we need to use fast processing power.

Like multiplication method, RMQ problem in the ST table, as well as doubling the LCA method for finding, no doubt with the "two" relevant. Fast processing power is such a method, that is 二进制拆分法. We will a base number \ (A \) binary decomposed into \ (logN \) part of the processing. Here we use a specific example to explain:

For example, we want to calculate the \ (3 ^ {14} \) values:
\ ((14) _ {10} = (1110) 2} = {_ 2 ^ 3 ^ 2 + 2 ^ 2 + 1 \) . We can find a positive integer can be arbitrarily split into such (^ \ 2 k) \ even add forms. And only for the time when the binary 1 will be accumulated. So long as we continue to base number multiplied by 3, the lowest level for the index 1is stored when the resinternal variable after each treatment right one. This is the power of rapid implementation principle.

Third, the template

The following is the power of fast template (non-recursive):

int quick_pow(int a,int b){
    int res=1;//记得赋值为1!
    while(b){
        if(b&1) res=res*a;//最低位为1
        b>>=1;a=a*a;
    }
    return res;
}

Fourth, examples

P1226 [template] || quickly take over power operation
code is as follows:

#include<bits/stdc++.h>
#define ll long long
using namespace std;
ll b,p,k;
inline ll quick_pow(ll b,ll p,ll k){
    ll res=1;
    while(p){
        if(p&1) res=(res*b)%k;
        p>>=1;
        b=(b*b)%k;
    }
    return res%k;
}
int main()
{
    scanf("%lld%lld%lld",&b,&p,&k);
    printf("%lld^%lld mod %lld=%lld",b,p,k,quick_pow(b,p,k));
    return 0;
}

Guess you like

Origin www.cnblogs.com/cyanigence-oi/p/11720401.html