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.
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)
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
题意:给你a和b,叫你求ax+by=1的x和y,要求是x为正整数,y为整数... 有就输出,没有就输出sorry。
题解:这里用到了扩展欧几里德算法。先用扩展欧几里德算法求出x,y然后再判断x是否大于0,如果小于0,则通过循环+b,直到x>0,在输出答案
这里给出两种代码,一种是书上的扩展欧几里德程序,一种是网上的(他们说是模板).....
代码如下:(最后打注释的主函数是开始自己打的,但是没有考虑x小于0的时候,所以wa了)
#include <stdio.h>
void gcd(int a,int b,int &d,int &x,int &y)
{
if(!b)
{
d=a;
x=;
y=;
}
else
{
gcd(b,a%b,d,y,x);
//printf("a=%d b=%d d=%d y=%d x=%d\n",a,b,d,y,x);
y-=x*(a/b);
//printf("y=-%d*(%d/%d) %d \n",x,a,b,y);
}
} int main()
{
int a,b,d,x,y;
while(scanf("%d%d",&a,&b)==)
{
gcd(a,b,d,x,y);
if(d==) //d=gcd(a,b),d为a,b的最大公约数。
{
if(x>)
printf("%d %d\n",x,y);
else
{
while(x<=) //求另外的解 例如:5x+6y=1 第一种解:x=-1,y=1 第二种 x=5 y=-4
{ // 这里通过x=x+b和y=y-a来算。 就等于 (x+b)*a+(y-a)*b 最终算式结果还是不变的
x+=b;
y-=a;
}
printf("%d %d\n",x,y);
}
}
else
printf("sorry\n");
}
return ;
}
/*int main()
{
int a,b,d,x,y;
while(scanf("%d%d",&a,&b)==2)
{
gcd(a,b,d,x,y);
//printf("%d %d %d\n",x,y,d);
if(x%d==0&&y%d==0&&x/d>0)
printf("%d %d\n",x/d,y/d);
else
printf("sorry\n");
}
return 0;
}*/
网上的:
#include<cstdio>
using namespace std;
int exgcd(int a,int b,int &x,int &y)
{
if(b==)
{
x=;
y=;
return a;
}
int r=exgcd(b,a%b,x,y);
//printf("a=%d b=%d\n",a,b);
int t=x;
//printf("t=%d\n",x);
x=y;
//printf("x=%d\n",y);
y=t-a/b*y;
//printf("y=%d\n",y);
return r;
}
int main()
{
int a,b,x,y,m;
while(scanf("%d%d",&a,&b)!=EOF)
{ m=exgcd(a,b,x,y);
if(m==)
{
while(x<)
{
x+=b;
y-=a;
}
printf("%d %d\n",x,y);
} else
printf("sorry\n");
}
return ;
}