`
诗意的栖居
  • 浏览: 273913 次
  • 性别: Icon_minigender_2
  • 来自: 北京
社区版块
存档分类
最新评论

No.5 The smallest positive number

 
阅读更多
Q:
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.

What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?


A:
''' method 1
    最小公倍数一定是最大的数的倍数
'''

p = 20
flag = True
while flag:
    for i in range(1,21):
        if p % i:
            p += 20
            break
        elif i == 20:
            flag = False

print p

''' method 2
    两两找最小公倍数,a与b的最小公倍数一定是a*[1~b],这里取了i从2520开始,是因为直到20以内不可能有,通用的还是从1开始
    so fast
'''

i = 2520
for k in range(1,21):
    if i % k > 0:
        for j in range(1,21):
            if (i*j)%k == 0:
                i *= j
                break
print i

'''
    method 3
    两两找最小公倍数,最小公倍数是由a*b/最大公约数得到的,gcd()是取最大公约数的方法
'''

def gcd(a, b):
    while b != 0:
        a, b = b, a % b
    return a
def lcm(a, b): return a*b/gcd(a, b)
print reduce(lcm, range(1, 20+1))
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics