递归写法
#include <bits/stdc++.h>
using namespace std;
int pow_mod(int a,int n,int m)
{
if(n==0)
return 1;
int x=pow_mod(a,n/2,m);
long long ans=(long long)x*x%m;
if(n%2==1)
ans=ans*a%m;
return (int)ans;
}
int main()
{
int x, y, p;
cin >> x >> y >> p;
cout << pow_mod(x, y, p) << endl;
return 0;
}
非递归写法
#include <bits/stdc++.h>
using namespace std;
int pow_mod(int a,int b,int m)
{
int ans=1;
a=a%m;
while(b!=0)
{
if(b&1) ans=(ans*a)%m;
b>>=1;
a=(a*a)%m;
}
return ans;
}
int main()
{
int x, y, p;
cin >> x >> y >> p;
cout << pow_mod(x, y, p) << endl;
return 0;
}
m一般取1E9+7