G. Hard Equation
time limit per test 10.0 s
memory limit per test 256 MB
inputs tandard input
outputs tandard output
Consider the following equationax≡bmodma^x\equiv b\quad mod\quad max≡bmodmGiven a, b and m, your task is to find a value x that satisfy the equation for the given values. Can you?
Input
The first line contains an integer T(1 ≤ T ≤ 500)T (1 ≤ T ≤ 500)T(1 ≤ T ≤ 500), in which T is the number of test cases.
Each test case consists of a line containing three integers a, b and m (0 ≤ a, b < m ≤ 109)(0 ≤ a, b < m ≤ 10^9)(0 ≤ a, b < m ≤ 109).
Output
For each test case, print a single line containing an integer x(0 ≤ x ≤ 1017)x (0 ≤ x ≤ 10^{17})x(0 ≤ x ≤ 1017) that satisfy the equation , for the given a, b and m.
If there are multiple solutions, print any of them. It is guaranteed that an answer always exist for the given input.
Example
input
3
3 9 11
2 3 5
2 1 5
output
2
3
4
思路:BSGS算法。ax≡bmodma^x\equiv b\quad mod\quad max≡bmodm其中x=i∗m−j,(j<m)x=i*\sqrt{m}-j,(j<\sqrt{m})x=i∗m−j,(j<m),转化一下即变为ai∗m≡b∗ajmodma^{i*\sqrt{m}}\equiv b*a^j\quad mod\quad mai∗m≡b∗ajmodm我们只需枚举b∗ajb*a^jb∗aj并将其与jjj保存在map中,然后遍历ai∗ma^{i*\sqrt{m}}ai∗m判断一下map里是否有对应的值即可。
#include<bits/stdc++.h>
using namespace std;
const int MAX=5e5+10;
typedef long long ll;
ll BSGS(ll a,ll b,ll m)
{
a%=m;
b%=m;
if(b==1)return 0;
unordered_map<ll,ll>ma;
ll n=sqrt(2*m)+1;
ll e=1;
for(int i=0;i<n;i++)
{
if(ma.count(b*e%m)==0)ma[b*e%m]=i;//很奇怪去掉ma.count(b*e%m)==0就会WA
e=e*a%m;
}
ll t=1;
for(int i=1;i<=n+1;i++)
{
t=t*e%m;
if(ma.count(t))return i*n-ma[t];
}
return -1;
}
int main()
{
int T;
cin>>T;
while(T--)
{
ll a,b,m;
scanf("%lld%lld%lld",&a,&b,&m);
printf("%lld\n",BSGS(a,b,m));
}
return 0;
}