Clever Y
题意:给a,c,b,求最小的x使得 ax≡b (mod c)。
扩展BSGS算法~
1 #include <cstdio> 2 #include <cstring> 3 #include <iostream> 4 #include <cmath> 5 #define ll long long 6 using namespace std; 7 const int mod=99991; 8 ll head[mod],nex[mod]; 9 ll cnt; 10 ll hs[mod],id[mod]; 11 void init(){ 12 memset(head,-1,sizeof(head)); 13 cnt=0; 14 } 15 void insert_(ll x,ll i){ 16 hs[cnt]=x;id[cnt]=i; 17 ll u=x%mod; 18 nex[cnt]=head[u]; 19 head[u]=cnt++; 20 } 21 ll find_(ll x){ 22 int u=x%mod; 23 for(int i=head[u];~i;i=nex[i]){ 24 if(hs[i]==x) return id[i]; 25 } 26 return -1; 27 } 28 ll gcd(ll a,ll b){ 29 ll r=a%b; 30 while(r){a=b;b=r;r=a%b;} 31 return b; 32 } 33 ll BSGS(ll a,ll b,ll c){ 34 a%=c;b%=c; 35 if(b==1) return 0; 36 ll g=1,d=1,k=0; 37 while((g=gcd(a,c))!=1){ 38 if(b%g) return -1; 39 b/=g;c/=g; 40 k++; 41 d=d*(a/g)%c; 42 if(b==d) return k; 43 } 44 ll m=ceil(sqrt(c*1.0)),q=1; 45 for(ll i=0;i<=m;i++){ 46 if(i==0) insert_(b,i); 47 else { 48 q=q*a%c; 49 insert_(q*b%c,i); 50 } 51 } 52 for(ll i=1;i<=m;i++){ 53 d=d*q%c; 54 ll j=find_(d); 55 if(j!=-1) return i*m-j+k; 56 } 57 return -1; 58 } 59 int main(){ 60 ll a,b,c; 61 while(scanf("%lld%lld%lld",&a,&c,&b)&&(a+b+c)){ 62 init(); 63 ll ans=BSGS(a,b,c); 64 if(ans==-1) puts("No Solution"); 65 else printf("%lld\n",ans); 66 } 67 }
时间: 2024-10-07 18:45:21