AC通道:http://www.lydsy.com/JudgeOnline/problem.php?id=2242
【吐槽】
三合一的一道模板题。快速幂+扩展gcd+离散对数
学过这三个的人应该都会吧,不会的。。。传送门:http://www.cnblogs.com/chty/p/6022641.html
写的时候手贱把哈希表写错了,调了半天。。。
贴个丑陋的代码:
/*************
bzoj 2242
by chty
2016.11.9
*************/
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<ctime>
#include<cmath>
#include<algorithm>
using namespace std;
#define FILE "read"
#define MAXN 99991
typedef long long ll;
struct node{ll v,f,num;}hash[MAXN+10];
ll a,b,mod;
inline ll read()
{
ll x=0,f=1; char ch=getchar();
while(!isdigit(ch)) {if(ch=='-') f=-1; ch=getchar();}
while(isdigit(ch)) {x=x*10+ch-'0'; ch=getchar();}
return x*f;
}
void insert(ll v,ll x)
{
ll temp=v%MAXN;
while(hash[temp].f&&hash[temp].v!=v) {temp++; if(temp>MAXN) temp-=MAXN;}
if(!hash[temp].f) hash[temp].f=1,hash[temp].v=v,hash[temp].num=x;
}
ll find(ll v)
{
ll temp=v%MAXN;
while(hash[temp].f&&hash[temp].v!=v) {temp++; if(temp>MAXN) temp-=MAXN;}
if(!hash[temp].f) return -1;
else return hash[temp].num;
}
ll gcd(ll a,ll b) {return !b?a:gcd(b,a%b);}
ll exgcd(ll a,ll b,ll &x,ll &y)
{
if(!b) {x=1; y=0; return a;}
ll g=exgcd(b,a%b,x,y);
ll t=x;x=y;y=t-a/b*y;
return g;
}
void solve1(){ll sum=1;for(;b;b>>=1,a=a*a%mod)if(b&1)sum=sum*a%mod;printf("%d\n",sum);}
void solve2()
{
ll x,y,d=exgcd(a,mod,x,y);
if(b%d) {printf("Orz, I cannot find x!\n");return;}
ll t=mod/d;
while(x<0) x+=t;
while(x>=t) x-=t;
printf("%lld\n",x*b%mod);
}
void solve3()
{
if(mod==1) {puts("0"); return;}
a%=mod;b%=mod;
ll ret(1);
for(ll i=0;i<=50;i++) {if(ret==b) {printf("%lld\n",i); return; ret=ret*a%mod;}}
ll temp,ans(1),cnt(0);
while((temp=gcd(a,mod))!=1)
{
if(b%temp) {printf("Orz, I cannot find x!\n");return;}
mod/=temp; b/=temp;
ans=ans*(a/temp)%mod;
cnt++;
}
ll m=(ll)sqrt(mod*1.0),t(1);
for(ll i=0;i<m;i++) {insert(t,i);t=t*a%mod;}
for(ll i=0;i<m;i++)
{
ll x,y;
exgcd(ans,mod,x,y);
ll val=x*b%mod;
val=(val+mod)%mod;
ll j=find(val);
if(j!=-1) {printf("%lld\n",i*m+j+cnt);return;}
ans=ans*t%mod;
}
printf("Orz, I cannot find x!\n");
return;
}
void pre() {for(ll i=0;i<=MAXN;i++)hash[i].f=0,hash[i].num=hash[i].v=-1;}
int main()
{
freopen(FILE".in","r",stdin);
freopen(FILE".out","w",stdout);
ll T=read(),flag=read();
while(T--)
{
pre();
a=read(); b=read(); mod=read();
switch(flag)
{
case 1:solve1();break;
case 2:solve2();break;
case 3:solve3();break;
}
}
return 0;
}