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.
1
solved Python script to find nth prime number