您的位置:首页 > 其它

扩转欧几里得算法 hdu 2669 Romantic

2013-12-29 21:15 330 查看

Romantic

[b]Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)

Total Submission(s): 2575 Accepted Submission(s): 1018

[/b]

[align=left]Problem Description[/align]

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.

[align=left]Input[/align]

The input contains multiple test cases.

Each case two nonnegative integer a,b (0<a, b<=2^31)

[align=left]Output[/align]

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.

[align=left]Sample Input[/align]

77 51
10 44
34 79


[align=left]Sample Output[/align]

2 -3
sorry
7 -3


扩转欧几里得算法是 用来在已知a,b

求解一组p,q使得p*a+q*b=Gcd(a,b)

(解一定存在,根据数论中的相关定理)。

因为Gcd(a,b)=Gcd(b,a%b)

所以p*a+q*b=Gcd(a,b)=Gcd(b,a%b)=p*b+q*a%b=

p*b+q*(a-a/b*b)=q*a+(p-a/b*q)*b; //注意此处a/b舍去了小数位,a-a/b*b即是a%b

这样就将a,b的线性组合化简b为a%b与的线性组合.

根据我们前面的结论:

a,b都在减小,当b减小到0时,

我们就可以得出p=1,q=0;

然后递归回去就可以求出最终的p,q了

<pre name="code" class="cpp">#include<stdio.h>
int extended_gcd(int a,int b,__int64 &x,__int64 &y)
{
__int64 ret,tmp;
if(!b)
{
x=1;
y=0;
return a;
}
ret=extended_gcd(b,a%b,x,y);
tmp=x;
x=y;
y=tmp-a/b*y;      //注意y在后面
return ret;
}
int main()
{
int a,b;
__int64 d,x,y;
while(scanf("%d%d",&a,&b)!=-1)
{
d=extended_gcd(a,b,x,y);
if(d!=1)
printf("sorry\n");
else
{
if(x<0)
x+=b;
printf("%I64d %I64d\n",x,(1-a*x)/b);
}
}
return 0;
}



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: