欧几里得算法是求两个数的最大公约数的一种方法。
"""
欧几里得算法是求两个数的最大公约数的一种方法。
"""
def compute_gcd(a, b):
"""
使用欧几里得算法计算两个整数的最大公约数。
参数:
a (int): 第一个整数。
b (int): 第二个整数。
返回值:
int: 两个整数的最大公约数。
"""
# 找出较大和较小的数
larger_number = max(a, b)
smaller_number = min(a, b)
# 如果较小数为0,返回较大数作为GCD
if smaller_number == 0:
return larger_number
# 计算较大数除以较小数的余数
remainder = larger_number % smaller_number
# 如果余数为0,则较小数即为最大公约数
if remainder == 0:
return smaller_number
# 如果余数不为0,则递归调用函数计算较小数和余数的最大公约数
return compute_gcd(smaller_number, remainder)
# 测试代码
def test_compute_gcd():
test_cases = [
(48, 18, 6), # 示例:48 和 18 的最大公约数是 6
(101, 103, 1), # 示例:101 和 103 的最大公约数是 1(质数)
(56, 98, 14), # 示例:56 和 98 的最大公约数是 14
(12, 15, 3), # 示例:12 和 15 的最大公约数是 3
(0, 25, 25), # 示例:0 和 25 的最大公约数是 25
(25, 0, 25) # 示例:25 和 0 的最大公约数是 25
]
for a, b, expected in test_cases:
result = compute_gcd(a, b)
assert result == expected, f"Test failed for {a}, {b}: expected {expected}, got {result}"
print(f"GCD of {a} and {b} is {result}, expected {expected}")
# 运行测试代码
test_compute_gcd()
GCD of 48 and 18 is 6, expected 6
GCD of 101 and 103 is 1, expected 1
GCD of 56 and 98 is 14, expected 14
GCD of 12 and 15 is 3, expected 3
GCD of 0 and 25 is 25, expected 25
GCD of 25 and 0 is 25, expected 25