给a,b,c三个数字,求a的b次幂对c取余
Input
多组样例循环输入,每一组输入a,b,c (1<=a,c<=10^9,1<=b<=10^1000000).
Output
对于每一组a,b,c,输出a^b%c
样例输入
1 1 1 2 2 2 139123 123124121241452124412124 123121
样例输出
0 0 8984
降幂公式:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
#define ll long long
#define N 1000100
using namespace std;
char b[N];
ll p[N];
ll a, c;
ll quick(ll a, ll b){ //快速幂
ll k = 1;
while(b){
if(b%2==1){
k = k*a;
k %=c;
}
a = a*a%c;
b /=2;
}
return k;
}
void priem(){
memset(p, 0, sizeof(p));
ll i, j;
p[1] = 1;
for(i=2; i<=sqrt(N); i++){
for(j=2; j<=N/i; j++)
p[i*j] = 1;
}
}
ll ola(ll n){ //欧拉函数
ll i, r, aa;
r = n;
aa = n;
for(i=2; i<=sqrt(n); i++){
if(!p[i]){
if(aa%i==0){
r = r/i*(i-1);
while(aa%i==0)
aa /= i;
}
}
}
if(aa>1)
r = r/aa*(aa-1);
return r;
}
int main(){
ll d, i;
priem();
while(scanf("%ld%s%ld",&a,b,&c)!=EOF){
ll l = strlen(b);
ll B=0;
ll oc = ola(c);
// cout<<"oc = "<<oc<<endl;
for(i=0; i<l; i++){
B = B*10+b[i]-'0';
if(B>oc)
break;
}
//cout<<i<<endl;
if(i==l)
d = quick(a,B);
else{
B=0;
for(i=0; i<l; i++){ //降幂
B = (B*10+b[i]-'0')%oc;
}
d = quick(a,B+oc);
}
// printf("B= %I64d\n",B);
printf("%ld\n",d);
}
return 0;
}
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#define maxn 1000006
#define ll long long
using namespace std;
char s[maxn];
ll ol(ll x)
{
ll i,res=x;
for(int i=2;i*i<=x;i++){
if(x%i==0){
res=res-res/i;
while(x%i==0)
x/=i;
}
}
if(x>1)
res=res-res/x;
return res;
}
ll quick(ll x,ll y,ll MOD)
{
ll res=1;
while(y){
if(y%2)
res=res*x%MOD;
x=x*x%MOD;
y/=2;
}
return res;
}
int main()
{
ll a,c,i,ans,tmp,b;
while(scanf("%lld%s%lld",&a,s,&c)!=EOF){
ans=0;b=0;tmp=ol(c);
ll len=strlen(s);
for(int i=0;i<len;i++)
b=(b*10+s[i]-'0')%tmp;
b+=tmp;
ans=quick(a,b,c);
printf("%lld\n",ans);
}
return 0;
}