給 a, b, c (≠0),判斷 ax + by = c 是否存在整數解。多組測資 T ≤ 10⁶。
裴蜀定理:ax + by = gcd(a,b) 必有整數解。推論:ax + by = c 有整數解 當且僅當 c % gcd(a,b) == 0。
g = gcd(a,b),O(log min(a,b))。c % g == 0,輸出 Yes/No。#includeusing namespace std; int gcd(int a, int b) { while (b) { int r = a % b; a = b; b = r; } return a; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int T; cin >> T; while (T--) { int a, b, c; cin >> a >> b >> c; cout << (c % gcd(a,b) == 0 ? "Yes" : "No") << '\n'; } return 0; }
O(T log V),V = max(|a|,|b|)。O(1)。a,b,c ≠ 0,無需處理零除錯誤。ios::sync_with_stdio(false); cin.tie(nullptr);。