gpt4 book ai didi

python - 为什么即使范围很大,这段 Python 代码也不给我一个解决方案?

转载 作者:太空宇宙 更新时间:2023-11-04 10:40:06 25 4
gpt4 key购买 nike

下面是我要解决的问题:

2520 是可以被 1 到 10 中的每一个数整除而没有余数的最小数。能被 1 到 20 的所有数字整除的最小正数是多少?

这是欧拉计划 (http://projecteuler.net/problem=5) 的第 5 个问题。我用 Python 写了一段代码来找出这个数字,但我无法获得解决方案。

我的代码是:

def smallestNumber():
smallest=0 ## Initializing the smallest number
end=False ## Initializing the break condition for lower level For loop
found=False ## Initializing the break condition for upper level For loop
for i in range(21,10000000): ## Upper level for loop
if i==10000000 and found==False: break ## This will break upper loop when range is satisfied
for k in range(1,20): ## Lower level for loop
if end==True: break ## This will break lower loop when range is satisfied
if i%k==0: ## If condition to check whether current i value is divisible evenly by current k value
if k==20: ## If k==20, this will make smallest equal to current i value and make both break conditions True
smallest=i
end=True
found=True
k=k+1
else: ## if not divisible, this will increment upper level loop
break
i=i+1

if found==False: print 'No value exists in this range'
else: return smallest

(我是 stackoverflow 的新手,无法在不弄乱格式的情况下粘贴实际代码。对于由此造成的任何不便,我深表歉意)。

无论我的范围有多大,我都会不断收到“此范围内不存在任何值”的输出。我猜想虽然我的逻辑没问题,但由于我是 Python 初学者,我在某处搞砸了代码。

如果有人能帮助我,那就太好了。

谢谢

最佳答案

一些错误的地方:

  1. 答案大于您的上限 10000000
  2. 你应该在 Python 2 中使用 xrange,否则如果你增加上限你会出现内存错误
  3. 如果你想要从 1 到 20 的所有数字,你应该使用 range(1, 21)
  4. 您不应该手动增加循环计数器,rangexrange 会为您完成

关于python - 为什么即使范围很大,这段 Python 代码也不给我一个解决方案?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21151166/

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