简体   繁体   中英

Problem with finding 10,001th prime number: 1 off

"""7. 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?"""
countprime=0
n=2
def prime(number):
    for factors in range(2, number):
        if number%factors==0:
            return False
            break
    return True

while countprime!=10001:
    if prime(n)==True:
        countprime+=1
    n+=1
print(n)

The answer is supposed to be 104743, but for some reason my brute force program gets 104744, 1 more. Does anyone know why it is one off?

while countprime != 10001:
    if prime(n)==True:
        countprime+=1
    n+=1

When you find a prime number, you always move on to the next number. So, after finding the correct answer, you add up 1 and get 104744. Try to firstly add 1, and then check if it's prime.

Here is an example:

n = 1
while countprime != 10001:
    n += 1
    if prime(n):
        countprime += 1

You need to break your loop immediately when countprime == 10001 to leave your variable n untouched. A possible way:

while True:
    countprime += prime(n)
    if countprime == 10001:
        break
    n += 1

After your program finds the 10001th prime, the value of n is increased by 1 therefore your output is 1 more than the expected answer.

If you use print(n-1) , your program will behave as expected.

You're increasing n one last time before your loop exits. If you increase n before checking if it's prime then your countPrime counter and the corresponding prime number will stay in sync (but you'll have to start n at 1 instead of 2):

n = 1
while countprime != 10001:
    n += 1
    if prime(n):
        countprime += 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