题目链接

3124. BSGS

给定正整数 \(a,p,b\),数据保证 \(a\)\(p\) 互质。

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

输入格式

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

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

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

输出格式

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

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

数据范围

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

输入样例:

3 5 2
3 2 1
0 0 0

输出样例:

3
0

解题思路

bsgs

有欧拉定理:\(a^{\alpha(p)}\equiv 1(\bmod p)\),则有 \(a^x\equiv a^{x\bmod \alpha(p)}(\bmod p)\),则答案范围为 \([0,\alpha(p)-1]\),为了简便计算通常会扩大查询的范围,计算 \(a^{t}\equiv b(\bmod p)\)\(t\) 的最小非负整数解 \(t\),设 \(t=k\times x-y\),其中 \(x\in [1,k],y\in [0,k-1],k=\sqrt{p}+1\),则有 \(a^{k\times x}\equiv b\times a^y(\bmod p)\),将所有的 \(b\times a^y\) 的取值放入哈希表,同时存储最大的 \(y\),然后遍历 \(x\) 即可

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

代码

// Problem: BSGS
// Contest: AcWing
// URL: https://www.acwing.com/problem/content/3127/
// Memory Limit: 64 MB
// Time Limit: 1000 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;
}

int a,p,b;
int bsgs(int a,int b,int p)
{
	b=b%p;
	if(1%p==b)return 0;
	int k=sqrt(p)+1;
	unordered_map<int,int> hash;
	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 -1;		
}
int main()
{
	while(cin>>a>>p>>b,a||b||p)
	{
		int res=bsgs(a,b,p);
		if(res>=0)cout<<res<<'\n';
		else
			puts("No Solution");
	}    
    return 0;
}

原文地址:http://www.cnblogs.com/zyyun/p/16793083.html

1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长! 2. 分享目的仅供大家学习和交流,请务用于商业用途! 3. 如果你也有好源码或者教程,可以到用户中心发布,分享有积分奖励和额外收入! 4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解! 5. 如有链接无法下载、失效或广告,请联系管理员处理! 6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需! 7. 如遇到加密压缩包,默认解压密码为"gltf",如遇到无法解压的请联系管理员! 8. 因为资源和程序源码均为可复制品,所以不支持任何理由的退款兑现,请斟酌后支付下载 声明:如果标题没有注明"已测试"或者"测试可用"等字样的资源源码均未经过站长测试.特别注意没有标注的源码不保证任何可用性