洛谷-P5656 【模板】二元一次不定方程 (exgcd)
题意
若该方程无整数解,输出 。
若该方程有整数解,且有正整数解,则输出其正整数解的数量,所有正整数解中 的最小值,所有正整数解中 的最小值,所有正整数解中 的最大值,以及所有正整数解中 的最大值。
若方程有整数解,但没有正整数解,你需要输出所有整数解中 的最小正整数值, 的最小正整数值。
思路
用 exgcd 在求 gcd 时求 的解。
当 时,,此时解为 。
通过递归求解其他的解。
- 设 的解为
所以 的解为 。
当 不为 的倍数,输出 。
- 先求解 为 。
- 于是原方程有解 。
- 设 。
- 通解为 。
- 可根据 为整数求出 的值域。
- 即 。
- 取整要特判。
代码
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
int T;
ll a, b, c;
ll x, y;
ll x_1, y_1;
ll x_2, y_2;
ll d;
ll t_min, t_max;
ll m_x, m_y;
ll exgcd(ll a, ll b){
if(!b){
x = 1, y = 0;
return a;
}
ll d = exgcd(b, a % b);
ll x_0 = x, y_0 = y;
x = y_0;
y = x_0 - (a / b) * y_0;
return d;
}
int main(){
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
cin >> T;
while(T --){
cin >> a >> b >> c;
d = exgcd(a, b);
if(c % d){
cout << -1 << '\n';
continue;
}
x *= c / d;
y *= c / d;
t_min = - (x * d) / b;
t_max = (y * d) / a;
///cout << a << ' ' << b << endl;
if(x + t_min * b / d <= 0){
t_min ++;
}
if(y - t_max * a / d <= 0){
t_max --;
}
////***
if(t_max - t_min + 1 <= 0){
///cout << "------------------------------------------------------------" << endl;
m_x = b / d;
m_y = a / d;
x_1 = (x % m_x + m_x) % m_x;
if(x_1 == 0){
x_1 += m_x;
}
y_1 = (y % m_y + m_y) % m_y;
if(y_1 == 0){
y_1 += m_y;
}
cout << x_1 << ' ' << y_1 << '\n';
}
else{
///cout << "0000000000000000000000000000000000000000000000000000000000" << endl;
cout << t_max - t_min + 1 << ' ' << x + t_min * b / d << ' ' << y - t_max * a / d << ' ' << x + t_max * b / d << ' ' << y - t_min * a / d << '\n';
}
///***/
}
return 0;
}