finding nth prime in python

馋奶兔 提交于 2020-01-30 13:27:34

问题


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)

回答1:


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))

Output:

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.



来源:https://stackoverflow.com/questions/41262631/finding-nth-prime-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!