我正在解决一个问题(在网站上)打印第 N 个素数,其中 N 是用户输入。该问题修复了这些限制 1s,512 MB。我在下面写了那个代码。
n = int(input())
r = (n+1)**2
nth = n - 1
d = [x for x in range(2, r)]
non_prime = []
for i in range(2, r):
for x in d:
if i % x == 0 and x != 1 and x != i:
non_prime.append(i)
non_prime = list(set(non_prime))
prime_numbers = [x for x in d if x not in non_prime]
print(prime_numbers[nth])
现在代码运行良好,但提交后显示超出内存限制。如何在不过度更改我的代码的情况下解决这个问题?
(我知道有更简单的方法可以解决这个问题。但我自己解决了。)