Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 873 Accepted Submission(s): 192
2 24 20 25 20
16 5
a^b%p=a^(b%phi(p)+phi(p))%p b>=phi(p)
#include<iostream> #include<cstdlib> #include<stdio.h> #define ll __int64 using namespace std; ll powermod(ll a,ll b,ll p) { ll res=1; while(b) { if(b&1)res=res*a%p; b>>=1; a=a*a%p; } return res; } ll get_phi(int m) { ll res=1; for(int i=2;i*i<=m;i++) { if(m%i==0) { m/=i; res*=(i-1); while(m%i==0){m/=i;res*=i;} } } if(m!=1) res*=(m-1); return res; } ll check(int a,int b,int p) { ll res=1; for(int i=1;i<=b;i++) { res*=a; if(res>=p) return res; } return res; }
ll dfs(int n,int m) { ll phi=get_phi(m); if(n<10) return n; ll x=dfs(n/10,phi); ll yy=check(n%10,x,m); if(yy>=m) { ll res=powermod(n%10,x+phi,m); if(res==0) res+=m; return res; } else return yy; }
int main() { int n,m,t; scanf("%d",&t); while(t--) { scanf("%d%d",&n,&m); printf("%I64d\n",dfs(n,m)%m); } return 0; }