uva 10104 Euclid Problem (数论-扩展欧几里德)
Euclid Problem
Euclid Problem |
The Problem
From Euclid it is known that for any positive integers A and B there exist such integers X and Y that AX+BY=D, where D is the greatest common divisor of A and B. The problem is to find for given A and B corresponding X, Y and D.
The Input
The input will consist of a set of lines with the integer numbers A and B, separated with space (A,B<1000000001).
The Output
For each input line the output line should consist of three integers X, Y and D, separated with space. If there are several such X and Y, you should output that pair for which |X|+|Y| is the minimal (primarily) and X<=Y (secondarily).
Sample Input
4 6 17 17
Sample Output
-1 1 2 0 1 17
题目大意:
已知 A 和 B , 问你 A*X+B*Y=GCD(A,B)的 X,Y解。
解题思路:
非常裸的拓展欧几里德算法。
拓展欧几里德算法证明过程:
因为 B*X1+A%B*Y1=GCD(B,A%B) =GCD(A,B)=A*X+B*Y
所以 B*X1+(A-A/B*B)*Y1=A*X+B*Y
A*Y1+B*(X1-A/B*Y1)=A*X+B*Y
于是: X=Y1,Y=(X1-A/B*Y1)
因此,得出( A*X+B*Y=GCD(A,B)的 X,Y解)结论:
当B=0时,GCD(A,B)=A,很明显,X=1,Y=0是解
当B!=0时,只需递归, 求B*X1+A%B*Y1=GCD(B,A%B) 的解,求出X1,Y1的解的数值之后,自然可以求出X,Y。
证明绝对值相加最小,x<y,请参照博客【转】:http://blog.csdn.net/metaphysis/article/details/6538584
解题代码:
#include <iostream> using namespace std; int x,y; int extend_gcd(int a,int b){ if(b==0){ x=1;y=0; return a; }else{ int ans=extend_gcd(b,a%b); int tmp=y; y=x-a/b*y; x=tmp; return ans; } } int main(){ int a,b; while(cin>>a>>b){ int d=extend_gcd(a,b); cout<<x<<" "<<y<<" "<<d<<endl; } return 0; }
补充:
gcd函数的基本性质:
gcd(a,b)=gcd(b,a)=gcd(-a,b)=gcd(|a|,|b|)
再补充欧几里德算法证明 why gcd(a,b)=gcd(b,a%b) ???
证明:
第一步:令c=gcd(a,b),则设a=mc,b=nc
第二步:a可以表示成a = kb + r,r =a-kb=mc-knc=(m-kn)c
第三步:根据第二步结果可知c也是r的因数
第四步:可以断定m-kn与n互素【否则,可设m-kn=xd,n=yd,(d>1),则m=kn+xd=kyd+xd=(ky+x)d,则a=mc=(ky+x)dc,b=nc=ycd,故a与b最大公约数≥cd,而非c,与前面结论矛盾】
从而可知gcd(b,r)=c,继而gcd(a,b)=gcd(b,r),
又因为a=kb+r,则r = a mod b,所以gcd(a,b)=gcd(b,a%b)得证
补充拓展欧几里德 ax+by=gcd(a,b) 所有解的通项公式:
xk = x0 + b/gcd(a, b) * k
yk = y0 - a/gcd(a, b) * k (其中k为任意整数)