#include <iostream>
using namespace Std;
Long b,p,k;
Long skt=1;
int WE,TSM;
int KSM (long b,long p,long k)
{
while (p)
{
if (p%2!=0)
{
The reason why skt=skt*b%k;//is not p=p-1 is because of the bit arithmetic in the backp=p>>1, the equivalent of P=P/2, the extra 1 is automatically eliminated, so p=p-1 can write not write
}
b=b*b%k;//re-initialized, the new formula is(b*b mod k) p/2 mod k
p=p>>1;//equivalent to P=P/2, when p=1 p displacement is 0
}
return skt%k;
}
int main ()
{
cin>>b>>p>>k;
cout<<b<< "^" <<p<< "mod" <<k<< "=" <<ksm (b,p,k);
}
Fast Power
The above formula is the core idea of the fast power algorithm.
Strength Analysis:
You can use the idea of divide and conquer to simply perform a fast power operation:
- When index b is odd, it is converted to an even number, b=b-1,ans*=b
- When exponent B is even, b=b/2,a=a*a is known by the Chinese remainder theorem: (a*b) mod c= (a mod c) * (b mod c)
The new formula is the B/2 mod C (a*a mod c)
When the exponent is 1 o'clock, the exponent can be converted to 0 by step 1, then the answer is ans*b%c.
Fast Power | | Take the remainder operation (divide and conquer the algorithm)