版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
/*
计算a^x = b mod p,求x
*/
#include <cstdio>
#include <cmath>
#include <map>
using namespace std;
typedef long long ll;
ll q_pow(ll a,ll b,ll p)
{
ll ans = 1;
while( b )
{
if( b & 1 )
{
ans *= a;
if( ans >= p ) ans %= p;
}
a *= a;
if( a >= p ) a %= p;
b >>= 1;
}
return ans;
}
ll gcd(ll a,ll b)
{
if( b == 0 ) return a;
return gcd(b,a%b);
}
ll ext_BSGS(ll a,ll b,ll p)
{
ll ans;
if( b == 1 ) return 0;
ll k = 0,d = 1,t;
/*while( ( t = gcd(a,p) ) != 1 ) //扩展时加上这段代码
{
if ( b % t ) return -1;
k ++;
b /= t;
p /= t;
d *= a / t;
d %= p;
if( d == b ) return k;
}*/
map<ll,ll> ma;
ll m = sqrt(p*1.0) + 1,a_m = q_pow(a,m,p);
ll mul = b;
for (int r = 1; r <= m; r++)
{
mul = mul * a % p;
ma[mul] = r;
}
for (int r = 1; r <= m; r++)
{
d = d * a_m % p;
if( ma[d] )
{
ans = r * m - ma[d];
ans += k;
return ans;
}
}
return -1;
}
int main()
{
ll a,b,p;
while( scanf("%lld%lld%lld",&p,&a,&b) != EOF )
{
ll res = ext_BSGS(a,b,p);
if( res == -1 ) printf("no solution\n");
else printf("%lld\n",res);
}
return 0;
}