The fast power to take the mold is actually a^b%c, this is the famous RSA public key encryption method, when a, B are very big time, the direct is not advisable, therefore uses the fast power to take the mold.
First you have to understand his principle, in fact, the use of two points of thought, the B in accordance with the binary expansion
b = P (n) *2^n + p (n-1) *2^ (n-1) +...+ P (1) * * + P (0). where P (i) (0<=i<=n) is 0 or 1.
So at this time a^b = a^ (P (n) *2^n + p (n-1) *2^ (n-1) +...+ P (1) * + P (0)) = a^ (P (n) *2^n) * a^ (P (n-1) *2^ (n-1)) *...* a^ (P (1) * 2) * A^P (0);
For P (i) =0 the case is not processed, since a^ (P (i) * 2^ (i-1)) = A^0 = 1;
So what we need to consider is just the case of P (i) =1:
a^ (2^i) = a^ (2^ (i-1) * 2) = (a^ (P (i) * 2^ (i-1))) ^2
"Http://baike.baidu.com/view/1431260.htm" is described here in detail.
Here is a non-recursive approach:
Long Long modexp (long long A, long long b, int mod) { long long Res=1; while (b>0) { //a=a%mod; (sometimes the value of n is too large to store a long long, so take the remainder first) if (b&1)//& bit operations: The last one to determine the binary is 0 or 1, & Operation rules are 1 before and after the time is 1; res=res*a%mod; b=b>>1;//is equivalent to dividing by 2; a=a*a%mod; } return res;}
Fast power modulo algorithm "template"