uva 10104 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 XY 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为任意整数)



转载于:https://www.cnblogs.com/toyking/p/3797325.html

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值