Problem 5
2520 is the smallest number that can be divided by each of the numbers
from 1 to 10 without any remainder. 2020是可以同时被1~10整除的最小整数。 What is the
smallest positive number that is evenly divisible by all of the
numbers from 1 to 20? 那么可以同时被1~20整除的最小整数是多少?
Python
思路1
试错,从1遍历到20!,挨个数据验证,成功则输出。
但是运行较旧,程序低效
i=1
num1 = 0
for a in range (1,21):i*=a
print (i)
def zhengchu(num):
for x in range (2,21):
if num%x == 0:
if x == 20:return(num)
else:break
return(False)
while not zhengchu(num1):
num1+=1
print(num1)
print (num1)
思路2
20至1做乘法,每做一次,验证一次。
缺点:数据会偏大,造成某些数多次计算。
思路3
1~20间质数相乘,然后验证,验证某数字不通过,乘以该数字。
缺点:数据偏大,某些数多次计算。
factor = []
i=1
#求20以内质数
for n in range(2, 20):
for x in range(2, n):
if n % x == 0:
break
else:
# 循环中没有找到元素
factor.append(n)
print (factor)
for a in factor:
i*=a
print(i)
num = 1
while True:
for a in range(1,21):
if i%a == 0:
if a == 20:
print(i)
else:
i*=a
print(i,a)
else:
break
最终解法
将1~20依次相乘,并与下一个数求最小公倍数
from functools import reduce
#求两个数的最大公约数
def gcd(x, y):
while y != 0:
x , y = y, x % y
return x
#求两个数的最小公倍数
def lcm(x, y):
return x * y // gcd(x, y)
#将1~20依次相乘并求最小公倍数
print(reduce(lcm, range(1, 21)))