Romantic (扩展欧几里德算法)

来源:互联网 发布:百分百qq营销软件 编辑:程序博客网 时间:2024/06/08 16:49

HDU 2669 http://acm.hdu.edu.cn/showproblem.php?pid=2669

Romantic

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 3061    Accepted Submission(s): 1196


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.
 

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 5110 4434 79
 

Sample Output

2 -3sorry7 -3

扩展欧几里德算法(摘自百度百科:扩展欧几里德算法):

对于不完全为 0 的非负整数 a,b,gcd(a,b)表示 a,b 的最大公约数,必然存在整
数对 x,y ,使得 gcd(a,b)=ax+by。
//c++语言实现(由于代码格式和数据范围的原因,做了改动)long long exgcd(long long a,long long b,long long &x,long long &y){    if(b==0)    {        x=1;        y=0;        return a;    }    long long r=exgcd(b,a%b,x,y);    long long t=x;    x=y;    y=t-a/b*y;    return r;}


求解 x,y的方法的理解
设 a>b。
1,显然当 b=0,gcd(a,b)=a。此时 x=1,y=0;
2,ab<>0 时
设 ax1+by1=gcd(a,b);
bx2+(a mod b)y2=gcd(b,a mod b);
根据朴素的欧几里德原理有 gcd(a,b)=gcd(b,a mod b);
则:ax1+by1=bx2+(a mod b)y2;
即:ax1+by1=bx2+(a-[a/b]*b)y2=ay2+bx2-[a/b]*by2;
也就是ax1+by1==ay2+b(x2-[a/b]*y2);
根据恒等定理得:x1=y2; y1=x2-[a/b]*y2;
这样我们就得到了求解 x1,y1 的方法:x1,y1 的值基于 x2,y2.
上面的思想是以递归定义的,因为 gcd 不断的递归求解一定会有个时候 b=0,所以递归可以结束。

扩展欧几里德定理:对于不完全为 0 的非负整数 a,b,必然存在整数对 x,y ,使得 gcd(a,b)=ax+by。

对于方程aX+bY=c,有解的条件是gcd(a,b)|c。否则的话由于方程左边是gcd(a,b)的倍数,右边c不是,方程无解。

以下讨论有解的情况:对于方程aX+bY=gcd(a,b),可以由扩展欧几里德算法求出一组解(x0,y0),方程aX+bY=c的通解公式为(x0-kb,y0+ka);(具体证明可以搜到)

这个题目中c=1,因此要使方程aX+bY=c有解,必须有gcd(a,b)|1,即gcd(a,b)=1,否则无解,再由扩展欧几里德算法求出aX+bY=gcd(a,b)的一组解,由特解公式求出最小的非负整数x和整数y。代码如下:

 #include<stdio.h>#include<iostream>using namespace std;long long exgcd(long long a,long long b,long long &x,long long &y){    if(b==0)    {        x=1;        y=0;        return a;    }    long long r=exgcd(b,a%b,x,y);    long long t=x;    x=y;    y=t-a/b*y;    return r;}int main(){    long long a,b,x,y;    while(cin>>a>>b)    {        if(exgcd(a,b,x,y)==1)        {            while(x<0)            {                x+=b;                y-=a;            }            cout<<x<<' '<<y<<endl;        }        else printf("sorry\n");    }    return 0;}


0 0