题目链接:http://acm.hust.edu.cn/vjudge/contest/view.action?cid=88159#problem/I
题意:
给你两个数a,b,是否有这样两个数x,y,使得ax+by=1方程成立,如果有输出x最小的一组数。x为非负整数。
案例:
input
77 51
10 44
34 79
output
2 -3
sorry
7 -3
思路分析:
当a,b的公约数不为1时,是没有整数解的。
详细思路可以进这个网页去了解。http://www.cnblogs.com/yuelingzhi/archive/2011/08/13/2137582.html
需要注意的是,求出的x可能是负数,所以当x<0时,要让加上b,而y要减a。
源代码如下:
1 #include<iostream> 2 #include<cstdio> 3 using namespace std; 4 void gcd(int a,int b,int &d,long long &x,long long &y) 5 { 6 if(!b) {d=a;x=1;y=0;} 7 else {gcd(b,a%b,d,y,x);y-=x*(a/b);} 8 } 9 int main() 10 { 11 int a,b,d; 12 long long x,y; //必须为longlong型 13 while(scanf("%d%d",&a,&b)!=EOF) 14 { 15 gcd(a,b,d,x,y); 16 if(d!=1) printf("sorry\n"); 17 else 18 { 19 while(x<0) 20 { 21 x+=b; 22 y-=a; 23 } 24 printf("%lld %lld\n",x,y); 25 } 26 } 27 return 0; 28 }