3125. 扩展BSGS

题目链接

3125. 扩展BSGS

给定整数 \(a,p,b\)

求满足 \(a^x≡b \pmod p\) 的最小非负整数 \(x\)

输入格式

每个测试文件中最多包含 \(100\) 组测试数据。

每组数据中,每行包含 \(3\) 个整数 \(a,p,b\)

\(a=p=b=0\) 时,表示测试数据读入完全。

输出格式

对于每组数据,输出一行。

如果有 \(x\) 满足该要求,输出最小的非负整数 \(x\),否则输出 No Solution

数据范围

\(1 \le a,p \le 2^{31}-1\),
\(0 \le b \le 2^{31}-1\)

输入样例:

5 58 33
2 4 3
0 0 0

输出样例:

9
No Solution

解题思路

exbsgs

bsgs 算法的扩展版

求解 \(a^t\equiv b(\bmod p)\)\(a\)\(p\) 不一定互质) 的最小非负整数解 \(t\),先特判 \(t=0\),上式等价于\(a^t+kp=b\),设 \(d=gcd(a,p)\),如果 \(d==1\) 则即朴素版的 bsgs 算法,否则由于 \(a^t+kp\) 一定是 \(d\) 的倍数,如果 \(b\) 不为 \(d\) 的倍数则无解,对于有解的情况:\(a/d\times a^{t-1}+kp/d=b/d\),即 \(a/d\times a^{t-1}\equiv b/d(\bmod p/d)\),由于 \(a/d,p/d\) 互质,则有 \(a^{t-1}\equiv (a/d)^{-1}\times b/d(\bmod p/d)\),对于这部分递归处理即可

由于一个数的约数不是很多,故递归的层数不多,瓶颈在于朴素版的 bsgs 算法,故:

  • 时间复杂度:\(O(\sqrt{p})\)

DaIM1

// Problem: 扩展BSGS
// Contest: AcWing
// URL: https://www.acwing.com/problem/content/3128/
// Memory Limit: 64 MB
// Time Limit: 2000 ms
// 
// Powered by CP Editor (https://cpeditor.org)

// %%%Skyqwq
#include <bits/stdc++.h>
 
//#define int long long
#define help {cin.tie(NULL); cout.tie(NULL);}
#define pb push_back
#define fi first
#define se second
#define mkp make_pair
using namespace std;
 
typedef long long LL;
typedef pair<int, int> PII;
typedef pair<LL, LL> PLL;
 
template <typename T> bool chkMax(T &x, T y) { return (y > x) ? x = y, 1 : 0; }
template <typename T> bool chkMin(T &x, T y) { return (y < x) ? x = y, 1 : 0; }
 
template <typename T> void inline read(T &x) {
    int f = 1; x = 0; char s = getchar();
    while (s < '0' || s > '9') { if (s == '-') f = -1; s = getchar(); }
    while (s <= '9' && s >= '0') x = x * 10 + (s ^ 48), s = getchar();
    x *= f;
}

const int inf=0x3f3f3f3f;
int a,p,b;
int exgcd(int a,int b,int &x,int &y)
{
	if(!b)
	{
		x=1,y=0;
		return a;
	}
	int d=exgcd(b,a%b,y,x);
	y-=a/b*x;
	return d;
}
int bsgs(int a,int b,int p)
{ 
	b%=p;
	if(1%p==b)return 0;
	unordered_map<int,int> hash;
	int k=sqrt(p)+1;
	for(int i=0,j=b;i<k;i++)
	{
		hash[j]=i;
		j=(LL)j*a%p;
	}
	int ak=1;
	for(int i=1;i<=k;i++)ak=(LL)ak*a%p;
	for(int i=1,j=ak;i<=k;i++)
	{
		if(hash.count(j))return i*k-hash[j];
		j=(LL)j*ak%p;
	}
	return -inf;
}
int exbsgs(int a,int b,int p)
{
	b=(b%p+p)%p;
	if(1%p==b)return 0;
	int x,y;
	int d=exgcd(a,p,x,y);
	if(d>1)
	{
		if(b%d)return -inf;
		exgcd(a/d,p/d,x,y);
		return exbsgs(a,(LL)b/d*x%(p/d),p/d)+1;
	}
	return bsgs(a,b,p);
}
int main()
{
    while(cin>>a>>p>>b,a||p||b)
    {
    	int res=exbsgs(a,b,p);
    	if(res>=0)cout<<res<<'\n';
    	else
    		puts("No Solution");
    }
    return 0;
}
posted @ 2022-10-14 21:33  zyy2001  阅读(29)  评论(0编辑  收藏  举报