top1编程
← 返回题目
题解

不定方程求解

1 条题解

  • 0
    @ 2026-8-4 16:08:45

    解题思路

    求 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