题意:
求
Ax≡B(modC)
的最小X解。
题解:
BSGS 。
互质很好想。
对于不互质:
#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<cstdio>
using namespace std;
namespace IO
{
streambuf *ib,*ob;int buf[50];
inline void init()
{
ios::sync_with_stdio(false);
cin.tie(NULL);cout.tie(NULL);
ib=cin.rdbuf();ob=cout.rdbuf();
}
inline int read()
{
char ch=ib->sbumpc();int i=0,f=1;
while(!isdigit(ch)){if(ch=='-')f=-1;ch=ib->sbumpc();}
while(isdigit(ch)){i=(i<<1)+(i<<3)+ch-'0';ch=ib->sbumpc();}
return i*f;
}
inline void W(int x)
{
if(!x){ob->sputc('0');ob->sputc('\n');return;}
if(x<0){ob->sputc('-');x=-x;}
while(x)buf[++buf[0]]=x%10,x/=10;
while(buf[0])ob->sputc(buf[buf[0]--]+'0');
ob->sputc('\n');
}
}
using namespace IO;
int A,B,C,S;
const int Mod=49999;
struct Hash_Table
{
int tot,last[Mod+50],nxt[Mod+50],val[Mod+50],id[Mod+50];
inline void reset()
{
memset(last,0,sizeof(last));
tot=0;
}
inline void insert(int v,int idx)
{
int pos=v%Mod;
val[++tot]=v;
nxt[tot]=last[pos];
last[pos]=tot;
id[tot]=idx;
}
inline int query(int v)
{
int pos=v%Mod;
int ans=-1;
for(pos=last[pos];pos;pos=nxt[pos])
if(val[pos]==v)ans=max(ans,id[pos]);
return ans;
}
}task;
inline int gcd(int x,int y)
{
return y?gcd(y,x%y):x;
}
inline void solve()
{
task.reset();
int res=1;
for(int i=0;i<=40;i++)
{
if(res==B){W(i);return;}
res=1ll*res*A%C;
}
res=1;int tmp=gcd(A,C),k=0;
while(tmp!=1)
{
if(B%tmp){cout<<"No Solution"<<endl;return;}
res=(1ll*res*A/tmp)%C;
C/=tmp;B/=tmp;k++;
tmp=gcd(A,C);
}
tmp=1;S=sqrt(double(C))+1;
task.insert(B,0);
for(int i=1;i<=S;i++)
{
tmp=1ll*tmp*A%C;
task.insert(1ll*tmp*B%C,i);
}
int nowans=res;
for(int i=1;i<=S;i++)
{
nowans=1ll*nowans*tmp%C;
int t=task.query(nowans);
if(t!=-1){W(i*S-t+k);return;}
}
cout<<"No Solution"<<endl;
}
int main()
{
init();
while(A=read(),C=read(),B=read(),(A||B||C))
{
A%=C;B%=C;
solve();
}
}