轉自:
https://blog.csdn.net/qq_38177302/article/details/78449982
第一步 : 給出方程 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.
代碼如下 :
/** function : work out ax + by = c ->(x, y) and request that x is least positive integer. date : 2017.11.5 author : LSC code : c++ */ #include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #define LL long long using namespace std; long long int x, y, d;// (x, y) ax+by = Gcd(a, b)的其中的一個解,d 是(a, b)最大公約數 LL Gcd(LL a, LL b)// 歐幾里德算法(輾轉相除法)求解最大公約數 { return (b == 0)? a : Gcd(b, a%b); } void ex_gcd(LL a, LL b)// 擴展歐幾里德 算法 { if(b == 0) { x = 1; y = 0; d = a; } else { ex_gcd(b, a%b); LL temp = x; x = y; y = temp - a/b*y; } } int main() { LL a, b, c, gcd; scanf("%lld%lld%lld", &a, &b, &c); gcd = Gcd(a, b); if(c % gcd != 0)// 判斷是否有解 printf("Impossible\n"); else { ex_gcd(a, b); LL x1, y1, b1; b1 = b/gcd; x1 = (x + b1) * (c/gcd); x1 = (x1 % b1 + b1) % b1;// 求解出 x 的 最小正整數解 y1 = (c - a*x1) / b; printf("x = %lld , y = %lld\n", x1, y1); } return 0; }
下面再來一個壓縮版本的比較短。
#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\n"); 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\n", x1, y1); } return 0; }