欧几里得算法-The Euclidean Algorithm
算法简介
欧几里得算法可汗学院介绍
用于计算两个正整数的最大公约数。the Greatest Common Divisor (GCD) of two integers A and B is the largest integer that divides both A and B. The Euclidean Algorithm is a technique for quickly finding the GCD of two integers.
问题描述
我们在学习分而治之(divide and conquer. aka D&C)算法的时候,总会遇到一个案例:
-
假设你是一个农场主,有一小块矩形土地,长1680m, 宽640m. 你要将这块土地均匀地分成方块,且分出的方块要尽可能地大。
-
分析以上问题:求长和宽的最大公约数GCD 。
-
多种方法可以求得GCD, 本文介绍The Euclidean Algorithm。
The Euclidean Algorithm
The Euclidean Algorithm for finding GCD(A,B) is as follows:
- If A = 0 then GCD(A,B)=B, since the GCD(0,B)=B, and we can stop.
- If B = 0 then GCD(A,B)=A, since the GCD(A,0)=A, and we can stop.
- Write A in quotient remainder form (A = B⋅Q + R)
- Find GCD(B,R) using the Euclidean Algorithm since GCD(A,B) = GCD(B,R)
求解土地划分问题
- 求解GCD(A, B), 其中A=1680, B=640.
A != 0
B != 0
A = B * 2 + 400
因此GCD(A, B) = GCD(640, 400) - 求解GCD(A, B), 其中A=640, B=400.
A != 0
B != 0
A = B * 1 + 240
因此GCD(A, B) = GCD(400, 240) - 求解GCD(A, B), 其中A=400, B=240.
A != 0
B != 0
A = B * 1 + 160
因此GCD(A, B) = GCD(240, 160) - 求解GCD(A, B), 其中A=240, B=160.
A != 0
B != 0
A = B * 1 + 80
因此GCD(A, B) = GCD(160, 80) - 求解GCD(A, B), 其中A=160, B=80.
A != 0
B != 0
A = B *2 + 0
因此GCD(A, B) = GCD(80, 0) - 求解GCD(A, B), 其中A=80, B=0.
A != 0
B ==0
因此GCD(A, B) = 80
故此,1680和640的最大公约数为80. 以上土地可以均匀地分成80x80的方块。
算法原理证明
GCD(0, B) = B
1. 能整除B的最大整数是B
2. 任何正整数都可以整除0
3. 以上,0和B的最大公约数为B
GCD(A, 0) = A
同上
GCD(A, B) = GCD(B, R), 其中A = B * Q + R.
1. 假设GCD(A, B) = u, 即au = A, bu = B
2. A-B = (a-b)u, B = bu, 故u是A-B和B的公约数, G(A,B)<=G(A-B, B)
3. 假设GCD(A-B, B) = k, 即mk = A-B, nk = B
4. A-B + B = (m+n)*k, 故k是A和B的公约数, G(A-B, B)<=G(A, B)
5. GCD(A-B, B) <= GCD(A, B) && GCD(A, B) <=GCD(A-B, B)
7. 以上GCD(A, B) = GCD(A-B, B)
8. GCD(A-B, B) = GCD(A-B-B, B)=GCD(A-B-B-B, B)=GCD(A-B*Q, B)
即,GCD(A, B) = GCD(B, R).
Python代码实现
def gcd(a, b):
'''
Calculate the Greatest Common Divisor of integers a and b.
'''
if a == 0:
return b
elif b== 0:
return a
else:
r = a%b
return gcd(b,r)