在python中找到第n个素数 [英] finding nth prime in python

查看:304
本文介绍了在python中找到第n个素数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用 Python 编写了以下代码段来查找第 n 个数字.我不明白为什么它不起作用.能否请您只给我一个提示或指出到底是哪一点弄乱了它,而不是一个完整的解决方案.

I wrote the following segment of code in Python to find the nth number. I don't understand why it doesn't work. Can you please only give me a hint or point out exactly which bit is messing it up rather than a complete solution.

term = int(input("What prime do you want to find?   "))
prime_list=[2]

def prime_search(term):
    x=3
    while len(prime_list) <= term:
        if all(x % y != 0 for y in range(2,x)):
            prime_list.append(x)
        x += 1
    return prime_list[term-1]

prime_search(term)

推荐答案

你不要打印任何东西.您的功能有效.

Your dont print anything. Your function works.

term = int(input("What prime do you want to find?   "))
prime_list=[2]

def prime_search(term):
    x=3
    while len(prime_list) <= term:
        if all(x % y != 0 for y in range(2,x)):
            prime_list.append(x)
        x += 1
    return prime_list[term-1]

print(prime_search(term))

输出:

What prime do you want to find?   5
11

但是,如果您真的想使用它,我建议您查找主筛.

However i advise you to look up prime sieve if you really want to use this.

这篇关于在python中找到第n个素数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆