Power and fast examples

Fast power:

Example: a ^ 11 = a ^ (2 ^ 0) * a ^ (2 ^ 1) * a ^ (2 ^ 3)

 

 11 is binary 1011 and 1 as the first, second, fourth, their weights were 0,1,3. 11 it can be split into 2 + 2 ^ 0 ^ 3 ^ 2 + 1.

With this thought fast power function (c ++) on behalf of ULL unsigned long long 

ULL quickpow(ULL a,ULL b){
    ULL res=1;
    for(;b;b>>=1){
        if(b&1)
            res*=a;
        a*=a;
    }
    return res;
}

 

Guess you like

Origin www.cnblogs.com/FrankYu-/p/11703211.html