标签:
Description
Input
Output
Sample Input
Sample Output
#include <iostream>
#include <cstdio>
using namespace std;
//x*a+y*b=GCD(a,b)=GCD(b,a%b)=x*b+y*(a%b)=x*b+y*(a-a/b*b)=y*a+x*b-a/b*y*b=y*a+(x-a/b*y)*b
//即得到一次辗转相除后 x=y;y=x-a/b*y;
int extend_euclid(int a,int b,int &x,int &y) //扩展欧几里德,能用64位尽量64位用32位可能超范围
{
int res, tmp;
if (!b)
{
x=1;
y=0;
return a;
}
res = extend_euclid(b, a%b,x, y);
tmp = x-a/b*y;
x = y;
y = tmp;
return res;
}
int main()
{
int a,b,x,y,z;
while(scanf("%d%d",&a,&b)!=EOF)
{
z=extend_euclid(a,b,x,y); //z即为a,b的最大公约数
if(z==1)
{
while(x<0)
{
x=x+b/1; //这里将x最小非负整数化(x可为0)
y=y-a/1; //运用a*x+b*y=1得到y
}
cout<<x<<" "<<y<<endl;
}
else
cout<<"sorry"<<endl;
}
return 0;
}
标签:
原文地址:http://www.cnblogs.com/xinxiangqing/p/4740012.html