Ad

# I Want To Fine 6th Prime Number. Why Execution Is Stuck After 3?

Q: By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10001st prime number?

My code is:

```
def is_prime(num):
if all(num % i != 0 for i in range(2, num)):
return True
else:
return False
def find_nth_prime(nth):
lst_prime = []
num = 2
while len(lst_prime) < nth:
if is_prime(num):
lst_prime.append(num)
print(len(lst_prime), ":", lst_prime[-1])
num += 1
```

When I try to run `find_nth_prime(6)`

it get stuck after finding "3" as prime. What am I missing here?

Ad

## Answer

In your if statement inside while loop it keeps repeating at `n=4`

since `n +=1`

never happens as 4 is not a prime. Therefore take it out of the if statement.

Try using https://pythontutor.com/. It helps you visualize your code

```
def find_nth_prime(nth):
lst_prime = []
num = 2
while len(lst_prime) < nth:
if is_prime(num):
lst_prime.append(num)
print(len(lst_prime), ":", lst_prime[-1])
num += 1
```

Also you can do some improvments to your `is_prime`

function. In that you don't have to take the whole range `(2, num)`

. It is enough to take the range 2 to square root of num. `(2,int(num**0.5)+1)`

or use `sqrt`

from python's `math`

library

Ad

source: stackoverflow.com

## Related Questions

- → How to configure JSON for graphql query?
- → Google couldn't fetch my sitemap.xml file
- → A lot of socket endpoints in python?
- → Historical price per minute between two timestamps for a cryptocurrency
- → How to get a value from a list of dictionaries - Python 3.7.1
- → What is the optimal way to parse these strings in Python?
- → Short Order on Binance futures testnet resulting in APIError (ReduceOnly Order is Rejected)
- → values subtracted while iterating through list has random miscalculations
- → Foreign key query error in case of custom uint64 field which was used as a primary key
- → Grouping all tests Python
- → Using #!python2 not working to run under Python 2
- → Storing last 3 scores and deleting older scores and calculating average?
- → Checking if input is in a list of numbers in python

Ad