洛谷P1226 【模板】快速幂||取余运算
百度文库有个很详细讲解(https://wenku.baidu.com/view/d65f294702768e9951e73883.html)
but 这个模板有个缺陷,指数为零咋办?
加一个预处理就行了,就是第九行。
#include<bits/stdc++.h>
using namespace std;
int main()
{
long long b,p,k,ans=1;
cin>>b>>p>>k;
cout<<b<<"^"<<p<<" mod "<<k<<"=";
b%=k;
if(!p) ans=ans%k;
while(p)
{
if(p%2) ans=(ans*b)%k;
p/=2;
b=(b*b)%k;
}
cout<<ans;
return 0;
}