BSGS模板

注意边界问题  sqrt(mod)要上取整  n^0=1 要和未出现的数特判区分开

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 #define ll long long
 4 ll n,mod,ans;
 5 inline ll ksm(ll a,ll p)
 6  {ll re=1;
 7   while(p)
 8    {if(p&1) re=re*a%mod;
 9     p>>=1; a=a*a%mod;
10    }
11   return re;
12  }
13  map<ll,ll> s;
14 int main()
15  {
16   int t; scanf("%d",&t);
17   while(t--)
18   {scanf("%lld%lld%lld",&mod,&n,&ans);  // n^k =ans mod(mod)
19                                                                      // ans*n^(-x*cmp)= n^(y) mod(mod)  k=x*cmp+y;         x--[0,cmp]  y--[0,cmp)
20    ll cmp=ceil(sqrt(mod)),tmp=1; bool biao=1;
21    for(ll i=0;i<cmp;i++)
22     {if(!s[tmp]) s[tmp]=i;  //printf("%lld,%lld\n",i,tmp);
23       tmp=tmp*n%mod;
24     }
25     ll hehe=ksm(n,mod-2);
26    for(ll i=0;i<=cmp;i++)
27     {tmp=ksm(hehe,i*cmp)*ans%mod;      // printf("%lld,%lld\n",i,tmp);
28      if(s[tmp]!=0 || tmp==1) {biao=0; printf("%lld\n",i*cmp+s[tmp]); break;}
29     }
30     if(biao) printf("-l\n");
31    tmp=1;
32    for(ll i=0;i<cmp;i++) s[tmp]=0,tmp=tmp*n%mod;
33   }
34 
35  return 0;
36  }

 



上一篇:多云CMP是一个好生意吗


下一篇:拼数