gpt4 book ai didi

python - 能被1到20的所有数整除的最小正数?

转载 作者:太空宇宙 更新时间:2023-11-04 07:19:50 24 4
gpt4 key购买 nike

我的代码有什么问题?当我运行程序时,没有打印任何内容。我想打印能被 1 到 20 的所有数字整除的最小数字。

found = False
i = 20
while found==False:
c = 0 # c checks if the number is the one im looking for
for x in range(1,21):
if i%x==0:
c = c + 1
if c==20: # if c = 20 then its the number im looking for
print i
found = True
i = i + 1

最佳答案

蛮力:

from itertools import count
for i in count(20):
if all(map(lambda x: i % x == 0, range(1, 21))):
print i
break

非暴力破解:

from itertools import count, takewhile

def primes(n):
"Generate prime numbers up to n"
seen = list()
for i in xrange(2, n + 1):
if all(map(lambda prime: i % prime, seen)):
seen.append(i)
yield i

def smallest(n):
result = 1
for prime in primes(n):
bprime = max(takewhile(lambda x:x<=n, (prime ** c for c in count(1))))
# we could just take last instead of max()
result *= bprime
return result

print smallest(20)

关于python - 能被1到20的所有数整除的最小正数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22711505/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com