uva 10104 Euclid Problem (数论-扩展欧几里德)
来源:互联网 发布:淘宝是日本的吗 编辑:程序博客网 时间:2024/06/05 17:30
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 617 17
Sample Output
-1 1 20 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为任意整数)
- uva 10104 Euclid Problem (数论-扩展欧几里德)
- UVa Problem 10104 Euclid Problem (欧几里德问题)
- UVA 10104 - Euclid Problem
- uva 10104 - Euclid Problem
- UVa 10104 - Euclid Problem
- UVA, 10104 Euclid Problem
- Uva 10104 Euclid Problem |x|+|y|最小解 扩展欧几里得
- UVa Problem Solution: 10104 - Euclid Problem
- uva 10104 (扩展欧几里德算法)
- RSA公钥加密+(Euclid)欧几里德扩展算法
- [数论]青蛙约会 (扩展欧几里德)
- 数论扩展欧几里德基础习题(4.15)
- 数论/扩展欧几里德算法
- 扩展欧几里德---数论
- 【数论】[总结]扩展欧几里德算法
- 数论初步之扩展欧几里德
- 初等数论-扩展欧几里德算法
- UVA 10368 - Euclid's Game(数论+博弈)
- 内存中堆栈
- 鼠标API
- 黑马程序员_GUI
- C#EXCEL 操作类--C#DataToExcel帮助类
- 屏幕适配问题
- uva 10104 Euclid Problem (数论-扩展欧几里德)
- VS2013自带打包部署教程
- 学习笔记之 Xpath用法
- 自定义标签技术
- .NET Framework源码研究系列之---Delegate
- javaweb-基础
- HDU 4398 whosyourdaddy 精确覆盖,允许重复覆盖
- zoj 3538 Arrange the Schedule
- Android关机流程解析---从reboot说起