我需要找到10000以下最长的非素数行
如何只打印输出中的最后一行? 没有最大值函数,没有简单的数值约束
我认为它只需要一些小的调整,只是不知道在哪里或如何
priemen = []
for x in range(2,10000): #prime generator
tel = 0
for deler in range(1,x):
if x % deler == 0:
tel += x % deler == 0
if tel <2:
priemen.append(x)
a = priemen[0]
b = priemen[1]
maxrow = 0
for next in priemen[2:]:
a = b
b = next
row = b - a - 1
if row > maxrow:
maxrow = row
print("The longest row starts at", a+1, "and stops at", b-1, "and is", maxrow, "long.")
------------------
Output:
The longest row starts at 8 and stops at 10 and is 3 long.
The longest row starts at 24 and stops at 28 and is 5 long.
The longest row starts at 90 and stops at 96 and is 7 long.
The longest row starts at 114 and stops at 126 and is 13 long.
The longest row starts at 524 and stops at 540 and is 17 long.
The longest row starts at 888 and stops at 906 and is 19 long.
The longest row starts at 1130 and stops at 1150 and is 21 long.
The longest row starts at 1328 and stops at 1360 and is 33 long.
The longest row starts at 9552 and stops at 9586 and is 35 long.
我只需要打印最后一张
谢谢
我看到了这段代码的低效和问题。首先,它测试从1到
x
的除数是低效的当它只需要测试从3到^{的平方根的奇数除数(处理偶数后)。但是,即使这样做也是低效的,因为它正在创建一个素数列表,它可以用它作为除数来加快速度!最后,就效率而言,我相信这可以一次完成:
最后,就目标而言,问题没有明确规定,解决方案可能是错误的。考虑9586的目标,而不是10000。编写的代码将打印:
但通过在主循环之后添加以下代码:
我们得到了正确的答案:
如果目标更大,跑步时间会更长,但这仍然是最长的跑步时间
您需要将
a
和b
的值保存到单独的变量中,以便在循环后打印它们其他需要注意的事项:
a_max
和b_max
-但是最后的if
测试是为了防止任何尚未设置它们的情况next
重命名为n
,因为next
是内置的名称a = priemen[0]
行毫无意义,因此我已将其删除相关问题 更多 >
编程相关推荐