Super A^B mod C [FZU 1759]

http://acm.fzu.edu.cn/problem.php?pid=1759

View Code
//A^x = A^(x % Phi(C) + Phi(C)) (mod C) 的应用
const int MM = 1111111;
#define debug puts("wrong")
typedef __int64 int64;
const double lep=1e-10;
int64 N,mod; char str[MM];

int64 euler(int64 x) {
    int64 i, res=x;
    for(i=2;(i*i)<=x;i++) {
        if(x%i==0) {
            res=res/i*(i-1);
            while(x%i==0) x/=i;
        }
    }
    if(x>1) res=res/x*(x-1);
    return res;
}
int64 pow(int64 x,int64 y) {
    int64 res=1;
    while(y) {
        if(y&1) {
            res=res*x;
            if(res>=mod) res%=mod;
        }
        x=x*x; y>>=1;
        if(x>=mod) x%=mod;
    }
    return res;
}

void solve() {
    int64 i,j,k,tmp,res=0;
    tmp=euler(mod);
    for(i=0;str[i];i++) {
        res=res*10+(str[i]-'0');
        if(res>=tmp) res%=tmp;
    }
    res+=tmp;
    printf("%I64d\n",pow(N,res));
}
int main() {
    while(scanf("%I64d%s%I64d",&N,str,&mod)!=EOF) solve();
    return 0;
}

 

posted @ 2013-05-06 20:06  zhang1107  阅读(136)  评论(0编辑  收藏  举报