Python程序教程

您现在的位置是:首页 >  Python

当前栏目

python—最大公约数和最小公倍数

python,最大公约数,最小,公倍数
2025-03-25 08:59:29 时间

大家好,又见面了,我是你们的朋友全栈君。

最大公约数

def hcf(x, y):
	if x <= 0 or y <= 0:
		return 
	res = 0
	if x > y:
		small = y
	else:
		small = x
	for i in range(1,small+1):
		if x % i ==0 and y % i == 0:
		 	res = i
if __name__ == '__main__':
	print(hcf(12,24))	
# 内置模块
import math
math.gcd(12,24)

最小公倍数

两数乘积除以最大公约数

def lcm(num1, num2):
	if x == y == 0:
		return 0
	return num1 * num2 // math.gcd(num1, num2)

注意:在python3.9中引入了模块

import math
math.lcm(49, 14) #98

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/145804.html原文链接:https://javaforall.cn