您的位置:首页 > 编程语言 > Go语言

Euclid‘s algorithm

2016-03-01 22:42 489 查看
这算是TAOCP的读书笔记吧,这次写的主要是卷一的Euclid‘s algorithm。

以下是一些书上的摘录和C语言代码的实现:

算法要求:

Give two positive integers m and n, find their greatest common divisor,that is,the largest positive integer that evenly divides both m and n.
对于给定的两个正整数m和n,找到相应的最大公约数。

描述1:

E1:[Find remainder.]Divide m by n and let r be the remainder.
                
                   (We
will have 0<=r<n.)
E2:[Is it zero?]If r=0,the algorithm terminates; n is the answer.
E3:[Reduce.]Set m<-n,n<-r,and go back to step E1.II

描述2:

int Eucild(int m,int n)
{
r=m%n;
while(r)
{
m=n,n=r;
r=m%n;
}
return n;
}



证明:

After step E1,we have
    m=q*n+r,

for some integer q.If r=0,then m is a multiple of n,and clearly in such a case n is the greatest common divisor of m and n.If r != 0,note that any
number that divides both m and n must divide m-q*n = r,and any number
that divides both n and r must divide q*n+r = m; so the set of common divisors of {m,n} is the same as the set of common divisors of {n,r}.

对于 m 和 n 有 m = q * n + r ;
当 r 为 0 时,m 和 n 有公约数 q ;
当 r 不为 0 时,设 m 和 n 的公约数是 d ,则有(m - q * n)能被 d 整除, 那么 r 也能被 d 整除。又因为 r = m%n ,所以 GDC(m,n)=GCD(n,m%n)。直到 r 为 0 时,就是最大公约数 GCD(m,n)。

鉴于本人英语能力的不足,如有不当之处希望各位大神指点。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: