公式:(a*b)%p=(a%p)(b%p)%p
对a^k进行如下拆分,以及对前后项有如下推导
从最末尾a^(b0*2^0)算起
初始化res=1,下一步要乘的数temp=a
利用位运算判断bi的值
如果为1,则进行res=temp*res%p
如果为0,则跳过该步
下一步乘数temp=temp*temp%p
#include <stdio.h>
int main()
{
int q;
scanf("%d",&q);
while(q--)
{
int a,k,p;
scanf("%d%d%d",&a,&k,&p);
long long res=1,temp=a;
while(k>0)
{
//位运算,判断当前的bi为1或0
if(k&1) res=temp*res%p;
temp=temp*temp%p;
k=k>>1;//右移一位
}
printf("%lld\n",res);
}
return 0;
}