加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

如何让这个Python代码更快地运行? [项目欧拉问题#7]

发布时间:2020-12-20 13:05:38 所属栏目:Python 来源:网络整理
导读:我正在尝试完成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? 我的代码似乎是正确的,因为它适用于小数字,例如6th prime是13. 我如何改进它,以
我正在尝试完成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?

我的代码似乎是正确的,因为它适用于小数字,例如6th prime是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,你真的需要用两个的倍数来检查除法吗?> 3的倍数怎么样? 5?有没有办法将这个想法扩展到以前测试的素数的所有倍数?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读