给定两个正整数 x 和 y ,请编写一个函数,找出它们最小公倍数。
示例:
输入:3,5,输出:15
输入:4,18,输出:36题目难度:简单
题目来源:Udemy教程
def lcm(x: int, y: int) -> int:
pass
assert lcm(3, 5) == 15
assert lcm(4, 16) == 16
assert lcm(4, 18) == 36
给定两个正整数 x 和 y ,请编写一个函数,找出它们最小公倍数。
示例:
输入:3,5,输出:15
输入:4,18,输出:36题目难度:简单
题目来源:Udemy教程
def lcm(x: int, y: int) -> int:
pass
assert lcm(3, 5) == 15
assert lcm(4, 16) == 16
assert lcm(4, 18) == 36
public Integer lcm(Integer x,Integer y){
int max = Math.max(x, y);
int min = Math.min(x, y);
for (int i = 1; i <=min; i++) {
if ((max*i)%min == 0){
return max*i;
}
}
throw new RuntimeException("no result");
}
@Test
public void testLcm(){
assert lcm(4, 16) == 16;
assert lcm(3, 5) == 15;
assert lcm(4, 18) == 36;
}
def gcd(x: int, y: int) -> int:
# 辗转相除法求最大公约数
if x < y:
x, y = y, x
while y != 0:
x, y = y, x % y
return x
def lcm(x: int, y: int) -> int:
return x * y / gcd(x, y)
assert lcm(3, 5) == 15
assert lcm(4, 16) == 16
assert lcm(4, 18) == 36
def lcm(x: int, y: int) -> int:
max=x*y
for i in range(1,max):
if (i%x==0 and i%y==0):
return i
return max
def lcm(x: int, y: int) -> int:
max = x * y
for i in range(1, max+1):
if i % x == 0 and i % y == 0:
return i
def lcm(x: int, y: int) -> int:
i = 1
while(i):
if i % x == 0 and i % y ==0:
break
else:
i +=1
return i
assert lcm(3, 5) == 15
assert lcm(4, 16) == 16
assert lcm(4, 18) == 36
def lcm(x: int, y: int) -> int:
max_mun = max(x, y)
n = 1
while True:
common_divisor = max_mun * n
if common_divisor % x == 0 and common_divisor % y == 0:
return common_divisor
n += 1
assert lcm(3, 5) == 15
assert lcm(4, 16) == 16
assert lcm(4, 18) == 36