解题思路:
BSGS模板题。
#include<cstdio>
#include<iostream>
#include<cstring>
#include<string>
#include<algorithm>
#include<cmath>
#include<ctime>
#include<vector>
#include<set>
#define ll long long
using namespace std;
const int N=50000;
const int H=999979;
int A,B,C,D;
int tot,first[H],nxt[N],val[N],deg[N];
int n,cnt,Pow[N];
int gcd(int a,int b)
{
return b?gcd(b,a%b):a;
}
void exgcd(int a,int b,int &x,int &y)
{
b?(exgcd(b,a%b,y,x),y-=a/b*x):(x=1,y=0);
}
int inv(int a,int b)
{
int x,y;
exgcd(a,b,x,y);
return (x%b+b)%b;
}
void Insert(int d,int x)
{
int u=x%H;
for(int v=first[u];v;v=nxt[v])
if(val[v]==x&°[v]<d)
{
deg[v]=d;
return;
}
nxt[++tot]=first[u],first[u]=tot,val[tot]=x,deg[tot]=d;
}
int find(int x)
{
int u=x%H;
for(int v=first[u];v;v=nxt[v])
if(val[v]==x)return deg[v];
return -1;
}
int BSGS()
{
memset(first,0,sizeof(first));
cnt=tot=0,Pow[0]=D=1;
int r,y,P=1;
while((r=gcd(A,C))!=1)
{
if(B%r!=0)return -1;
++cnt,B/=r,C/=r;
D=1ll*D*(A/r)%C;
}
B=1ll*B*inv(D,C)%C;
for(n=1;n*n<C;n++);
for(int i=1;i<=n;i++)
Pow[i]=1ll*Pow[i-1]*A%C;
for(int i=0;i<n;i++)
Insert(i,1ll*Pow[i]*B%C);
for(int i=1;i<=n;i++)
{
P=1ll*P*Pow[n]%C;
if((y=find(P))!=-1)
return i*n-y+cnt;
}
return -1;
}
bool check()
{
for(int i=0,t=1;i<=10;i++)
{
if(t%C==B)
{
cout<<i<<'\n';
return true;
}
t=1ll*t*A%C;
}
if(A==0)
{
puts("No Solution");
return true;
}
return false;
}
int main()
{
//freopen("lx.in","r",stdin);
//freopen("lx.out","w",stdout);
while(scanf("%d%d%d",&A,&C,&B)&&(ll)A+B+C>0)
{
A%=C,B%=C;
if(check())continue;
int ans=BSGS();
if(ans==-1)puts("No Solution");
else cout<<ans<<'\n';
}
return 0;
}