题目
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?
解答
这道题是要求多个数的最小公倍数,首先是得实现2个数的最小公倍数,然后循环一下就可以了。而2个数的最小公倍数,那就是2个数的乘积除以最大公约数。
而最大公约数可以用辗转相除法来求得。所以我们首先把最大公约数和最小公倍数的函数写一下。
def gcd(a, b):
return a if b == 0 else gcd(b, a % b)
def lcm(a, b):
return a * b / gcd(a, b)
有了最小公倍数的函数,就正如开头写的,循环一下出答案。
def solution5(n):
res = n
for i in range(1, n):
res = lcm(res, i)
return res
