【发布时间】:2018-09-06 14:32:55
【问题描述】:
我的代码有问题,我使用eratosthenes这个函数来创建一个列表,我只是制作了一个大内存大小列表(1000000),在主要我输入codeforces input()并让他们sqrt( ),所以,我不知道为什么我的代码时间限制超过 2000 毫秒,请帮我解决这个问题。
import math
def eratosthenes(n): # creative the prime list
IsPrime = [True] * (n + 1)
IsPrime[1] = False
for i in range(2, int(n ** 0.5) + 1):
if IsPrime[i]:
for j in range(i * i, n + 1, i):
IsPrime[j] = False
return [x for x in range(2, n + 1) if IsPrime[x]]
# main code
input()
li = list(map(int, input().split()))
nl = eratosthenes(1000000)
for i in li:
i = math.sqrt(i)
if int(i) == i:
print("YES" if i in nl else "NO")
else:
print("NO")
当我引用别人的代码时,我认为我的代码的运行时间与其他代码相似,否则我错了。
【问题讨论】:
-
为什么
return [x for x in range(2, n + 1) if IsPrime[x]]是缩进的?这会在第一个数字之后返回吗?这应该在 for 循环之外吗? -
你如何满足输入()?这只是在等待用户输入数字,还是在 stdin 上提供输入?
-
你的第一个 munber 是 0 还是 2 ?它返回就像 [2, 3, 5, 7, 11.....]
-
我在 codeforces 上做,他们会给我一些 input() link
-
很难说你的实际代码是什么样子的,因为缩进在问题中被破坏了。你能纠正一下吗?我看到两个不必要的工作实例:从
IsPrime创建列表,然后在该列表中进行线性搜索。为了测试一个数字是否为素数,IsPrime列表本身已经可以使用了。
标签: python sieve-of-eratosthenes time-limiting