[C] rapid power

Fast power code is as follows:

int me (int a, int b ) // a, b incoming power 
 {
    int year = 1 ;
    
    while(b!=0)
    {
        if(b&1==1)
        { years * = a;
        }
        a*=a; b=b>>1; } return ans; }

11 to the power of 3 as an example.

If a = 3, b = 11

11 will be expressed in binary, 11 (2) = 1011, 11 may be disassembled 2 0 + 2 1 + 2 . 3

11 can be expressed as a power of 3 3 ^ (2 0 + 2 1 + 2 3 )

3 cubic dismantling of 3 ^ (2 0 ) · 3 ^ (2 1 ) * 3 ^ (2 3 )

1 & derived binary number with 3 bits at the end of operation, a right shift >> = 1, is calculated individually for each acquisition of a binary number 3.

meaning a * a:. 3 . 1 →. 3 2 →. 3 . 4 →. 3 . 8 →. 3 16 →. 3 32 → ...

 

Guess you like

Origin www.cnblogs.com/Decimus/p/11032637.html