Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading