Appearance
若无特殊说明,本章涉及的变量皆为正整数。
简介
形如
特殊解
先用 扩展欧几里得算法 求出一组
两边同乘
于是找到方程
通解
若
在实际问题中,往往只需要最小正整数解:
模板
cpp
int exGcd(int a, int b, int& x, int& y) {
if (b == 0) { x = 1, y = 0; return a; }
int d = exGcd(b, a % b, x, y);
int t = x; x = y, y = t - a / b * y;
return d;
}
int liEu(int a, int b, int c) { // ax ≡ c (mod b)
int x, y, d = exGcd(a, b, x, y);
if (c % d != 0) return -1; // 没有整数解
return x * (c / d); // 特殊解
// int t = b / d;
// return x = (x % t + t) % t; // 最小正整数解
}