1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
| #include<iostream> #include<cstring> #include<algorithm> #define ll long long #define inf 0x7fffffffffffffff #define mem(a, x) memset(a,x,sizeof(a)) #define io_opt ios::sync_with_stdio(false);cin.tie(0);cout.tie(0) typedef std::pair<int, int> Pii; typedef std::pair<ll, ll> Pll; ll power(ll a, ll b,ll p) { ll res = 1; for (; b > 0; b >>= 1) { if (b & 1) res = res * a % p; a = a * a % p; } return res; } ll gcd(ll p, ll q) { return q == 0 ? p : gcd(q, p % q); } ll _abs(ll x){return x < 0 ? -x : x;} using namespace std; const int maxn=1000000; bool check[maxn+10]; int phi[maxn+10]; int prime[maxn+10]; int tot; void phi_and_prime_table(int N) { memset(check,false,sizeof(check)); phi[1]=1; tot=0; for(int i=2;i<=N;++i) { if(!check[i]) { prime[tot++]=i; phi[i]=i-1; } for(int j=0;j<tot;++j) { if(i*prime[j]>N) break; check[i*prime[j]]=true; if(i%prime[j]==0) { phi[i*prime[j]]=phi[i]*prime[j]; break; } else { phi[i*prime[j]]=phi[i]*(prime[j]-1); } } } } ll quick_pow(ll a,ll b,ll mod) { ll ans=1; while(b) { if(b&1) ans=(ans*a)%mod; a=(a*a)%mod; b>>=1; } return ans%mod; } ll lowspeed(ll a,ll b,ll p){ ll cur=a,ans=0; while(b){ if(b&1) ans=(ans+cur)%p; cur=(cur+cur)%p; b>>=1; } return ans%p; } ll speed(ll a,ll b,ll p){ ll cur=a,ans=1; while(b){ if(b&1) ans=lowspeed(ans,cur,p)%p; cur=lowspeed(cur,cur,p)%p; b>>=1; } return ans%p; } ll my_pow(ll a,ll b){ ll ans=1; while(b) { if(b&1) ans=(ans*a); if(ans>1e6) return ans; a=(a*a); if(a>1e6) return a; b>>=1; } return ans; } int T,n; ll a,b,m,p,ans; ll fun(ll x,ll las){ if(las==1){ return 0; } if(x==0){ return 1; } if(gcd(las,a)==1){ return speed(a,fun(x-1,phi[las])%phi[las],las); } else{ ll anss=1; for(int i=1;i<=x-1;i++){ anss=my_pow(a,anss); if(anss>=phi[las]){ return speed(a,fun(x-1,phi[las])%phi[las]+phi[las],las); } } return speed(a,anss,las); }
} int main(){ phi_and_prime_table(1000000); io_opt; cin>>T; while(T--){ cin>>a>>b>>m; cout<<fun(b,m)<<endl; } return 0; }
|