题目:扩展欧几里得 单独列出几种情况判断
#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;
}