Home > Software design >  I want to fine 6th prime number. why execution is stuck after 3?
I want to fine 6th prime number. why execution is stuck after 3?

Time:02-20

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?

CodePudding user response:

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

  • Related