BITACM 1056 A^B mod C v3.0

来源:互联网 发布:javascript 注释规范 编辑:程序博客网 时间:2024/04/29 22:30

最BT的一个版本吧。。。

A,C的范围比较小,但最好还是考虑一下乘法溢出的问题。

B有100w位,那肯定是不能硬算的。

注意到取模有这样的一个公式: A^B = A^(B mod phi(C)+ phi(C)) mod C。

那么这题就可做了。

对B进行预处理然后快速幂即可。

#include "cstdio"#include "cstring"#include "cmath"#define LL long longLL mul_mod(LL a,LL b,LL c){    LL ret=0,tmp=a%c;    while(b)    {        if(b&0x1)if((ret+=tmp)>=c)ret-=c;        if((tmp<<=1)>=c)tmp-=c;        b>>=1;    }    return ret;}LL pow_mod(LL a,LL p,LL n){    if(p==0)  return 1%n;    LL ans=pow_mod(a,p/2,n);    ans=mul_mod(ans, ans, n);    if(p%2==1)  ans=mul_mod(ans, a, n);    return ans%n;}LL euler_phi(LL n){    LL m=(int)sqrt(n+0.5);    LL ans=n;    for(int i=2;i<=m;i++)        if(n%i==0){            ans=ans/i*(i-1);            while (n%i==0)   n/=i;        }    if(n>1)  ans=ans/n*(n-1);    return ans;}int main(){    char s[1000005];    LL len;    LL a,c;    while(scanf("%lld%s%lld",&a,s,&c)!=EOF){        LL p=0;        LL tem=euler_phi(c);        len=strlen(s);        for(LL i=0;i<len;i++){            p=(p*10+s[i]-'0')%tem;        }        p+=tem;        printf("%lld\n",pow_mod(a, p, c));    }    return 0;}

 

0 0
原创粉丝点击