Fast exponentiation && && bit computing power

1. Ordinary exponentiation method:

The time complexity is O (n), for a large number of 1s in the TLE may limit

int pow(int base,int p){
       int ans=1;

       for(int i=1;i<=p;i++)
          ans*=base;

       return ans;
}

2. Fast power:

The time complexity is logn

(1) binding Bitwise

Principle: The index p can be converted into binary form

  Provisions Base the p- = Base I (1) * 2 ^ 0 Tasu I (2) * 2 ^ 1 Tasu I (3) * 2 ^ 2 Tasu ......

      Base = I (1) * 2 ^ 0 * Base I (2) * 2 ^ 1 * Base I (3) * 2 ^ 2 * ......

                When i (n) = 0 when multiplied by the equivalent of 1, it is equivalent to nothing by, and each is to be multiplied by the number of Base 2 ^ K , by not by (k + 1) is determined by the coefficients i, but regardless of ride do not ride, the next number is to be multiplied by the Base 2 ^ (k + 1) , ie Base 2 * 2 ^ k is (Base 2 ^ k ) 2 .

Code:

Long  Long fastpow ( Long  Long  Base , Long  Long the p-) {
         Long  Long ANS = 1 ; 

        the while (! the p-= 0 ) {    
                IF (the p-& 1 ! = 0 ) // If this bit (binary last) 1, to be multiplied by the number (or% 2 ==. 1 P) 
                      ANS * = Base ; 
              
               Base * = Base ; 
               P >> = . 1 ; (or P / = 2 ) 
         } 

         return ANS; 
}
        
         

 

(2) binding modular arithmetic

We know Base the p- % d = (Base% d) * (Base% d) * (Base% d)% * d ......

        =(base%d)p%d

On the code:

 long long fastpowmod(long long base,long long p,long long d){
                long long ans=1;
                base%=d;
    
                while(p!=0){
                        if(p&1!=0)
                                ans=ans*base%d;
                        
                        base=base*base%d;
                        p>>=1;
                }
                
                return ans;
}        

 

Guess you like

Origin www.cnblogs.com/WhiteThornZzf/p/12335995.html