跳到正文

个人记录

BSGS

XiaoQuQu约 4 分钟
原文
文章信息与版本

文章信息

发布
2024年6月15日
收录
2025年12月12日
更新
2026年11月8日
篇幅
约 4 分钟

版本

  1. v1当前
C++
// Problem: P3846 [TJOI2007] 可爱的质数/【模板】BSGS
// Contest: Luogu
// URL: https://www.luogu.com.cn/problem/P3846
// Memory Limit: 125 MB
// Time Limit: 1000 ms
// Author: xiaoququsd<xiaoququsd@gmail.com>
// 
// Powered by CP Editor (https://cpeditor.org)

#include <bits/stdc++.h>
using namespace std;

// Options Start

// #define NETWORK_FLOW
// #define SEGMENT_TREE
// #define FILE_IO
// #define MULTI_TESTS

// Options End
#ifdef LOCAL_TEST
bool __mem_begin;
#endif
#define int long long
#define mid ((l + r) >> 1)
#ifndef LOCAL_TEST
#define endl '\n'
#endif
#ifdef SEGMENT_TREE
#define lson (p << 1)
#define rson (p << 1 | 1)
#endif
#ifdef NETWORK_FLOW
#define rev(p) (p ^ 1)
#endif

map<int, int> mp;
int quickpow(int a, int b, int mod) {
	int ret = 1;
	while (b) {
		if (b & 1) ret = ret * a % mod;
		a = a * a % mod; b >>= 1;
	}
	return ret;
}

void work() {
	int p, b, n;
	cin >> p >> b >> n;
	int P = ceil(sqrt(p)), pw = 1;
	for (int B = 0; B <= P; ++B) {
		mp[pw * n % p] = B;
		pw = pw * b % p;
	}
	int ans = INT_MAX;
	for (int A = 1; A <= P; ++A) {
		int x = quickpow(b, A * P, p);
		if (mp[x]) ans = min(ans, A * P - mp[x]);
	}
	if (ans == INT_MAX) return cout << "no solution" << endl, void();
	cout << ans << endl;
}

#ifdef LOCAL_TEST
bool __mem_end;
#endif

signed main(void) {
	ios::sync_with_stdio(false); cin.tie(NULL);
	srand(time(nullptr));
#ifdef LOCAL_TEST
	auto __time_begin = clock();
#endif
#ifdef FILE_IO
#ifndef LOCAL_TEST
	freopen(".in", "r", stdin);
	freopen(".out", "w", stdout);
#endif
#endif
#ifdef MULTI_TESTS
	int ___T = 1; cin >> ___T; ___T--;
	while (___T--) work();
#endif
	work();
#ifdef LOCAL_TEST
	auto __time_end = clock();
	cerr << "Time: " << __time_end - __time_begin << "ms" << endl;
	cerr << "Memory: " << (&__mem_end - &__mem_begin) / 1024 << "KiB" << endl;
#endif
	return 0;
}
原文