hdu2837(2009多校第三场) a^b%p=a^(b%phi(p)+phi(p))%p b>=phi(p)
公式如上,dfs函数思考清楚==
另外欧拉函数以前写的可以换了
1 #include<stdio.h> 2 #include<string.h> 3 #include<math.h> 4 #define LL long long 5 LL phi(LL x) 6 { 7 LL ans=x,i; 8 for (i=2;i*i<=x;i++) 9 if (x%i==0) 10 { 11 ans=ans/i*(i-1); 12 while (x%i==0) x/=i; 13 } 14 if (x!=1) ans=ans/x*(x-1); 15 return ans; 16 } 17 LL quick(LL a,LL b,LL m) 18 { 19 LL ans=1; 20 while (b!=0) 21 { 22 if (b%2) ans=ans*a%m; 23 b/=2; 24 a=a*a%m; 25 } 26 return ans; 27 } 28 LL check(LL a,LL b,LL m) 29 { 30 LL ans=1,i; 31 for (i=1;i<=b;i++) 32 { 33 ans=ans*a; 34 if (ans>=m) return ans; 35 } 36 return ans; 37 } 38 LL dfs(LL n,LL m) 39 { 40 if (n<10) return n; 41 LL p,tmp,y,ans; 42 p=phi(m); 43 tmp=dfs(n/10,p); 44 y=check(n%10,tmp,m); 45 if (y>=m) { 46 ans=quick(n%10,tmp+p,m); 47 return ans==0?m:ans; 48 } 49 return y; 50 } 51 int main() 52 { 53 LL T,n,m; 54 scanf("%I64d",&T); 55 while (T--) 56 { 57 scanf("%I64d%I64d",&n,&m); 58 printf("%I64d\n",dfs(n,m)%m); 59 } 60 return 0; 61 }