Euclid Problem-ACM

算法:假设a>b, ax1+by1=gcd(a,b), 那么bx2+(a-a/b*b)y2=gcd(b,a%b). 根据欧几里德定律可知,gcd(a,b)=gcd(b,a%b), 所以ax1+by1=bx2+(a-a/b*b)y2 =>ay2+bx2-a/b*by2. 又因为相应的项的系数是相等的,所以x1=y2, y1=x2-a/by2, 以些类推,运用递归方法,直到b的系数为0为止。

// Euclid Problem.cpp : Defines the entry point for the console application. // #include "stdafx.h" using namespace std; int x,y; int _tmain(int argc, _TCHAR* argv[]) { void Euclid(unsigned int a,unsigned int b); unsigned int a=0; unsigned int b=0; while(cin>>a>>b) { if(a==0&&b==0)break; else { if(b>a)swap(a,b); Euclid(a,b); cout<<x<<" "<<y<<" "<<a*x+b*y<<"/n"; } } return 0; } void Euclid(unsigned int a,unsigned int b) { if(b==0) { x=1; y=0; } else { Euclid(b,a%b); int tmp=x; x=y; y=tmp-a/b*y; } }  

你可能感兴趣的:(算法)