PS: Reprint, write their own less than others, afraid of misleading. Reprint Address: http://www.cnblogs.com/CXCXCXC/p/4641812.html
First of all, the purpose of the fast power is to do a quick exponentiation, assuming we ask a^b, according to the naïve algorithm is to connect A to B, so that the time complexity is O (b) is also the O (n) level, fast power to do O (Logn), a lot faster. It has the following principles:
Suppose we ask for a^b, then in fact B can be split into binary, the second number of bits I is the right to 2^ (i-1), such as when b==11
a^11=a^ (2^0+2^1+2^3) 11 binary is 1011,11 = 23x1 + 22x0 + 21x1 + 2ox1, therefore, we will A11 converted to calculate a^ (2^0) *a^ (2^1) *a^ (2^3), see much faster than the original count 11 times, now count Three times, but these three looks like a bad look .... No hurry, there will be a detailed explanation below. Because it is binary, it is natural to think of this powerful tool with bit operations: the & and >> & operations are typically used for binary take operations, such as the result of a number & 1, which is the last digit of the binary. It can also be judged that the odd and even x&1==0 are even, x&1==1 is odd. >> operations relatively simple, the binary system to remove the last one, not much to say, first put the code to explain.
1 int poww (int a,int b) {2 int ans=1,base=a; 3 while (b!=0) {4 if (b&1!=0) 5 ans*=base; 6 Base*=ba Se 7 b>>=1; 8} 9 return ans;10}
Code is very short, rote is also feasible, but it is better to understand, in fact, also very good understanding, take b==11 For example, b=>1011, binary from right to left, but the order is a^ (2^0) *a^ (2^1) *a^ (2^3), is from left to right. We constantly make base*=base the purpose of the ride, so that we can contribute to ans at any time.
One to understand base*=base this step, see:: base*base==base^2, Next multiply, is base^2*base^2==base^4, and then the same base^4*base4=base^8,,,,, seeing? is not done base-->base^2-->base^4-->base^8-->base^16-->base^32 ... index is 2^i ah, look at the above example, a11= a^ (2^0) *a^ (2^1) *a^ (2^3), these three items are not the perfect solution,, well, fast power is like this.
By the way, because the exponential function is the function of explosion growth, so it is likely to explode the range of int, according to test instructions decide whether to use a long long AH or unsigned int ah or mod a number ah himself look at the office.
Fast Power Algorithm (matrix fast power is not very good.) will be updated later)