hdu2669 扩展欧几里得

本文介绍如何使用扩展欧几里得算法求解形如ax+by=1的线性方程组,并寻找非负整数解中x的最小值。文章详细解释了扩展欧几里得算法的原理及其应用,并提供了具体的实现代码。

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

题目大意:求ax+by=1的非负整数x和y(x最小)

思路:简单的扩展欧几里得

1、ax+by=c若有解(x0,y0),则必有(a,b)|c , 其中(a,b)表示a,b的最大公约数,可以整除c则有解。

2、若(a,b)=1 , 则方程全部解为:x=x0+bt ,y=y0-at(t为整数)

3、若(a,b)> 1 , 则方程全部解为:x=x0+bt/d ,y=y0-at/d , d=(a,b);

扩展欧几里得可以求出a,b最大公约数d,还可以求出|x|+|y|最小值得x,y的解。


#include <cstdio>
#include <string>
#include <cstring>
#include <fstream>
#include <algorithm>
#include <cmath>
#include <queue>
#include <stack>
#include <vector>
#include <map>
#include <set>
#include <iomanip>
#include <iostream>
#include <sstream>
using namespace std;
#define maxn 1000003
#define MOD 1000000007
#define mem(a , b) memset(a , b , sizeof(a))
#define LL __int64
LL a ,b;

LL gcd(LL a , LL b)
{
    if(b == 0) return a;
    else return gcd(b , a%b);
}

void gcd2(LL a , LL b , LL &d ,LL &x , LL &y)
{
    if(!b)
    {
        d = a;
        x = 1 ;
        y = 0;
    }
    else
    {
        gcd2(b , a%b , d , y , x);
        y -= x*(a/b);
    }
}

int main()
{
    while(scanf("%I64d %I64d" , &a , &b) != EOF)
    {
        LL d , x , y;
        LL g = gcd(a , b);
        if(g != 1)
        {
            printf("sorry\n");
            continue;
        }
        gcd2(a , b , d , x , y);
        x /= d;
        y /= d;
        LL t1 = b / d;
        LL t2 = a / d;
        x = (x % t1 + t1) % t1;     //找到最小正整数x
        y = (1 - a * x) / b;     //对应的y;
        printf("%I64d %I64d\n" ,x , y);
    }
   /* std::string name("12345 56789 56789");
    string age = "27";
     stringstream os;
     os << name;
     while(os >> age)
     // age = 12345
     cout<<age<<endl;*/
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值