Python I';我不明白为什么下面的代码没有给我答案?
运行最小除数的代码:Python I';我不明白为什么下面的代码没有给我答案?,python,Python,运行最小除数的代码: def smallesteuler(): t=0 result=[] for no in range(11,10000): for i in range(1,11): if (no%i==0): t=t+1 if(t==20): return result.append(no) t=0 print (smal
def smallesteuler():
t=0
result=[]
for no in range(11,10000):
for i in range(1,11):
if (no%i==0):
t=t+1
if(t==20):
return result.append(no)
t=0
print (smallesteuler())
看起来您正在尝试收集满足
no%i==0
的前20个数字。您必须将这些数字附加到结果
,然后返回结果
def smallesteuler():
t=0
result=[]
for no in range(11,10000):
for i in range(1,11):
if (no%i==0):
result.append(no)
t=t+1
if(t==20):
return result
print (smallesteuler())
这看起来像欧拉问题5——找到1..20的最小公倍数 您的代码可以重写为
def euler5(upto=20):
"""
Find the least common multiple of 1..upto
"""
num = upto
while True:
if all(num % factor == 0 for factor in range(2, upto+1)):
return num
else:
num += 1
然而,一个更有效的解决方案是
from fractions import gcd
from functools import reduce
def lcm(a, b):
return a * b // gcd(a, b)
def euler5(upto=20):
return reduce(lcm, range(1, upto+1))
第一个解决方案是O(n!),第二个是O(n**2)。
list.append()。