题解
不定方程求解
1 条题解
-
0
解题思路
求
ax + by = c的非负整数解。枚举x(从 0 到c/a),对每个 x 算出c - ax,如果它能被b整除,就得到一组(x, y)。如果所有 x 都没有解,输出
no answer。参考代码
#include <iostream> using namespace std; int main() { int a, b, c; cin >> a >> b >> c; int found = 0; // 枚举x,剩下的让y满足 for (int x = 0; a * x <= c; x++) { int rest = c - a * x; if (rest % b == 0) { int y = rest / b; if (y >= 0) { cout << x << " " << y << endl; found = 1; } } } if (!found) cout << "no answer" << endl; return 0; }复杂度分析
枚举 x 从 0 到 c/a,c < 1000,时间复杂度 O(c/a),额外空间复杂度 O(1)。
- 1