python - 如何让这段 Python 代码运行得更快? [欧拉计划问题 #7]

标签 python performance interpreter

我正在尝试完成这个 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/

相关文章:

python - matplotlib 子图未显示

python - 卡固定满足 FITS 标准是什么意思?

c - "const"有成本吗?

performance - C# 和 C++ 可以互操作高性能代码吗?

python - 如何将 python 模块加载到 Komodo 中的新交互式 shell 中?

python - PyCharm - 无法使用远程解释器

python - 将数组的行连接成一维数组的有效算法方法

python - 将两个相关的 DataFrame 列拆分为两个新的 DataFrame

java - 多线程Java

python - 如何向 PyCharm 添加解释器?