c++ -求ax +by = c的所有非负整数解

#include <iostream>
#include <functional>
#include <algorithm>
#include <vector>
#include <math.h>

using namespace std;

int extgcd(int a, int b, int& x, int& y) {
    if (b == 0) {
        x = 1, y = 0;
        return a;
    }
    int d = extgcd(b, a % b, y, x);
    y -= a / b * x;
    return d;
}

vector<pair<int, int>> findPositiveSolution(int a, int b, int c) {
    int gd, x0, y0;
    gd = extgcd(a, b, x0, y0);
    if (c % gd != 0) {
        return {};
    }
    int factor = c / gd;
    x0 *= factor;
    y0 *= factor;

    int a_d = a / gd;
    int b_d = b / gd;
    int k1 = ceil((double )(-x0) / b_d);
    int k2 = floor((double )y0 / a_d);
    if (k1 > k2) {
        return {};
    }
    vector<pair<int, int>> res;
    for (int k = k1; k <= k2; k++) {
        int x = x0 + b_d * k;
        int y = y0 - a_d * k;
        if (x >= 0 and y >= 0) {
            res.emplace_back(x, y);
        }
    }
    return res;
}

int main() {
    auto res = findPositiveSolution(3, 5, 120);
    if (res.empty()) {
        cout << "No solution" << endl;
        return 0;
    }
    for (auto [x, y] : res) {
        cout << x << " " << y << endl;
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值