Reuse the smaller primes we found and only try divisions by them instead of every number. Also technically we only need to try up to sqrt(n) which is usually less than n//2 + 1.
sqrt(n)
n//2 + 1
import math def nth_prime(n: int) -> int: primes = [2] m = 3 while len(primes) < n: j = 0 sqrt_m = math.sqrt(m) is_prime = True while primes[j] <= sqrt_m: if m % primes[j] == 0: is_prime = False break j += 1 if is_prime: primes.append(m) m += 1 return primes[-1] print(nth_prime(10001))
It can save time and space complexity.
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Reuse the smaller primes we found and only try divisions by them instead of every number. Also technically we only need to try up to
sqrt(n)
which is usually less thann//2 + 1
.It can save time and space complexity.