exgcd求解最小正整数解模板
LL exgcd(LL a, LL b, LL &x, LL &y) {
if (b == 0) { x = 1, y = 0; return a;}
LL d = exgcd(b, a % b, x, y);
LL t = x;
x = y;
y = t - a / b * y;
return d;
}
LL cal(LL a, LL b, LL c) {
LL x, y;
LL d = exgcd(a, b, x, y);
if (c % d != 0) return -1;
x *= c / d;
b /= d;
if (b < 0) b = -b;
LL ans = x % b;
if (ans <= 0) ans += b;
return ans;
}
题意:a数组中所有的数的最小公倍数为L。求出最小的数t,使得t *(t+1) 是2 * L的倍数
将指数列表中最前面几个质数相乘,可以发现乘到第十六个质数后,结果已经超过了1e18
故可以暴力枚举 L 的每个质因子是属于 t 还是 t + 1(用dfs或者位运算)
将质因子分为A,B两个集合。存在正整数x,y,使得 t+1 = ax, t = by。则有ax-by=1.可以考虑到exgcd求出最小正整数解x,则t = ax-1,每次循环更新最小答案ans
#include <bits/stdc++.h>
using namespace std;
using LL = long long;
const int N = 1e5 + 10, mod = 998244353, INF = 0x3f3f3f3f;
LL a[N];
vector<LL> p;
LL exgcd(LL a, LL b, LL &x, LL &y) {
if (b == 0) { x = 1, y = 0; return a;}
LL d = exgcd(b, a % b, x, y);
LL t = x;
x = y;
y = t - a / b * y;
return d;
}
LL cal(LL a, LL b, LL c) {
LL x, y;
LL d = exgcd(a, b, x, y);
if (c % d != 0) return -1;
x *= c / d;
b /= d;
if (b < 0) b = -b;
LL ans = x % b;
if (ans <= 0) ans += b;
return ans;
}
void solve() {
int n;
cin >> n;
for (int i = 0; i < n; i ++) cin >> a[i];
LL lcm = a[0];
for (int i = 1; i < n; i ++) {
lcm = lcm / __gcd(lcm, a[i]) * a[i];
}
lcm *= 2;
for (LL i = 2; i * i < lcm; i ++) {
if (lcm % i) continue;
p.push_back(1);
while (lcm % i == 0) lcm /= i, p.back() *= i;
}
if (lcm != 1) p.push_back(lcm);
int sz = p.size();
LL ans = 1e18;
for (int i = 0; i < (1 << sz); i ++) {
LL a = 1, b = 1;
for (int j = 0; j < sz; j ++) {
if (i & (1 << j)) a *= p[j];
else b *= p[j];
}
LL x, y;
exgcd(a, -b, x, y);
if (x == 0 || y == 0) continue;
LL t = cal(a, b, 1);
// cout << t << " ";
ans = min(ans, t * a - 1);
}
cout << ans;
}
int main() {
ios::sync_with_stdio(0), cin.tie(0);
int T = 1;
// cin >> T;
while (T -- )
solve();
return 0;
}