Romatic HDU2699

本文介绍如何使用扩展欧几里得算法解决特定数学问题,即给定两个非负整数a和b,找到非负整数x和整数y,使x×a+y×b=1成立。通过调整和优化,确保x为非负数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意:给两个非负整数 a 和 b,要找到一个非负整数 x 和一个整数 y,使得满足 x×a+y×b=1

思路:用扩展欧几里得,因为要求 x 非负,所以可以把式子写成 x×a+y×b+a×ba×b=a×(b+x)+b×(ya)=1。欧几里得算出 x 和 y 后还要判断下 x,如果 x 小于 0,则用上面的推导式分别给 x 和 y 加上 b 和 -a 就好。

代码:

#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<stack>
#include<queue>
#include<utility>
#include<vector>
#include<cmath>
#include<set>
#include<map>
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long LL;

LL ExtendGcd(LL a, LL b, LL& x, LL& y)
{
    LL r;
    if(b == 0){
        x = 1;
        y = 0;
        return a;
    }
    else{
        r = ExtendGcd(b, a%b, y, x);
        y -= (a/b)*x;
    }
    return r;
}

int main()
{
    LL a, b;
    while(scanf("%lld%lld", &a, &b) == 2){
        LL x, y;
        if(ExtendGcd(a, b, x, y) == 1){
            while(x < 0){
                x += b;
                y -= a;
            }
            printf("%lld %lld\n", x, y);
        }
        else{
            printf("sorry\n");
        }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值