Problem Description
The Sky is Sprite.
The Birds is Fly in the Sky.
The Wind is Wonderful.
Blew Throw the Trees
Trees are Shaking, Leaves are Falling.
Lovers Walk passing, and so are You.
................................Write in English class by yifenfei
Girls are clever and bright. In HDU every girl like math. Every girl like to solve math problem!
Now tell you two nonnegative integer a and b. Find the nonnegative integer X and integer Y to satisfy X*a + Y*b = 1. If no such answer print "sorry" instead.
The Birds is Fly in the Sky.
The Wind is Wonderful.
Blew Throw the Trees
Trees are Shaking, Leaves are Falling.
Lovers Walk passing, and so are You.
................................Write in English class by yifenfei
![](https://i-blog.csdnimg.cn/blog_migrate/50d0d5b948acfeebc45f5f1ccb8eaa48.jpeg)
Girls are clever and bright. In HDU every girl like math. Every girl like to solve math problem!
Now tell you two nonnegative integer a and b. Find the nonnegative integer X and integer Y to satisfy X*a + Y*b = 1. If no such answer print "sorry" instead.
Input
The input contains multiple test cases.
Each case two nonnegative integer a,b (0<a, b<=2^31)
Each case two nonnegative integer a,b (0<a, b<=2^31)
Output
output nonnegative integer X and integer Y, if there are more answers than the X smaller one will be choosed. If no answer put "sorry" instead.
Sample Input
77 51
10 44
34 79
Sample Output
2 -3
sorry
7 -3
由连分数可知ax-by=d的一组解为
x=(-1)^n-1*Q[n-1];
y=(-1)^n-1*P[n-1];
通解为X=x+b/d*t;
Y=y-a/d*t;
t为整数;
代码如下:
#include<stdio.h>
#include<math.h>
int main()
{
int a,b,q[1000],P[1000],Q[1000],t,m,x,y,n,i,j,flag,k;
while(~scanf("%d %d",&a,&b))
{
t=0;
x=a>=b?a:b;
y=a<b?a:b;
do
{
m=x%y;
q[t]=x/y;
x=y;
y=m;
t++;
}while(m!=0);
if(x==1)
{
P[0]=1;
P[1]=q[0];
Q[0]=0;
Q[1]=1;
for(i=2;i<t;i++)
{
P[i]=q[i-1]*P[i-1]+P[i-2];
Q[i]=q[i-1]*Q[i-1]+Q[i-2];
}
flag=((t-1)%2==0)?1:-1;
j=flag*P[i-1];
k=-1*flag*Q[i-1];
m=(a>=b)?k:j;
n=(a<b)?k:j;
if(b<0)
t=ceil(m*1.0/(b*1.0));
else
t=floor(m*1.0/(b*1.0));
x=m-b*t;
y=n+a*t;
printf("%d %d\n",x,y);
}
else
printf("sorry\n");
}
return 0;
}