HIT 2815 扩展欧几里得(前方高能)

题目:扩展欧几里得 单独列出几种情况判断 

#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;
typedef long long LL;

LL gcd(LL a,LL b)
{
    return b?gcd(b,a%b):a;
}
void exgcd(LL a,LL b,LL &x,LL &y)
{
    if(b==0)
    {
        x=1;
        y=0;
        return ;
    }
    exgcd(b,a%b,x,y);
    LL tmp=x;
    x=y;
    y=tmp-(a/b)*y;
}
int main()
{
    int T;
    cin>>T;
    LL a, b;
    while(T--)
    {
        cin>>a>>b;
        if(a<b) swap(a,b);
        LL w=gcd(a,b);
        if(w!=1)
        {
            cout<<"-1"<<endl;
            continue;
        }
        if(b==1&&a==2)
        {
            cout<<"1"<<endl;
            continue;
        }
        if(a==1&&b==0)
        {
            cout<<"1"<<endl;
            continue;
        }
        if(b==1)//此情况要注意 可以只用其中的一种数字 1+1-1 次坑WA了n发
        {
            cout<<"2"<<endl;
            continue;
        }
        LL x,y;
        exgcd(a,b,x,y);
        LL x1=(x%b+b)%b,y1=(1-a*x1)/b;
        LL y2=(y%a+a)%a,x2=(1-b*y2)/a;
        LL sum1=abs(x1)+abs(y1)-1,sum2=abs(x2)+abs(y2)-1;
        cout<<min(sum1,sum2)<<endl;
    }


    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值