手敲了这题,差不多入门同余了
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define ls (o<<1)
#define rs (o<<1|1)
#define pb push_back
//#define a(i,j) a[(i)*(m+2)+(j)] //m是矩阵的列数
const double PI= acos(-1.0);
const int M = 1e5+7;
/*
int head[M],cnt;
void init(){cnt=0,memset(head,0,sizeof(head));}
struct EDGE{int to,nxt,val;}ee[M*2];
void add(int x,int y,int z){ee[++cnt].nxt=head[x],ee[cnt].to=y,ee[cnt].val=z,head[x]=cnt;}
*/
ll qpow(ll a,ll b,ll p)
{
ll ans=1;
while(b)
{
if(b&1)ans=ans*a%p;
a=a*a%p;
b/=2;
}
return ans;
}
ll bsgs(ll a,ll b,ll p)// a^x \equiv b (mod p)
{
map<ll,ll>hash;hash.clear();
b%=p;
ll t=(ll)sqrt(p)+1;
for(int j=0;j<t;j++)
{
ll val=(ll)b*qpow(a,j,p)%p;//b*a^j
hash[val]=j;
}
a=qpow(a,t,p);//a^t
if(a==0)return b==0?1:-1;//0 % b =0 只有b是0才有解
for(ll i=0;i<=t;i++)
{
ll val=qpow(a,i,p);
ll j= hash.find(val)==hash.end() ? -1 : hash[val];
if(j>=0&&i*t-j>=0)return i*t-j;//最非负整数解
}
return -1;
}
ll exgcd(ll a,ll b,ll &x,ll &y)
{
if(b==0)
{
x=1,y=0;
return a;
}
ll d=exgcd(b,a%b,x,y);
ll z=x;
x=y,y=z-y*(a/b);
return d;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
ll a,b,p;
int t,q;
cin>>t>>q;
while(t--)
{
cin>>a>>b>>p;
if(q==1)cout<<qpow(a,b,p)<<endl;
if(q==2)
{
ll x,y;
// a*x+p*y=b
ll tp=exgcd(a,p,x,y);
//cout<<tp<<" -- "<<x<<endl;
x*=b/tp;//一个特解
ll m=p/tp;
// cout<<m<<endl;
if(b%tp!=0)cout<<"Orz, I cannot find x!"<<endl;
else cout<<(x%m+m)%m<<endl;
}
if(q==3)
{
int tp=bsgs(a,b,p);
if(tp>=0)cout<<tp<<endl;
else cout<<"Orz, I cannot find x!\n";
}
}
return 0;
}