第一步 : 给出方程 ax + by = c 。
第二步 : 算出 辗转相除法 gcd(a, b) 。
第三步 : 运用 扩展欧几里德 ex_gcd(a, b)-》 ax + by = gcd(a,b) 的 一组解(x, y) 。
第三步: 根据 c % gcd(a, b) 判断是否 ax + by = c 有解 。
第四步 : 根据 ax + by = c 的通解公式 x1 = (x + k * ( b / gcd(a, b) )) * (c / gcd(a, b) 令 b1 = b / gcd(a, b) , 所以 x1 的 最小正整数解 为 : x1 = (x1 % b1 + b1) % b1, 对应的 y1 = (c - a*x1) / b.
#include <iostream> #include <cstring> #include <cstdio> #include <algorithm> #define LL long long using namespace std; void extend_gcd(LL a, LL b, LL& d, LL& x, LL& y) { if(!b){ d = a; x = 1; y = 0; } else { extend_gcd(b, a%b,d, y, x); y -= x*(a/b);} } int main() { LL a, b, c, d; LL x, y, x1, y1; cin >> a >> b >> c; extend_gcd(a, b, d, x, y); if(c % d != 0) printf("Impossible "); else { LL b1 = b / d; x1 = (x + b1) * (c / d); x1 = (x1 % b1 + b1) % b1; y1 = (c - a*x1) / b; printf("x = %lld, y = %lld ", x1, y1); } return 0; }