Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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 inrange(2, int(math.sqrt(start)) +1)]) !=0:
            count +=1
            if count == n:
                returnstartstart+=1In [91]: nthprime(50)
Out[91]: 229In [92]: nthprime(100)
Out[92]: 541

Tested with this.

Solution 2:

Try like this?

print2for i inrange(3,1000):

    b = Falsefor j inrange(2,i):
            if i % j == 0:
                b=Trueif b == False:
        print i

Post a Comment for "Python Script To Find Nth Prime Number"