简体   繁体   English

查找第 10,001 个素数的问题:1 分

[英]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.答案应该是 104743,但由于某种原因,我的蛮力程序得到了 104744,多了 1 个。 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.所以,找到正确答案后,你加 1 得到 104744。尝试先加 1,然后检查它是否为素数。

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.countprime == 10001时,您需要立即中断循环以保持变量n不变。 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.在您的程序找到第 10001 个素数后,n 的值增加 1,因此您的 output 比预期答案多 1。

If you use print(n-1) , your program will behave as expected.如果您使用print(n-1) ,您的程序将按预期运行。

You're increasing n one last time before your loop exits.在循环退出之前,您最后一次增加了n一次。 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,那么您的 countPrime 计数器和相应的质数将保持同步(但您必须从 1 而不是 2 开始 n):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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