简体   繁体   中英

PYTHON: Finding an nth prime number

I've looked through a variety of older posts on this subject, and they have all left me confused in some way or another. So I'll start at the beginning.

The problem is #7 on Project Euler and I am a fairly new programmer trying to work my way through the problems. #7 is as follows.

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 10,001st prime number?

My issue is as follows. I have a clear understanding of what prime numbers are and how they work. The sudo-code I would write for this problem is this:

For n in range(3,n) #where n is some very large value.
if n%i ==0 for i in range(2,n-1)
return False
if n%i == 0 for i == n 
return True 

But I think my lack of knowledge when it comes to Python is impeding me in finding what I want.

In most of the other solutions I have seen, they limit n to something like 125000 and I honestly have no clue where they came up with that number from.

The other issue is I don't know how to search properly through a range and create a list of values that satisfied that relation in a manner that I can then check the Max value in the list.

The thing that would make the most sense to me would be to basically append each new prime to a list and then just take the max value, but I'm sure there is a better and faster way to do this. If you are going to answer, please include a healthy dose of explanation without jumping into python technobabble, remember, I'm a beginner in programming.

I know that the typical way people deal with questions like this is to prod the asker into finding the right answer, I don't want that. I would like someone to show me a solution and then walk through it step by step explaining what each part of the code does so that I can learn not only how to solve the problem, but also gain a better intuition for how python works.

Thanks.

This task basically asks you to gather 10001 prime numbers. So start by building a list of primes and when you reach the 10001th number display it.

Here is a sample code:

def is_prime(n):
    for i in range(3, n):
        if n % i == 0:
            return False
    return True

primes = [] # list of primes
x = 10001 # go to the nth-number
n = 2 # start at number 2

while len(primes) != x+1:  # is n-th number on the list? +1 is because list is zero-based
    if is_prime(n):
        primes.append(n)  # add prime to the list
    n+=1 # increment n to check the next number

# print the last item in the list - the n-th number
print(primes[-1])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM