Provided: ○ operation and the set as a group V configuration, a∈V, e is the identity element ○ operation.
That is, for any e satisfy a, there is e ○ a = a ○ e = a
We can remember
a 0 = e
an=an-1○a
It has the following properties
an+m=an○am
At this time, the calculation of a n-th power calculation on a fast power ○ can write
res=e;temp=a;
while(n)
{
if(n&1)
res=res○temp;
temp=temp○temp;
n>>=1;
}
return res;
Wherein the addition identity element is 0, the multiplication of 1
Because the same n + 0, n * 1 unchanged
Addition exponentiation
ll quick_mul(ll a, ll b, ll c) { ll res = 0; while (b != 0) { if (b % 2 == 1) res = (a + res) % c; a = (a + a) % c; b /= 2; } return res; }
Multiply exponentiation
ll quick_pow(ll a, ll b, ll c) { ll res = 1; while (b != 0) { if (b % 2 == 1) res=(res*a)%c //优化 res = quick_mul(res, a, c); a = cq(a, a, c); b /= 2; } return res; }
First, know (a * b)% c == (a% c) * (b% c) (a + b)% c == a% c + b% c
In particular to be understood as constantly first modulo c c Save, Save until enough
(a*b)%c==( ((a%c)*(c*x)) * ((b%c)(c*y)) )%c a+b)%c==( (a%c+a*x) +( b%c+b*y) )%c
Wherein the ((a% c) * (c * x)) represents a, x represents the unknown unrelated result, the (c * x) gave the same reason not Save
For a power of b
If b is an odd number a, b == a power of b / 2 * a power of b / 2 * a power
If b is an even number a, b == a power of b / 2 * a power of b / 2 power
So the code above
Another point is that the power of multiplication operation can be optimized using addition exponentiation