我正在尝试完成这个 Project Euler 挑战:
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10 001st prime number?
我的代码似乎是正确的,因为它适用于小数字,例如第 6 个素数是 13。
我怎样才能改进它,以便代码对于更大的数字(例如 10 001)运行得更快。
代码如下:
#Checks if a number is a prime
def is_prime(n):
count = 0
for i in range(2, n):
if n%i == 0:
return False
break
else:
count += 1
if count == n-2:
return True
#Finds the value for the given nth term
def term(n):
x = 0
count = 0
while count != n:
x += 1
if is_prime(x) == True:
count += 1
print x
term(10001)
更新:
感谢您的回复。我应该更清楚,我不是要加快解释器的速度或寻找更快的解释器,因为我知道我的代码不是很好,所以我一直在寻找使我的代码更高效的方法。
最佳答案
需要思考的几个问题:
- 你真的需要检查除法直到 n-1 吗?你能提前多久停止?
- 除了 2,您真的需要检查所有 2 的倍数的除法吗?
- 3 的倍数呢? 5?有没有办法将这个想法扩展到所有以前测试过的素数的倍数?
关于python - 如何让这段 Python 代码运行得更快? [欧拉计划问题 #7],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6789649/