int tmp=1;
while(y != 0)
{
if((y & 1) == 1)
tmp = (tmp*x)%k;
x = (x*x)%k;
y = y>>1;
}
return tmp;
也可以不用移位的方法
int ans = 1;
while(x != 0)
{
if(x%2 == 1)
ans = (ans*x)%k;
y /= 2;
x = (x*x)%k;
}
常见的一些模运算公式:
(a+b)mod m=((a mod m)+(b mod m))mod m;
a*b mod m=(a mod m)*(b mod m) mod m;
a^b mod m=(a mod m)^b mod m;
#include <stdio.h>
#include <iostream>
using namespace std;
long long int Func(long long int x,long long int y, long long int k)
{
long long int tmp=1;
while(y != 0)
{
if((y & 1) == 1)
tmp = (tmp*x)%k;
x = (x*x)%k;
y = y>>1;
}
return tmp;
}
int main()
{
long long int x = 0,y = 0,ans = 0;
long long int k = 0;
while(cin>>x>>y>>k)
{
ans = Func(x,y,k-1);
if(ans == 0)
ans = k-1;
cout<<ans<<endl;
}
return 0;
}