Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
294 views
in Technique[技术] by (71.8m points)

if statement - Python script to find nth prime number

I'm new to Python and I thought I'd try to learn the ropes a bit by writing a function to find the nth prime number, however I can't get my code to work properly. No doubt this is due to me missing something fundamental, but I'd appreciate your help in finding where it went wrong!

c=2
n=input("Which prime would you like? ")
n=int(n)
a=[]
l=len(a)

while l<=n:
    if c==2:
        a.append(c)
    elif (c % 2 ==0): #c is even
        break
    elif (c % 2 !=0): #c is odd
        if c<7:
            a.append(c)
        elif c >=7:
            for i in range(3,int((c+1)/2)):
                if (c % i ==0):
                    break
            else:
                a.append(c)
    else:            
        c+=1
a[n]

Thanks! Andrew

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This can be a start. This checks whether the number N is divisible by all numbers from 2 to int(sqrt(N)) + 1, where the int function truncates the square root of N. The all() function in python returns True if all members of a list satisfy some condition (here not zero). You should set an upper bound as this is not very efficient for really large n. I'll leave that to you.

def nthprime(n):
    import math
    start = 2
    count = 0
    while True:
        if all([start % i for i in range(2, int(math.sqrt(start)) + 1)]) != 0:
            count += 1
            if count == n:
                return start
        start += 1 



In [91]: nthprime(50)
Out[91]: 229

In [92]: nthprime(100)
Out[92]: 541

Tested with this.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...