您的位置:首页 > 编程语言 > Python开发

最小公倍数

2016-07-14 00:00 232 查看
问题描述:

求任意3个整数的最小公倍数。

我的代码:

def GCD(m, n):
if n > m: m, n = n, m
while True:
m, n = n, m % n
if n == 0: break
return m
m=int(raw_input("please input the first number: "))
n=int(raw_input("please input the second number: "))
p=int(raw_input("please input the third number: "))

gcd1=GCD(m,n)
lcm1=m*n/gcd1

gcd2=GCD(lcm1,p)
lcm2=lcm1*p/gcd2

print "%d and %d and %d Least common multiple is: %d" % (m,n,p,lcm2)


我的思路:

求最小公倍数有多种方法如分解质因数法,公式法等,想来想去还是觉得公式法简单点,上一次做了最大公约数,直接拿过来用,而公式法就是最小公倍数=两数成绩/其最大公约数,所以先求两个数的最小公倍数,再求该最小公倍数和第三个数的最小公倍数;

示例代码:

a, b= (input() for i in range(3))
if b > a: a, b = b, a
if c > a: a, c = c, a
ans = a
while ans % b or ans % c:
ans += a
print ans


代码分析:

代码的两个if语句是将三个数中的最大值给a,我觉得可以直接使用a=max(a,b,c)替代,获取最大值是为了让其对较小的数进行除取余操作。代码的核心就是while ans % b or ans % c这一句,它是求b和c的公倍数的;

举例说明吧:

先算a%b

ans a b ans%b

20 20 3 20%3=2

40 20 3 40%3=1

60 20 3 60%3=0

然后再算a%c

20 20 18 20%18=2

40 20 18 40%18=4

60 20 18 60%18=6

80 20 18 80%18=8

100 20 18 100%18=10

120 20 18 120%18=12

140 20 18 140%18=14

160 20 18 160%18=16

180 20 18 180%18=0

那么a%c or a%b就是180了;

题目出处:http://www.cheemoedu.com/exercise/37
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 最小公倍数