bzoj 1467: Pku3243 clever Y 扩展BSGS

时间:2024-03-22 16:07:20

1467: Pku3243 clever Y

Time Limit: 4 Sec  Memory Limit: 64 MB
[Submit][Status][Discuss]

Description

小Y发现,数学中有一个很有趣的式子: X^Y mod Z = K 给出X、Y、Z,我们都知道如何很快的计算K。但是如果给出X、Z、K,你是否知道如何快速的计算Y呢?

Input

本题由多组数据(不超过20组),每组测试数据包含一行三个整数X、Z、K(0 <= X, Z, K <= 109)。 输入文件一行由三个空格隔开的0结尾。

Output

对于每组数据:如果无解则输出一行No Solution,否则输出一行一个整数Y(0 <= Y < Z),使得其满足XY mod Z = K,如果有多个解输出最小的一个Y。

Sample Input

5 58 33
2 4 3
0 0 0

Sample Output

9
No Solution
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define pi (4*atan(1.0))
#define eps 1e-14
const int N=2e5+,M=4e6+,inf=1e9+,mod=1e9+;
const int MAXN= ;
struct LINK{
ll data;
ll j;
ll next;
}HASH_LINK[];
ll ad, head[MAXN]; ll Gcd(ll a, ll b){
return b ? Gcd(b, a % b) : a;
} ll Ext_Gcd(ll a, ll b, ll &x, ll &y){
if(!b){
x = ; y = ;
return a;
}
ll r = Ext_Gcd(b, a % b, x, y);
ll t = x; x = y; y = t - a / b * y;
return r;
} ll POWER(ll a, ll b, ll c){
ll ans = ;
while(b){
if(b & ) ans = ans * a % c;
a = a * a % c;
b >>= ;
}
return ans;
} void init(){
memset(head, -, sizeof(head));
ad = ;
} ll Hash(ll a){
return a % MAXN;
} void INSERT_HASH(ll i, ll buf){
ll hs = Hash(buf), tail;
for(tail = head[hs]; ~tail; tail = HASH_LINK[tail]. next)
if(buf == HASH_LINK[tail]. data) return;
HASH_LINK[ad]. data = buf;
HASH_LINK[ad]. j = i;
HASH_LINK[ad]. next = head[hs];
head[hs] = ad ++;
} ll BSGS(ll a, ll b, ll c){
ll i, buf, m, temp, g, D, x, y, n = ;
for(i = , buf = ; i < ; i ++, buf = buf * a % c)
if(buf == b) return i;
D = ;
while((g = Gcd(a, c)) != ){
if(b % g) return -; // g | b 不满足,则说明无解
b /= g;
c /= g;
D = D * a / g % c;
++ n;
}
init();
m = ceil(sqrt((long double) c));
for(i = , buf = ; i <= m; buf = buf * a % c, i ++) INSERT_HASH(i, buf);
for(i = , temp = POWER(a, m, c), buf = D; i <= m; i ++, buf = temp * buf % c){
Ext_Gcd(buf, c, x, y);
x = ((x * b) % c + c) % c;
for(ll tail = head[Hash(x)]; ~tail; tail = HASH_LINK[tail].next)
if(HASH_LINK[tail]. data == x) return HASH_LINK[tail].j + n + i * m;
}
return -;
}
int main()
{
ll a,b,n;
while(~scanf("%lld%lld%lld",&a,&n,&b))
{
if(a==&&b==&&n==)break;
if(n<b)
{
printf("No Solution\n");
continue;
}
ll ans=BSGS(a,b,n);
if(ans==-)
printf("No Solution\n");
else
printf("%lld\n",ans%mod);
}
return ;
}